首页 > 解决方案 > 自定义 JPanel 未添加到 JFrame

问题描述

我正在创建一个使用自定义 JPanel 的 GUI,该 JPanel 在 JPanel 上连续显示三次,然后将其添加到 JFrame。出于某种原因,自定义 JPanel 在添加到JFrame时不会显示。

我设法让 JPanel 显示的唯一方法是将以下行添加到自定义 JPanel 类的底部:

this.add(myPanel); // myPanel 是 JPanel 实例

我确定这不是正确的方法

带主方法的类驱动程序

public class Driver {
    public static void createAndShowGUI() {
        JFrame frame = new JFrame("Test");

        JPanel mainPanel = new JPanel(new GridLayout(1, 3));

        MyPanel firstPanel = new MyPanel();
        MyPanel secondPanel = new MyPanel();
        MyPanel thirdPanel = new MyPanel();

        mainPanel.add(firstPanel);
        mainPanel.add(secondPanel);
        mainPanel.add(thirdPanel);

        frame.getContentPane().add(mainPanel);

        // show the window.
        frame.setSize(MyPanel.WIDTH, MyPanel.HEIGHT);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setVisible(true);
    } // createAndShowGUI

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            } // run
        }); // Runnable
    } // main
} // Driver

自定义 JPanel 类

@SuppressWarnings("serial")
public class MyPanel extends JPanel {
     public MyPanel() {
        JPanel myPanel = new JPanel();

        // inner panel
        JPanel innerPanel = new JPanel();

        innerPanel.setBorder(BorderFactory.createEtchedBorder());
        innerPanel.setBackground(Color.red);
        innerPanel.setPreferredSize(new Dimension(WIDTH / 3, HEIGHT - 100));
        myPanel.add(innerPanel);

        JPanel buttonPanel = new JPanel();

        buttonPanel.setBackground(Color.MAGENTA);

        myPanel.add(buttonPanel);
    } // constructor
} // class

有些行已被编辑掉

标签: javaswinguser-interfacelayout

解决方案


这个类是错误的:

public MyPanel() {
        JPanel myPanel = new JPanel();
        myPanel.setBorder(BorderFactory.createEtchedBorder());
        myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));

        // inner panel
        JPanel innerPanel = new JPanel();

        innerPanel.setBorder(BorderFactory.createEtchedBorder());
        innerPanel.setBackground(Color.red);
        innerPanel.setPreferredSize(new Dimension(WIDTH / 3, HEIGHT - 100));

        myPanel.add(innerPanel);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(Color.MAGENTA);

        myPanel.add(buttonPanel);
    } // constructor
} // class

我猜它扩展了 JPanel,这意味着在创建此类时会创建两个 JPanel,一个 myPanel 变量将组件添加到其中,但从未添加到 GUI 中,而 MyPanel 实例没有添加任何内容到它,并且它确实被添加到 GUI 中。

建议:不要让此类扩展 JPanel,而是将 myPanel 局部变量设为实例字段。为类提供getMyPanel()返回此字段的方法并将其添加到 GUI。

选项 2:摆脱myPanel局部变量,而是将所有内容添加到this.


推荐阅读