java label覆盖_java – 将JLabel置于JLabel之上,其中包含图像
我很確定之前已經(jīng)問過這個問題,但我的情況略有不同,因為我試圖將JLabel置于JLabel作為背景的頂部,我想使用JLabel顯示更改的數(shù)字并且需要數(shù)字顯示在背景上,但是我有點搖擺n00b,感謝提前,Jonathan
解決方法:
如果您不需要完全理解您的要求,如果您只需要在背景圖像上顯示文字,那么最好將標(biāo)簽放在能夠繪制背景的自定義面板上.
您可以獲得布局管理器的好處而不會出現(xiàn)問題.
如果這看起來令人生畏,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);
}
}
}
用…構(gòu)造
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);
}
只是為了表明我不偏見;),一個使用標(biāo)簽的例子……
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);
}
標(biāo)簽:java,swing,jpanel,jlabel
來源: https://codeday.me/bug/20190529/1181755.html
總結(jié)
以上是生活随笔為你收集整理的java label覆盖_java – 将JLabel置于JLabel之上,其中包含图像的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魅族16s充电速度
- 下一篇: stata面板数据回归步骤是什么(Sta