将JLabel置于JLabel之上,其中包含图像

Exc*_*bur 4 java swing jlabel jpanel

我很确定之前已经问过这个问题,但是我的情况略有不同,因为我试图将JLabel置于JLabel作为背景之上,我希望使用JLabel显示更改的数字并且需要数字显示在背景上,但是我有点摇摆n00b,感谢提前,Jonathan

Mad*_*mer 9

如果您不需要完全理解您的要求,如果您只需要在背景图像上显示文字,那么最好将标签放在能够绘制背景的自定义面板上.

您可以获得布局管理器的好处而不会出现问题.

我开始有一个阅读槽Performing Custom PaintingGraphics2D 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);                
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

用...构造

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);

}
Run Code Online (Sandbox Code Playgroud)

只是为了表明我不偏见;),一个使用标签的例子......

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);

}
Run Code Online (Sandbox Code Playgroud)

着火