我很确定以前有人问过这个问题,但是我的情况略有不同,因为我试图将 JLabel 放在作为背景的 JLabel 之上,我想使用 JLabel 显示不断变化的数字,并且需要的数字在背景上显示,但我有点摇摆不定,提前感谢乔纳森
问问题
16696 次
3 回答
10
在不完全了解您的要求的情况下,如果您只需要在背景图像上显示文本,最好将标签放在能够绘制背景的自定义面板上。
您可以从没有混乱的布局管理器中受益。
我会先阅读Performing Custom Painting和Graphics2D Trail。
如果这看起来令人生畏,JLabel
实际上是 的一种Container
,这意味着它实际上可以“包含”其他组件。
例子
背景窗格...
public class PaintPane extends JPanel {
private Image background;
public PaintPane(Image image) {
// This is just an example, I'd prefer to use setters/getters
// and would also need to provide alignment options ;)
background = image;
}
@Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(0, 0) : new Dimension(background.getWidth(this), background.getHeight(this));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
Insets insets = getInsets();
int width = getWidth() - 1 - (insets.left + insets.right);
int height = getHeight() - 1 - (insets.top + insets.bottom);
int x = (width - background.getWidth(this)) / 2;
int y = (height - background.getHeight(this)) / 2;
g.drawImage(background, x, y, this);
}
}
}
建造...
public TestLayoutOverlay() throws IOException { // Extends JFrame...
setTitle("test");
setLayout(new GridBagLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
PaintPane pane = new PaintPane(ImageIO.read(new File("fire.jpg")));
pane.setLayout(new BorderLayout());
add(pane);
JLabel label = new JLabel("I'm on fire");
label.setFont(label.getFont().deriveFont(Font.BOLD, 48));
label.setForeground(Color.WHITE);
label.setHorizontalAlignment(JLabel.CENTER);
pane.add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
只是为了表明我没有偏见;),一个使用标签的例子......
public TestLayoutOverlay() {
setTitle("test");
setLayout(new GridBagLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
JLabel background = new JLabel(new ImageIcon("fire.jpg"));
background.setLayout(new BorderLayout());
add(background);
JLabel label = new JLabel("I'm on fire");
label.setFont(label.getFont().deriveFont(Font.BOLD, 48));
label.setForeground(Color.WHITE);
label.setHorizontalAlignment(JLabel.CENTER);
background.add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
于 2012-09-03T21:12:43.637 回答
0
在运行时:
- 从其父标签中删除标签
- 添加一个容器,它支持层
- 添加 2x 层,但保持 Z 顺序
享受。(没有给出复制粘贴的完整代码)
于 2012-09-03T21:13:16.160 回答
-3
你可以这样做:
JLabel l1=new JLabel();
JLabel l2=new JLabel();
l1.add(l2, JLabel.NORTH);
于 2012-09-03T21:35:51.163 回答