Java 为什么JFrame中没有显示JPanel?
java新手。我在两个独立的java文件中有两个类 Grid.java的代码是:Java 为什么JFrame中没有显示JPanel?,java,swing,Java,Swing,java新手。我在两个独立的java文件中有两个类 Grid.java的代码是: package grid; import java.awt.*; import javax.swing.*; public class Grid { public static void main(String[] args){ JFrame f = new JFrame("The title"); f.setDefaultCloseOperation(JFram
package grid;
import java.awt.*;
import javax.swing.*;
public class Grid {
public static void main(String[] args){
JFrame f = new JFrame("The title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,400);
f.setResizable(false);
f.setVisible(true);
GridSupport g = new GridSupport();
f.add(g); //getting error when i don't extends GridSupport to JPanel
}
}
GridSuppoer.java的代码是:
package grid;
import java.awt.*;
import javax.swing.*;
public class GridSupport extends JPanel{
private JPanel p;
private JButton b;
public GridSupport(){
p = new JPanel();
p.setBackground(Color.GREEN);
p.setSize(100, 100);
b = new JButton("Click me!");
p.add(b);
}
}
我想知道1)为什么没有放映JPanel?2) 如果我把两个类放在同一个文件中,我不需要将GridSupport类扩展到JPanel,但当我把它们放在两个单独的文件中时,我需要扩展JPanel,否则它会显示错误。为什么
JFrame f = new JFrame("The title");
GridSupport g = new GridSupport();
f.add(g)
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,400);
f.setResizable(false);
f.setVisible(true);
在设置框架可见之前,添加gridsupport
。通常,在使框架可见之前,应确保将所有组件添加到框架中
GridSupport本身就是一个JPanel。因此,当您在GridSupport的内部创建一个新的JPanel并在该面板中添加所有内容时,仍然需要将内部面板添加到GridSupport中
public class GridSupport extends JPanel{
private JButton b;
public GridSupport(){
setBackground(Color.GREEN);
setSize(100, 100);
b = new JButton("Click me!");
add(b);
}
}
因为GridSupport扩展了JPanel,所以您不需要在其中创建JPanel(因为它本身就是一个JPanel,具有一些额外的特性)。 您的GridSupport类应该如下所示:
package grid;
import java.awt.*;
import javax.swing.*;
public class GridSupport extends JPanel{
private JButton b;
public GridSupport(){
this.setBackground(Color.GREEN);
this.setSize(100, 100);
b = new JButton("Click me!");
this.add(b);
}
}
您的编辑将起作用,但实际上您所做的是在一个JPanel中创建一个JPanel,然后将其放在JFrame上。请参阅我的答案,了解应该如何做。