是否可以在 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);
}
最佳答案
您可以使用 JLayeredPane
完成此操作,但如果我理解正确的话,绝对最好的方法是覆盖 paintComponent
:
// as part of your JPanel
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(background, 0, 0, this);
}
然后您可以根据需要向面板添加组件,而不需要 JLabel
。
关于java - 在 Java Swing 中将 JButton 覆盖在 JLabel 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9137404/