adding JLayeredPane to JPanel

南楼画角 提交于 2019-12-03 12:32:13
OscarRyz

From the tutorial

By default a layered pane has no layout manager. This means that you typically have to write the code that positions and sizes the components you put in a layered pane.

See the changes to your code:

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 );
    }
}       

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 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!