- 几乎不使用空布局
- 而是使用嵌套在JPanels中的布局的最佳组合来为您的GUI实现令人愉悦的布局。
- 如果您确实使用null布局,那么您将完全负责设置添加到该容器的 所有 组件的大小和位置。
- 当前的问题是,您永远不会给TestView指定大小或位置,而是将其添加到使用空布局的容器中。
- 您不应将一个组件(上面的JComboBox)添加到多个容器中。
- 在添加所有组件并对其进行调用
setVisible(true)
之前 , 请勿调用Jframepack()
。
例如,
import java.awt.*;import javax.swing.*;public class TestController extends JPanel { private static final int PREF_W = 1000; private static final int PREF_H = 800; TestView cgView; public TestController() { setLayout(null); cgView = new TestView(); cgView.setSize(getPreferredSize()); add(cgView); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Jframe fr = new Jframe("testt"); // fr.setSize(1200, 1000); fr.setResizable(false); TestController cgc = new TestController(); fr.setBackground(Color.white); // fr.setVisible(true); fr.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); fr.add(cgc); fr.pack(); //!! added fr.setVisible(true); // !! moved } }); }}但是最好使用布局:
import java.awt.*;import javax.swing.*;public class TestController extends JPanel { private static final int PREF_W = 1000; private static final int PREF_H = 800; TestView cgView; public TestController() { //!! setLayout(null); cgView = new TestView(); //!! cgView.setSize(getPreferredSize()); add(cgView); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Jframe fr = new Jframe("testt"); // fr.setSize(1200, 1000); fr.setResizable(false); TestController cgc = new TestController(); fr.setBackground(Color.white); // fr.setVisible(true); fr.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); fr.add(cgc); fr.pack(); //!! added fr.setVisible(true); // !! moved } }); }}class TestView extends JPanel { private static final long serialVersionUID = 1L; public JComboBox<String> comboBox; public TestView() { comboBox = new JComboBox<String>(new String[] { "option1", "option2" }); // comboBox.setBounds(100, 500, 100, 20); add(comboBox); }}编辑
OP在评论中询问:
‘几乎从不’?在哪种情况下,您会使用[null布局]?
我很少使用它,例如当我想通过动画或使用MouseListener来移动组件时,但是即使如此,许多人还是建议您创建自己的布局来处理它,例如Rob
Camick的Drag Layout。



