为何JPanel颜色铺满整个GUI窗口?排查代码或编译器问题
问题原因与解决方法
你这段代码的问题出在JFrame默认使用BorderLayout布局管理器,直接调用add()方法时,所有面板都会被加到同一个区域(默认是CENTER),后面添加的面板会把前面的覆盖掉,所以最终只会显示最后添加的红色面板,而不是你想要的三个面板分块显示。
解决方法一:使用绝对布局(快速匹配你的写法)
给JFrame设置空布局,这样setBounds()的位置和大小设置才会生效:
import java.awt.Color; import javax.swing.JFrame; import javax.swing.JPanel; public class gui2 { public static void main(String[] args) { JPanel bluepanel = new JPanel(); bluepanel.setBackground(Color.blue); bluepanel.setBounds(0, 0, 250, 250); JPanel greenpanel = new JPanel(); greenpanel.setBackground(Color.green); greenpanel.setBounds(250, 0, 250, 250); JPanel redpanel = new JPanel(); redpanel.setBackground(Color.red); redpanel.setBounds(0, 250, 250, 250); JFrame frame = new JFrame(); frame.setTitle("what?"); frame.setSize(500,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 添加这一行,关闭默认布局 frame.setLayout(null); frame.add(bluepanel); frame.add(greenpanel); frame.add(redpanel); // 把setVisible放到最后,避免组件显示异常 frame.setVisible(true); } }
注意:绝对布局不推荐用于实际项目,因为窗口大小变化时面板不会自动适配。
解决方法二:使用标准布局管理器(推荐)
用GridLayout来实现2行2列的布局,更符合Swing的设计规范:
import java.awt.Color; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JPanel; public class gui2 { public static void main(String[] args) { JPanel bluepanel = new JPanel(); bluepanel.setBackground(Color.blue); JPanel greenpanel = new JPanel(); greenpanel.setBackground(Color.green); JPanel redpanel = new JPanel(); redpanel.setBackground(Color.red); // 空面板填充第四个位置 JPanel emptyPanel = new JPanel(); JFrame frame = new JFrame(); frame.setTitle("what?"); // 设置2行2列的网格布局,间距为0 frame.setLayout(new GridLayout(2,2,0,0)); frame.setSize(500,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(bluepanel); frame.add(greenpanel); frame.add(redpanel); frame.add(emptyPanel); frame.setVisible(true); } }
这种方式下,窗口大小改变时,面板会自动调整大小,适应性更好。
内容的提问来源于stack exchange,提问作者Nikel Halogen
相关产品推荐
相关产品推荐

