来自另一个类的JPanel不会出现在主JFrame中

时间:2016-01-11 10:28:35

标签: java swing jframe jpanel

这是我的主要代码

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

public class MainGUI extends JFrame {

    cPanel cP = new cPanel();

    public static void main(String[] args) {
        MainGUI main = new MainGUI();
        main.setVisible(true);
    }

    private MainGUI(){
        setTitle("X");
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(null);
        add(cP);
    }   


}

然后是我的JPanel代码

import java.awt.GridLayout;
import javax.swing.*;

public class cPanel extends JPanel{

//cPanel
    JPanel cP1 = new JPanel();

//Panel 1
    JLabel lb1 = new JLabel("dx");
    JLabel lb1dx = new JLabel("dx (pixel)");
    JTextField tf1dx = new JTextField(5);
    JLabel lb1dy = new JLabel("dy (pixel)");
    JTextField tf1dy = new JTextField(5);
    JButton btn1 = new JButton("move");


    public void cPanel(){
        setBounds(0, 0, 600, 190);
        setLayout(new GridLayout(1, 8));
        add(cP1);

    //Panel 1   
        cP1.add(lb1);
        cP1.add(lb1dx);
        cP1.add(tf1dx);
        tf1dx.setText("10");
        cP1.add(lb1dy);
        cP1.add(tf1dy);
        tf1dy.setText("10");
        cP1.add(btn1);
    }

}

小组似乎没有出现。框架显示标题,没有大小,向框架添加pack()不执行任何操作。我尝试了很多方法,包括尝试新课程,我的代码出了什么问题?

3 个答案:

答案 0 :(得分:4)

public void cPanel(){ //get rid of void as it is a constructor not a method.
//public cPanel(){ instead
    setBounds(0, 0, 600, 190);
    setLayout(new GridLayout(1, 8));
    add(cP1);


private MainGUI(){
    setTitle("X");
    setResizable(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(null); //change this to setSize(500, 200) or something.
    add(cP);
}   

答案 1 :(得分:1)

问题是因为cPanel类的实现错误。您已在cPanel类中创建了一个方法,而不是构造函数。构造函数不能有返回类型,进行以下更改,它应该可以工作。

public cPanel(){
    setBounds(0, 0, 600, 190);
    setLayout(new GridLayout(1, 8));
    add(cP1);

//Panel 1   
    cP1.add(lb1);
    cP1.add(lb1dx);
    cP1.add(tf1dx);
    tf1dx.setText("10");
    cP1.add(lb1dy);
    cP1.add(tf1dy);
    tf1dy.setText("10");
    cP1.add(btn1);
}

答案 2 :(得分:-1)

正如Berger建议的那样:使用getContentPane()

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

public class MainGUI extends JFrame {

cPanel cP = new cPanel();

public static void main(String[] args) {
    MainGUI main = new MainGUI();
    main.setVisible(true);
}

private MainGUI(){
    setTitle("X");
    setResizable(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(800,600);
    getContentPane().add(cP);
}   

}