5

是否可以在 Swing 中将按钮覆盖在标签上?

例如,如果有一个带有图像但没有文本的 JLabel,并且我想将我的按钮覆盖在这个 JLabel 上。标签的定义如下:

myLabel = new javax.swing.JLabel(new ImageIcon( myPicture ));  

如果没有,那么任何想法我该如何实现这一点,谢谢。

编辑:实际上我读到了关于将 JPanel 添加到 JLabel 的信息,当我添加一个带有按钮布局的面板时,它编译得很好,但没有任何东西是可见的,只有带有图像的 JLabel

更新:正如@paranoid-android 所建议的,我以某种方式解决了我的问题。但是我仍然必须知道如何自定义覆盖在 JLabel 之上的组件的位置,因为我没有太多控制权(可能是因为通常我使用 netbeans 来绘制布局,这需要硬编码)。

像这样的东西有效:

ImagePanel(Image image, int id) {
    this.image = image;
    this.tile = false;

    JButton backButton = new JButton();
    JButton nextButton = new JButton();
    backButton.setText(" BACK ");
    nextButton.setText(" NEXT ");


    add(backButton);
    add(nextButton);

};

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
4

3 回答 3

9

您可以使用 a 来做到这一点JLayeredPane,但如果我理解正确,那么绝对最好的方法是覆盖paintComponent

// as part of your JPanel
@Override
public void paintComponent(Graphics g){
     super.paintComponent(g);
     g.drawImage(background, 0, 0, this);
}

然后,您可以根据需要将组件添加到面板中,而无需JLabel.

于 2012-02-04T01:15:19.107 回答
2

您可以重叠按钮和标签,但您必须使用固定布局来做到这一点。如果使用 gridBagLayout,您可能会成功,但我对此表示怀疑。

这里有更多关于你需要什么的信息。

http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

于 2012-02-04T01:00:55.057 回答
0

谢谢 rtheunissen。这对我有用。
我稍微修改了一下。

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
    try {
        ImageIcon icon =  new ImageIcon(getClass().getClassLoader().getResource("img/lake.jpeg"));        
        g.drawImage(icon.getImage(),0,0,this);

    } catch (Exception ex) {
        Logger.getLogger(InfoPanel.class.getName()).log(Level.SEVERE, null, ex);
    }            
}
于 2021-02-04T11:51:51.373 回答