简体   繁体   English

将 JPanel 添加到 JFrame 不起作用

[英]Adding JPanel to JFrame didn't work

How to add JPanel to JFrame in other class??如何在其他类中将 JPanel 添加到 JFrame 中? I've tried with this code, but when I compile it, it didn't show any component in MyFrame.java (the label "Hello World").我已经尝试过这段代码,但是当我编译它时,它没有在MyFrame.java显示任何组件(标签“Hello World”)。 What's wrong with my code?我的代码有什么问题?

(Button in MainFrame.java called the MyFrame.java ) MainFrame.java按钮称为MyFrame.java

Here's the code:这是代码:

MyPanel.java (contains button and label) 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主框架.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);
            }
        });
    }
}       

I don't know what you have done in initComponents method.我不知道你在 initComponents 方法中做了什么。 So I have changed your code a little bit.所以我稍微改变了你的代码。

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

I hope you are sure that you can call the btnCallFrameActionPerformed method with some button.我希望您确定您可以使用某个按钮调用 btnCallFrameActionPerformed 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM