簡體   English   中英

無法使JPanel組件顯示在JFrame上

[英]Unable to get JPanel components to display on a JFrame

我正在為類編寫一個簡單的代碼,要求我實現JMenuBar 我沒有問題可以顯示,但無法在菜單下的JFrame上顯示JPanel

我已經嘗試過各種方法,但是無法顯示面板。 我嘗試為框架提供布局,為面板提供布局,但仍然無法正常工作。 將顯示的只是Menu 這是因為我是通過主要方法來完成這一切嗎? 我知道這里的專業人士將可以在幾秒鍾內解決這個問題。 謝謝。

//TestPerson.java 
import javax.swing.*;
import java.awt.*;



public class TestPerson{
    public static void main(String [] args){
        JFrame f = new JFrame();
        f.setSize(600, 600);
        f.setVisible(true);
        JMenuBar pmb = new JMenuBar();
        f.setJMenuBar(pmb);
        f.setLocationRelativeTo(null);


        JMenu file = new JMenu("File");
        JMenu display = new JMenu("Display");
        JMenu edit = new JMenu("Edit");

        pmb.add(file);
        pmb.add(display);
        pmb.add(edit);

        file.add(new JMenuItem("Open"));
        file.add(new JMenuItem("Save"));

        edit.add(new JMenuItem("Add"));
        edit.add(new JMenuItem("Remove"));
        edit.add(new JMenuItem("Modify"));

        JPanel p1 = new JPanel();
        p1.add(new JLabel("Something"));
        p1.add(new JTextField("Type here"));
        JPanel p2 = new JPanel();
        p2.add(new JLabel("Something New"));
        p2.add(new JTextField("Type here again"));

        f.add(p1);
        f.add(p2);

    }
}   

不要在主線程中使用擺動組件。 swing教程中對此進行了解釋。

將組件添加到框架,然后,使框架可見。

不要設置框架的大小。 在使其可見之前調用pack()

框架使用BorderLayout。 將兩個面板添加到布局的中心將不起作用:只有一個面板可見。 學習使用布局管理器

GUI創建的實現有些困難。

如果需要進一步的了解,可以參考以下內容: 創建JFrame Windows

不過,我已解決您的問題。 參見下面的代碼:(經過測試)


//TestPerson.java 
import javax.swing.*;
import java.awt.*;



public class TestPerson extends JFrame{

    public TestPerson(){
        super("TestPerson");        


        JMenuBar pmb = new JMenuBar();
        this.setLayout(new BorderLayout());
        this.setJMenuBar(pmb);
        //this.setLocationRelativeTo(null);


        JMenu file = new JMenu("File");
        JMenu display = new JMenu("Display");
        JMenu edit = new JMenu("Edit");

        pmb.add(file);
        pmb.add(display);
        pmb.add(edit);

        file.add(new JMenuItem("Open"));
        file.add(new JMenuItem("Save"));

        edit.add(new JMenuItem("Add"));
        edit.add(new JMenuItem("Remove"));
        edit.add(new JMenuItem("Modithisy"));

        JPanel p1 = new JPanel();
        p1.add(new JLabel("Something"));
        p1.add(new JTextField("Type here"));
        JPanel p2 = new JPanel();
        p2.add(new JLabel("Something New"));
        p2.add(new JTextField("Type here again"));

        this.add(p1);
        this.add(p2);

        this.setSize(600, 600);
        this.setVisible(true);
        this.pack();
        this.setVisible(true);

    }

    public static void main(String [] args){
        new TestPerson();
    }
}  

那應該對你有幫助。

證明

讓我知道結果,你可以:)

暫無
暫無

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

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