我很确定以前有人问过这个问题,但我的情况略有不同,因为我试图将 JLabel 放在充当背景的 JLabel 之上,我想使用 JLabel 和数字需要显示在背景上,但是我有点 Swing 不定 n00b,在此先感谢 Jonathan
最佳答案
在没有完全理解您的要求的情况下,如果您只需要在背景图片上显示文本,您最好将标签放在能够绘制背景的自定义面板上。
您可以从布局管理器中受益,而不会弄得一团糟。
我会先读一个 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);
}
关于java - 将 JLabel 放在 JLabel 的顶部,图像在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12253979/