我有一个包含 4 个 JPanel 和 1 个 JScrollPane 的框架,这 4 个面板的边框布局为北、东、南、西,滚动 Pane 位于中心。
我一直在尝试获取框架功能的 pack 方法,但运行时您只会获得窗口的标题栏。
有什么想法吗?
JFrame conFrame;
JPanel panel1;
JPanel panel2;
JPanel panel3;
JPanel panel4;
JScrollPane listPane;
JList list;
Object namesAr[];
...
...
...
namesAr= namesA.toArray();
list = new JList(namesAr);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-3);
list.addListSelectionListener(this);
listPane = new JScrollPane(list);
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
conFrame.setLayout(new BorderLayout());
panel1.setPreferredSize(new Dimension(100, 100));
panel2.setPreferredSize(new Dimension(100, 100));
panel3.setPreferredSize(new Dimension(100, 100));
panel4.setPreferredSize(new Dimension(100, 100));
panel1.setBackground(Color.red);
panel2.setBackground(Color.red);
panel3.setBackground(Color.red);
panel4.setBackground(Color.red);
conFrame.pack();
conFrame.add(panel1, BorderLayout.NORTH);
conFrame.add(panel2, BorderLayout.EAST);
conFrame.add(panel3, BorderLayout.SOUTH);
conFrame.add(panel4, BorderLayout.WEST);
conFrame.add(listPane, BorderLayout.CENTER);
conFrame.setVisible(true);
最佳答案
您需要在执行 pack() 之前将面板添加到框架中,否则就没有任何东西可以打包。
此外,框架的默认布局是 BorderLayout。
关于Java JFrame 方法 pack(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2440754/