package element;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Jpanel extends JFrame{
public static void main(String[] args) {
// Jpanel p = new Jpanel();
new Jpanel().setVisible(true);
}
public Jpanel(){//构造方法
/*
* 拥有三个布局,分别为p1,p2,p4
*
* */
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p4 = new JPanel();
/*
* 在这三个布局中添加按钮JButton 1 2 3 4 5 6
* */
JButton a1 = new JButton("1");
JButton a2 = new JButton("2");
JButton a3 = new JButton("3");
JButton a4 = new JButton("4");
JButton a5 = new JButton("5");
JButton a6 = new JButton("6");
//添加按钮a1
//设置布局的颜色
p1.add(a1);
p1.setBackground(Color.red);
p1.add(a2);
p1.add(a3);
p2.add(a4);
p2.add(a5);
p4.add(a6);
p2.setBackground(Color.black);
p4.setBackground(Color.blue);
/*利用JFrame组件设置布局的位置
* 默认的内容窗格上会设置有 BorderLayout 管理器。
* 注意布局中的BorderLayout后面的东南西北是大写的,如果布局有重复则会覆盖
* */
this.add(p1,BorderLayout.WEST);
this.add(p2,BorderLayout.EAST);
this.add(p4,BorderLayout.NORTH);
this.setTitle("main");//设置窗口的名字
this.setSize(400,400);//设置窗口的大小
/*与 Frame 不同,当用户试图关闭窗口时,JFrame 知道如何进行响应。用户关闭窗口时,
* 默认的行为只是简单地隐藏 JFrame。要更改默认的行为,可调用方法 setDefaultCloseOperation(int)。
* 要使 JFrame 的行为与 Frame 实例相同,请使用
* setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)。
* EXIT_ON_CLOSE
*public static final int EXIT_ON_CLOSE
*退出应用程序后的默认窗口关闭操作。如果执行关闭操作时窗口具有此设置,并且是在 applet 中关闭窗口,
*则可能抛出 SecurityException。建议仅在应用程序中使用此设置。
* */
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// this.setLocation(10,100);//窗口出现在电脑屏幕的位置
//另一种显示方法为显示在中心
this.setLocationRelativeTo(null);
/*
* void setVisible(boolean b)
根据参数 b 的值显示或隐藏此 Window。
* */
this.setVisible(true);//另一种写法,new Jpanel.setVisible(true);
}
}
一个窗口的基本组件介绍(1)
最新推荐文章于 2022-11-15 12:51:29 发布