我有这个gui;当高度不够大时,窗格会相互重叠。我必须设置它至少200,所以我可以完全看到这两行;但是当它设置为200时,我最后会有一个很大的空行,我不希望这样。我怎么能解决这个问题?感谢。
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
JButton panicButton;
JButton dontPanic;
JButton blameButton;
JButton newsButton;
JButton mediaButton;
JButton saveButton;
JButton dontSave;
public MyFrame() {
super("Crazy App");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel row1 = new JPanel();
panicButton = new JButton("Panic");
dontPanic = new JButton("No Panic");
blameButton = new JButton("Blame");
newsButton = new JButton("News");
//adding first row
GridLayout grid1 = new GridLayout(4, 2, 10, 10);
setLayout(grid1);
FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(flow1);
row1.add(panicButton);
row1.add(dontPanic);
row1.add(blameButton);
row1.add(newsButton);
add(row1);
//adding second row
JPanel row2 = new JPanel();
mediaButton = new JButton("Blame");
saveButton = new JButton("Save");
dontSave = new JButton("No Save");
GridLayout grid2 = new GridLayout(3, 2, 10, 10);
setLayout(grid2);
FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row2.setLayout(flow2);
row2.add(mediaButton);
row2.add(saveButton);
row2.add(dontSave);
add(row2);
setVisible(true);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
}
}
答案 0 :(得分:3)
pack()
,使GUI缩小到组件所需的最小值。
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.*;
public class MyFrame17 extends JFrame {
JButton panicButton;
JButton dontPanic;
JButton blameButton;
JButton newsButton;
JButton mediaButton;
JButton saveButton;
JButton dontSave;
public MyFrame17() {
super("Crazy App");
setLayout(new GridLayout(2, 2, 10, 10));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel row1 = new JPanel();
panicButton = new JButton("Panic");
dontPanic = new JButton("No Panic");
blameButton = new JButton("Blame");
newsButton = new JButton("News");
FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(flow1);
row1.add(panicButton);
row1.add(dontPanic);
row1.add(blameButton);
row1.add(newsButton);
add(row1);
//adding second row
JPanel row2 = new JPanel();
mediaButton = new JButton("Blame");
saveButton = new JButton("Save");
dontSave = new JButton("No Save");
FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row2.setLayout(flow2);
row2.add(mediaButton);
row2.add(saveButton);
row2.add(dontSave);
add(row2);
pack();
setVisible(true);
}
public static void main(String[] args) {
MyFrame17 frame = new MyFrame17();
}
}
MyFrame
更明智的名称。要添加的好词是Test
,然后考虑一下正在测试的内容。这是关于按钮的布局,因此ButtonLayoutTest
可能是一个好名字。