将 JLayeredPane 添加到 JPanel
我试图将 JLayeredPane 添加到 JPanel,然后将图像(JLabel 图标)和按钮添加到 JLayeredPane,但两者都没有显示。我已经测试了没有按钮和分层窗格的图像,所以我知道这是可行的。这是我正在使用的一些代码。我是否遗漏或做错了什么?
public class MyClass extends JPanel
{
private JLayeredPane layeredPane;
private JLabel imageContainer = new JLabel();
private JButton info = new JButton("i");
MyClass(ImageIcon image)
{
super();
this.imageContainer.setIcon(image);
this.layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(300, 300));
layeredPane.add(imageContainer, new Integer(50));
layeredPane.add(info, new Integer(100));
this.add(layeredPane);
}
}
I am trying to add a JLayeredPane to a JPanel and then add an image (JLabel icon) and a button to the JLayeredPane, but neither show up. I've tested the image without the button and the layeredpane so I know that works. Here is some of the code I am using. Is there something I am missing or doing wrong?
public class MyClass extends JPanel
{
private JLayeredPane layeredPane;
private JLabel imageContainer = new JLabel();
private JButton info = new JButton("i");
MyClass(ImageIcon image)
{
super();
this.imageContainer.setIcon(image);
this.layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(300, 300));
layeredPane.add(imageContainer, new Integer(50));
layeredPane.add(info, new Integer(100));
this.add(layeredPane);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自教程
请参阅对代码的更改:
附加说明:
1)(在我看来)最好将左大括号在同一行。这就是大多数 Java 代码的样子。
2)如果您不是真正创建子类,请避免从 JPanel(或任何其他组件)继承。您可以直接使用它而无需继承(除非您确实正在创建一个新组件。
From the tutorial
See the changes to your code:
Additional notes:
1) It is better ( in my opinion ) to put the opening brace in the same line. That's how most Java code looks like.
2) Avoid inheriting from JPanel ( or any other component ) if you don't are not really creating a subclass. You can use it directly without having to inherit ( unless you're indeed creating a new component.
JLayeredPane 默认情况下有一个空布局管理器,因此在您的示例中,您需要设置子组件的位置和大小。您可以在 JLayeredPane 上设置布局管理器,但这很可能会否定我猜您想要的分层渲染,因为您正在使用分层窗格。
JLayeredPane has a null layout manager by default, so in your example you'll need to set the location and size of the child components. You can set a layout manager on the JLayeredPane, but that will most likely negate the layered rendering I'm guessing you want, since you're using a layered pane.