Swing为GUI(图形用户界面)提供开发工具包,使用Swing开发的应用程序可以统一应用程序在不同平台上运行的GUI组件显示风格,因为在Swing组件可以跨平台指定统一风格和外观。
一般常用的组件有JButton、JFrame、JDialog、JList等等
JFream窗体:一个容器,可以装载组件的容器,可以通过继承java.swing.JFrame类来创建窗体,继承了JFrame类后拥有最大化,最小化,关闭等按钮。
JFrame窗体示例:
创建JFrame对象后,调用getContentPane方法转为容器,实例化组件后可以用Container类的add方法将组件添加到容器中。
public class JFrameDemo {
private int width=500;
private int height=300;
public static void main(String[] args) {
new JFrameDemo().init();
}
private void init() {
//实例化JFrame对象
JFrame jframe = new JFrame("田野上的风筝");
Container container =jframe.getContentPane();
//设置窗体大小
jframe.setSize(width, height);
//实例化一个JButton对象
JButton jbutton = new JButton("按钮");
//使用Container的add方法将组件添加到Container
container.add(jbutton);
//设置窗体背景颜色
jframe.setBackground(Color.blue);
//设置窗体可见
jframe.setVisible(true);
//窗体关闭方式
jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jframe.setLocationRelativeTo(null);//设置窗体大小后设置窗体居中显示
}
}
设置窗体出现的位置为居中有两种方法,除了上面代码中那种方法,还有一种方法首先获取显示器的大小,然后使用setBounds方法设置窗体的位置(x,y坐标)以及指定窗体大小。
代码如下
//获取显示器的宽高
int compwidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int compheight=Toolkit.getDefaultToolkit().getScreenSize().height;
jframe.setBounds((compwidth-width)/2,(compheight-height)/2,width,height);
运行结果如下:
一般设置关闭窗体的方式有四种:
DO_NOTHING_ON_CLOSE(表示不做任何操作关闭窗体)
DISPOSE_ON_CLOSE(表示任何监听程序对象会自动隐藏释放窗体)
HIDE_ON_CLOSE(表示隐藏窗体的默认窗口关闭)
EXIT_ON_CLOSE(表示退出应用程序默认窗口关闭)
JDialog窗体:Swing中的对话框,代码示例如下
创建一个类继承JDialog,使用super关键字调用JDialog构造方法。
public class JDiallogDemo extends JDialog{
private int width = 250;
private int height= 150;
public JDiallogDemo(){
super(new Jframe(),"提示",true);
Container c= this.getContentPane();
JLabel jb = new JLabel("提交成功");//实例化JLabel对象
this.setSize(width, height);// 设置大小
this.setLocationRelativeTo(null);
c.add(jb);
}
public static void main(String[] args) {
new JDiallogDemo();
}}
Jframe类继承JFrame,该窗体定义一个按钮,按钮添加了监听事件,当点击按钮时弹出对话框。代码如下
class Jframe extends JFrame{
private int width = 600;
private int height= 350;
public Jframe(){
init();
}
//初始化窗体方法
private void init() {
//获取显示屏大小
int compwidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int compheight = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setBounds((compwidth-width)/2,(compheight-height)/2 , width, height);// 窗体居中显示
this.setBackground(Color.white);// 设置背景颜色
JButton button = new JButton("提交");//实例化JButton对象
// button.setBackground(Color.LIGHT_GRAY);
button.setBounds(100, 30, 50, 30);
//添加监听
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
new JDiallogDemo().setVisible(true);//设置JDialog显示
}
});
Container container = this.getContentPane();
container.add(button);// 添加到容器中
this.setVisible(true);// 显示窗体
//窗体的关闭方式
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
运行结果如下