将JPanel添加到JFrame不起作用

时间:2016-05-10 17:02:17

标签: java swing netbeans

如何将JPanel添加到其他类的JFrame中?我已尝试使用此代码,但是当我编译它时,它没有显示MyFrame.java中的任何组件(标签“Hello World”)。我的代码出了什么问题?

MainFrame.java中的按钮称为MyFrame.java

以下是代码:

MyPanel.java (包含按钮和标签)

public class MyPanel extends javax.swing.JPanel {

    public MyPanel() {
        initComponents();
        myLabel.setText("Hello World");
    }
}

MyFrame.java

public class MyFrame extends javax.swing.JFrame {

    MyPanel myPanel = new MyPanel();

    public MyFrame() {
        initComponents();
        this.add(myPanel);
    }
}

MainFrame.java

public class MainFrame extends javax.swing.JFrame {

    public MainFrame() {
        initComponents();
    }

    private void btnCallFrameActionPerformed(java.awt.event.ActionEvent evt) {                                         
        new MyFrame().setVisible(true);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
}       

1 个答案:

答案 0 :(得分:0)

我不知道你在initComponents方法中做了什么。所以我稍微更改了你的代码。

public class MyPanel extends javax.swing.JPanel {

    public MyPanel() {
        initComponents();
        //I don't know what you did in initComponents(); so I ve changed the layout to be sure that you didn't use null layout. 
        this.setLayout(new BorderLayout());

        JLabel myLabel = new JLabel();
        myLabel.setText("Hello World");

       //adding the label in MyPanel 
       this.add(myLabel);
    }
}

public class MyFrame extends javax.swing.JFrame {

    MyPanel myPanel = new MyPanel();

    public MyFrame() {
        initComponents();
        // added because of the former reason
        this.setLayout(new BorderLayout());
        this.add(myPanel);
    }
}

我希望您确定可以使用某个按钮调用btnCallFrameActionPerformed方法。