JFrame 未在 Eclipse Neon 中添加 JPanel
JFrame not adding JPanel in Eclipse Neon
public class DrawablePanel extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawablePanel());
frame.setVisible(true);
}
public DrawablePanel(){
setBackground(Color.black);
}
public Color pickColor(){
Random rand = new Random();
int a = rand.nextInt(255)+0;
int b = rand.nextInt(255)+0;
int c = rand.nextInt(255)+0;
Color color = new Color(a,b,c);
return color;
}
}
我不知道为什么 JPanel
没有出现在 JFrame
上。
I have attached an image of what it looks like when I run the code.
frame.setLayout(null);
此行删除布局管理器。要解决眼前的问题,只需删除此行,您就会得到预期的黑色背景。然后你需要学习如何使用布局管理器。 Swing API 提供了很多选项。您选择哪一个取决于您希望程序具有的外观。我建议查看 A Visual Guide to Layout Managers 以大致了解最常见的布局管理器。
public class DrawablePanel extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawablePanel());
frame.setVisible(true);
}
public DrawablePanel(){
setBackground(Color.black);
}
public Color pickColor(){
Random rand = new Random();
int a = rand.nextInt(255)+0;
int b = rand.nextInt(255)+0;
int c = rand.nextInt(255)+0;
Color color = new Color(a,b,c);
return color;
}
}
我不知道为什么 JPanel
没有出现在 JFrame
上。
I have attached an image of what it looks like when I run the code.
frame.setLayout(null);
此行删除布局管理器。要解决眼前的问题,只需删除此行,您就会得到预期的黑色背景。然后你需要学习如何使用布局管理器。 Swing API 提供了很多选项。您选择哪一个取决于您希望程序具有的外观。我建议查看 A Visual Guide to Layout Managers 以大致了解最常见的布局管理器。