我想放置几个按钮来检查不同布局管理器之间的差异。但是我编写的代码仅显示一个布局管理器显示的按钮,而另一个布局管理器的按钮根本不显示。我该怎么办?
这是我的代码:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class No2{
public No2() {
JFrame frame=new JFrame("MyFrame");
JPanel MainPanel=new JPanel();
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JButton[] btn=new JButton[5];
for (int i = 0; i < btn.length; i++) {
btn[i]=new JButton("Button"+(i+1));
}
frame.add(MainPanel);
MainPanel.setLayout(new GridLayout(3,1));
MainPanel.add(panel1);
MainPanel.add(panel2);
MainPanel.add(panel3);
panel1.setLayout(new FlowLayout());
for (int i = 0; i < btn.length; i++) {
panel1.add(btn[i]);
}
panel1.setLayout(new BorderLayout());
for (int i = 0; i < btn.length; i++) {
panel2.add(btn[i]);
}
panel1.setLayout(new GridLayout());
for (int i = 0; i < btn.length; i++) {
panel3.add(btn[i]);
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new No2();
}
}
答案 0 :(得分:0)
您正在将相同的JButton重新添加到3个JPanel中,这将无法正常工作,因为您只能将组件添加到一个容器中。在这种情况下,只有 last JPanel会显示您的按钮-您正在查找。
我将要做的是创建一个布局管理器数组,因为那是唯一更改的东西,然后在for循环中动态创建我的JPanels和按钮。查看代码中的注释:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.*;
@SuppressWarnings("serial")
public class No3 extends JPanel {
private static final int BUTTON_COUNT = 5;
// the only thing changing in each JPanel are the layouts used
// so put them into an array
private LayoutManager[] layouts = {
new FlowLayout(),
new BorderLayout(),
new GridLayout()
};
public No3() {
// give the enclosing JPanel a layout that holds all the other JPanels
setLayout(new GridLayout(layouts.length, 0));
for (LayoutManager layoutManager : layouts) {
// create each JPanel on the fly
JPanel panel = new JPanel(layoutManager);
// get the title of each layout (why not?) and use it in a titled border
String title = layoutManager.getClass().toString();
title = title.substring(title.lastIndexOf(".") + 1);
panel.setBorder(BorderFactory.createTitledBorder(title));
// fill this JPanel with buttons
for (int i = 0; i < BUTTON_COUNT; i++) {
panel.add(new JButton("Button" + (i + 1)));
}
// add this panel to the main JPanel
add(panel);
}
}
private static void createAndShowGui() {
No3 mainPanel = new No3();
JFrame frame = new JFrame("Layout Fun GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}