我正在为一个程序制作一个gui,它使用JPanels
来执行此操作。我有2 JPanels
。第一个包含JLabel
和JTextField
。第二个包含JLabel
和JTextField
。我需要屏幕底部的两个,一个在另一个的顶部。我试过BorderLayout.SOUTH
,但其中一个Panels
会覆盖另一个。如果我使用BoxLayout.Y_AXIS
,那么它们不会居中或位于底部。我该怎么做?
答案 0 :(得分:2)
解决方案:嵌套JPanels
创建第三个JPanel,使用面向BoxLayout.PAGE_AXIS的BoxLayout,将2个JPanel添加到此,然后将第三个JPanel添加到主GUI(希望使用BorderLayout)到BorderLayout.PAGE_END位置。
例如,我的Minimal, Complete, and Verifiable Example Program:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
public class LayoutExample extends JPanel {
public LayoutExample() {
JPanel panel1 = new JPanel();
panel1.add(new JLabel("Label 1"));
panel1.add(new JTextField(10));
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
JPanel panel2 = new JPanel();
panel2.add(new JLabel("Label 2"));
panel2.add(new JTextField(10));
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
JPanel boxLayoutUsingPanel = new JPanel();
boxLayoutUsingPanel.setLayout(new BoxLayout(boxLayoutUsingPanel, BoxLayout.PAGE_AXIS));
boxLayoutUsingPanel.add(panel1);
boxLayoutUsingPanel.add(panel2);
boxLayoutUsingPanel.setBorder(BorderFactory.createTitledBorder("BoxLayout Panel"));
setLayout(new BorderLayout());
setBorder(BorderFactory.createTitledBorder("Main BorderLayout GUI"));
add(Box.createRigidArea(new Dimension(400, 200)), BorderLayout.CENTER);
add(boxLayoutUsingPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
LayoutExample mainPanel = new LayoutExample();
JFrame frame = new JFrame("LayoutExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
如果仍然卡住,请创建并发布您的Minimal, Complete, and Verifiable Example Program。