我试图将它们放在南边,两个按钮并排放置,但我该怎么做呢? 如果我就这样保留它们,但按钮会自动放置在顶部。
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JButton button1 = new JButton("Button 1");
panel1.add(button1);
JButton test2 = new JButton("Button 2");
panel1.add(button2);
另外,如何在内部有两个按钮的底部面板周围放置边框?
最佳答案
我们的框架将有两个面板,即 topPanel、bottomPanel。 TopPanel 将位于北边,BottomPanel 将位于南边。
在主框架上,我们使用 BorderLayout
,使用它我们将两个面板一个放置在北边,另一个放置在南边。
在 BottomPanel 上,我们将从中心开始使用 FlowLayout
。因此,无论您添加到底部面板的什么组件,它们的对齐方式都将从中心开始。
private void creteUI() {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel topPnl = new JPanel();
JPanel btnPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton btnLeft = new JButton("Left");
JButton btnRight = new JButton("Right");
btnPnl.add(btnLeft);
btnPnl.add(btnRight);
btnPnl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
mainPanel.add(topPnl, BorderLayout.NORTH);
mainPanel.add(btnPnl, BorderLayout.SOUTH);
JLabel label = new JLabel("Top Panel");
topPnl.add(label);
frame.add(mainPanel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
关于java - 如何在南面板中放置 2 个带有边框的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25987739/