gpt4 book ai didi

java - JFrame 未在 Eclipse Neon 中添加 JPanel

转载 作者:行者123 更新时间:2023-12-01 20:27:21 24 4
gpt4 key购买 nike

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了解最常见的布局管理器的概述。

关于java - JFrame 未在 Eclipse Neon 中添加 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com