在 Java Swing 中将 JButton 覆盖在 JLabel 上?
是否可以在 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);
}
Is it possible to overlay a Button over a Label in Swing?
For example, if have a JLabel with image and no text, and i want to overlay my button over this JLabel. Label is defined something like:
myLabel = new javax.swing.JLabel(new ImageIcon( myPicture ));
If not, then any ideas how can i realize this, thank you.
EDIT: Actually i read about adding JPanel to a JLabel, when i add a Panel with button layout, it compiles fine but nothing is visible, just the JLabel with image
UPDATE: As suggested by @paranoid-android, somehow i have solved my problem. However i still have to know how can i customize the positions of components overlayed on top of JLabel as i don't have much control (probably because normally i use netbeans for drawing layouts, and this would require hard coding).
Something Like this worked:
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
JLayeredPane
来完成此操作,但如果我理解正确的话,绝对最好的方法是重写paintComponent
:然后您可以将组件添加到面板中,如下所示您喜欢,无需
JLabel
。You can do it using a
JLayeredPane
, although if I understand correctly, the absolute best way to do that would be to overridepaintComponent
:Then you can add components to the panel as you like, without the need for the
JLabel
.您可以重叠按钮和标签,但必须使用固定布局来执行此操作。您也许可以使用 gridBagLayout 来完成,但我对此表示怀疑。
以下是您需要的更多信息。
http://docs.oracle.com/javase/tutorial/uiswing/layout /视觉.html
You can overlap the button and the label, but you would have to do this with a Fixed Layout. You might be able to pull if off with a gridBagLayout, but I doubt it.
Here is more on what you will need.
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
谢谢鲁特尼森。
这对我来说很有效。
我稍微修改了一下。
Thanks rtheunissen.
That did the trick for me.
I modified it a little.