JPanel 位于 JLabel 之上
再会!
是否可以在 JLabel 之上添加 JPanel?
我希望我的 JFrame 有一个背景图像,为此,我使用了这段代码(基于过去的 stackoverflow 答案):
setLocation(150,50);
setSize(700,650);
setVisible(true);
JLabel contentPane = new JLabel();
contentPane.setIcon(new ImageIcon("pics/b1.jpg"));
contentPane.setLayout( new BorderLayout());
setContentPane( contentPane );
现在我的问题是,由于 JLabel 背景,我无法在 JFrame 上放置面板。 请帮忙。
谢谢。
Good day!
Is it possible to add a JPanel on top of a JLabel?
I would like my JFrame to have a background image and in order to this, i used this code (based from past stackoverflow answers):
setLocation(150,50);
setSize(700,650);
setVisible(true);
JLabel contentPane = new JLabel();
contentPane.setIcon(new ImageIcon("pics/b1.jpg"));
contentPane.setLayout( new BorderLayout());
setContentPane( contentPane );
Now my problem is, I cannot put a panel on my JFrame because of the JLabel background.
Please help.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要为 JFrame 创建背景图像,我建议您在 JPanel 的 PaintComponent 方法中绘制图像,然后将此 JPanel 添加到 contentPane BorderLayout.CENTER 中,使其填充 contentPane。您甚至可能希望将 JPanel 的首选尺寸设置为图像的首选尺寸。然后,您可以将任何您想要的组件添加到图像面板,并且不必担心尝试将组件添加到 JLabel,这对我来说似乎很糟糕。
例如,这里有一个程序可以执行此操作,但略有不同。它创建一个 ImagePanel 对象,一个 JPanel,它绘制图像并根据图像调整自身大小,然后将其放入 JScrollPane 中,然后将其添加到 contentPane 中,但是您可以删除 JScrollPane 并将图像 JPanel 直接放入内容窗格改为:
To create a background image for a JFrame, I recommend that you draw the image in the paintComponent method of a JPanel, and then add this JPanel to the contentPane BorderLayout.CENTER which has it fill the contentPane. You may even want to set the JPanel's preferredSize to be that of the Image. Then you can add any components you'd like to the image panel, and don't have to worry about trying to add comopnents to a JLabel which seems bass ackwards to me.
For example here's a program that does this but slightly different. It creates an ImagePanel object, a JPanel that draws an image and sizes itself to the image and then places it in a JScrollPane which is then added to the contentPane, but you can just get rid of the JScrollPane and put your image JPanel directly in the contentPane instead:
您可以使用 JLayeredPane。这使您可以将组件添加到不同的层并将它们叠加在一起。
You could use a JLayeredPane. This lets you add components to different layers and have them ontop of one another.
这是因为面板是不透明的,因此它会绘制在标签之上。您需要使用:
Thats because a panel is opague so it paints over top of the label. You need to use:
当然..您可以..使用 NetBEans IDE 通过拖放和编写实际编程来简化此类繁琐的任务。
sure..you can....Use NetBEans IDE to simplify tedious tasks like this by drag and drop and write the actual programming..