有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将JPanel从其他类包含到主类

我有另一个类,我在里面做了一个面板。如何在主类中添加此面板(当我像这样运行时,我得到一个空白窗口)

public class Other extends JFrame {

    JTextField input = new JTextField(4);

    public JPanel panel () {
        //JPanel for all
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(null);

        //Input panel
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(null);
        inputPanel.setLocation(50,50);
        inputPanel.setSize(250, 30);
        totalGUI.add(inputPanel);

        input.setSize(100,30);
        input.setLocation(150,30);
        inputPanel.add(input);

        totalGUI.setOpaque(true);
        return totalGUI;
    }

    public Other () {
        super("Guess The Number");
    }
}

这是我的主要课程:

public class Main {

    public static void main (String[] args) {

        Other obj = new Other();
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setSize(300,300);
        obj.setVisible(true);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    您根本不应该从Main类访问面板,不需要它。要将面板添加到整个框架中,请将其写入Other构造函数:

    setContentPane(panel());
    

    如果您想保留面板,只需添加面板,请写下以下内容:

    getContentPane().add(panel());
    

    您也可以使用这一行,但AWT中仍有这一行,不应在Swing应用程序中使用:

    add(panel());
    
  2. # 2 楼答案

    您应该调用JFrame对象的add函数并向其添加JPanel。 在主函数中,在初始化其他对象后执行以下操作:

    obj.add(obj.panel());
    
  3. # 3 楼答案

    只需将JPanel添加到其构造函数上的JFrame

    public Other(){
        super("Guess The Number");
        add(panel());
    }