import javax.swing.JFrame;
import java.awt.*;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
public class ComplexLayoutTest extends JFrame {
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JPanel panel3 = new JPanel();
private JPanel panel4 = new JPanel();
public ComplexLayoutTest() {
this.setSize(600, 600);
this.setLocation(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// *****对panel1,2,3,4进行布局******//
layoutPanel1();
layoutPanel2();
layoutPanel3();
layoutPanel4();
// *****对顶层容器进行布局*****//
setLayout(new GridLayout(2, 2));
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.add(panel4);
this.setVisible(true);// 底层容器可见的话那么顶层容器也就可见,所以后面不用写setVisible(true);
}
private void layoutPanel1() {
JButton button1 = new JButton("NORTH");
JButton button2 = new JButton("SOUTH");
JButton button3 = new JButton("WEST");
JButton button4 = new JButton("EAST");
JButton button5 = new JButton("CENTER");
// this.setLayout(new BorderLayout()); // 使用this引用当前对象的成员!!!所以此句错误
// setLayout(new BorderLayout()); // 不写,默认调用的是this.setLayout();
panel1.setLayout(new BorderLayout()); // 加this
panel1.add(button1, BorderLayout.NORTH);// 加this
panel1.add(button2, BorderLayout.SOUTH);
panel1.add(button3, BorderLayout.WEST);
panel1.add(button4, BorderLayout.EAST);
panel1.add(button5, BorderLayout.CENTER);
// panel1.setVisible(true);
}
private void layoutPanel2() {
JButton button1 = new JButton("First Button");
JButton button2 = new JButton("Second Button");
JButton button3 = new JButton("Third Button");
JButton button4 = new JButton("Fourth Button");
panel2.setLayout(new FlowLayout());
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
panel2.add(button4);
// setVisible(true);
}
private void layoutPanel3() {
JButton button1 = new JButton("First Button");
JButton button2 = new JButton("Second Button");
JButton button3 = new JButton("Third Button");
JButton button4 = new JButton("Fourth Button");
panel3.setLayout(new GridLayout(2, 2));
panel3.add(button1);
panel3.add(button2);
panel3.add(button3);
panel3.add(button4);
// setVisible(true);
}
private void layoutPanel4() {
JButton button = new JButton("JButton");
JTextArea textArea = new JTextArea("JTextField");
textArea.setBounds(20, 50, 200, 200);
button.setSize(100, 20);
button.setLocation(20, 20);
panel4.setLayout(null);
panel4.add(button);
panel4.add(textArea);
// setVisible(true);
}
public static void main(String args[]) {
ComplexLayoutTest frame = new ComplexLayoutTest();
}
}
常用界面布局
最新推荐文章于 2020-05-19 01:57:14 发布