Java null布局导致空白屏幕

当我尝试使用setLayout(null)时,我得到一个纯灰色的屏幕,我的组件都没有。 我是否需要为ColorPanel中的每个组件提供x,y值?

import javax.swing.*; import java.awt.*; public class GUI{ public static void main(String[] args){ JFrame GUI = new JFrame(); GUI.setLayout(null); GUI.setTitle("Betrai"); GUI.setSize(500, 500); GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ColorPanel panel = new ColorPanel(Color.white); Container pane = GUI.getContentPane(); JButton continueButton = new JButton("TEST"); continueButton.setBackground(Color.red); continueButton.setBounds(10, 10, 60, 40); pane.add(continueButton); GUI.setVisible(true); GUI.setBounds(0, 0, 500, 500); GUI.setResizable(false); } } 

我尝试了代码,我可以看到你的按钮,就像你指定的一样!

您需要将ColorPanel添加到布局并设置边界(就像您为测试按钮所做的那样)。

  panel.setBounds(50, 50, 100, 100); pane.add(panel); 

但是你不应该使用null布局。 几乎总有另一种布局可以满足您的需求!

当您为布局管理器使用null时,您告诉Swing您要进行绝对定位。 绝对定位的规则是在添加之前必须为添加到Container的每个组件设置边界。

在这里您可以找到Oracle使用无布局管理器的规范示例。 http://download.oracle.com/javase/tutorial/uiswing/layout/none.html

另请注意,您应该按如下方式包装所有内容:

 SwingUtilities.invokeLater(new Runnable() { public void run() { ... GUI creation stuff here ... } });