我试图将JLayeredPane添加到JPanel,然后将图像(JLabel图标)和按钮添加到JLayeredPane,但均未显示.我已经测试了没有按钮和分层窗格的图像,所以我知道这是可行的.这是我正在使用的一些代码.有什么我想念或做错的事吗?
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); } }推荐答案
来自教程
默认情况下,分层窗格没有布局管理器.这意味着您通常必须编写代码来确定放置在分层窗格中的组件的位置和大小.
查看对您代码的更改:
import java.awt.*; import javax.swing.*; 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); // CHANGED CODE // Manually set layout the components. imageContainer.setBounds( 0, 0, image.getIconWidth(), image.getIconHeight() ); info.setBounds( 200, 00, 50, 40 ); } public static void main( String [] args ) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.add( new MyClass( new ImageIcon("logo.png") ) ); frame.pack(); frame.setVisible( true ); } }其他说明:
1)(我认为)最好将开括号放在同一行.那就是大多数Java代码的样子.
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)如果您并不是真正在创建子类,请避免从JPanel(或任何其他组件)继承.您可以直接使用它而无需继承(除非您确实要创建一个新组件.
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添加到JPanel
发布评论