簡體   English   中英

自定義 JPanel 未添加到 JFrame

[英]Custom JPanel not being added to JFrame

我正在創建一個使用自定義 JPanel 的 GUI,該 JPanel 在 JPanel 上連續顯示三次,然后將其添加到 JFrame。 由於某種原因,自定義 JPanel 在添加到JFrame時不會顯示。

我設法讓 JPanel 顯示的唯一方法是將以下行添加到自定義 JPanel class 的底部:

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

我確定這不是正確的方法

class 驅動帶主法

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 class

@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

有些行已被編輯掉

這個 class 是錯誤的:

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,這意味着在創建此 class 時創建了兩個 JPanel,一個 myPanel 變量將組件添加到其中,但從未添加到 GUI 中,而 MyPanel 實例沒有添加任何內容到它,並且它確實被添加到 GUI 中。

建議:不要讓這個 class 擴展 JPanel,而是讓 myPanel 局部變量成為實例字段。 為 class 提供一個getMyPanel()方法,該方法返回此字段並將其添加到 GUI。

選項 2:擺脫myPanel局部變量,而是將所有內容添加到this中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM