我很确定以前有人问过这个问题,但我的情况略有不同,因为我正尝试将一个JLabel放在JLabel上作为背景,我想使用JLabels显示不断变化的数字,并且需要在背景上显示的数字,但我是一个有点摇摆的n00b,提前谢谢你,乔纳森
发布于 2012-09-04 05:12:44
如果您没有充分了解您的需求,如果您只是需要在背景图像上显示文本,您最好将标签放在能够绘制您的背景的自定义面板的顶部。
你可以享受到布局管理器的好处,而不会弄得一团糟。
我会从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-04 05:13:16
在运行时:
好好享受吧。(没有给出复制-粘贴的完整代码)
发布于 2012-09-04 05:35:51
你可以这样做:
JLabel l1=new JLabel();
JLabel l2=new JLabel();
l1.add(l2, JLabel.NORTH);https://stackoverflow.com/questions/12253979
复制相似问题