[英]JPanel from another class wont appear in main JFrame
This is my main frame code 这是我的主机代码
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);
}
}
Then my JPanel code 然后我的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);
}
}
The Panel doesn't seem to appear. 该面板似乎没有出现。 The frame appeared with the title and no size, adding
pack()
to the frame does nothing. 框架出现时没有标题,没有大小,将
pack()
添加到框架没有任何作用。 I've tried a lot of ways including making a new class to try, what's wrong with my code? 我尝试了很多方法,包括制作一个新的类来尝试,我的代码有什么问题?
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);
}
The issue is because of the wrong implementation of the cPanel class. 问题是由于cPanel类的错误实现。 You have created a method in cPanel class rather then constructor.
您已经在cPanel类中创建了一个方法,而不是构造函数。 The constructor must not have a return type, make the below changes and it should work.
构造函数必须没有返回类型,进行以下更改才能正常工作。
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);
}
As Berger suggests: use getContentPane() 如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);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.