Swing 简介
1.Swing 是 Java 的一个图形框架,继承自 AWT;
2.Swing 主要涉及到容器,组件,还有布局管理器;
3.Swing 与用户交互的时候还涉及到事件概念;
JFrame 容器
方法太多,了解一下常用的
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
public class JFrameTest {
public static void main(String[] args) {
JFrame a=new JFrame("云的窗体标题");
a.setSize(500, 500); //设置容器大小
a.setVisible(true); //显示容器
a.setLocation(400, 100); //设置容器位置
a.getContentPane().setBackground(Color.ORANGE); //设置背景颜色
/*Container container=a.getContentPane();
container.setBackground(Color.BLUE);*/
}
}
JButton
package com.java1234.yun09.yun3;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButtonTest {
@SuppressWarnings("static-access")
public static void main(String[] args) {
JFrame a=new JFrame("JButton测试");
JButton b=new JButton("按钮"); //按钮
a.add(b);
a.setSize(500, 500); //设置容器大小
a.setVisible(true); //显示容器
a.setLocation(400, 100); //设置容器位置
a.getContentPane().setBackground(Color.ORANGE); //设置背景颜色
a.setDefaultCloseOperation(a.EXIT_ON_CLOSE); //关掉窗口结束程序的运行
}
}
Swing布局管理器
1.FlowLayout
流式布局,使用此种布局方式会使所有的组件像流水一样依次进行排列
package com.java1234.yun09.yun4;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FlowLayoutTest {
public static void main(String[] args) {
JFrame a=new JFrame("FlowLayout测试");
/*a.setLayout(new FlowLayout()); //默认居中
a.setLayout(new FlowLayout(FlowLayout.LEFT)); //向左对齐*/
a.setLayout(new FlowLayout(FlowLayout.LEFT,15,15)); //按钮间距
JButton b=null; //按钮
for (int i = 0; i < 9; i++) {
b=new JButton("JButton"+1);
a.add(b);
}
a.setSize(500, 500); //设置容器大小
a.setVisible(true); //显示容器
a.setLocation(400, 100); //设置容器位置
a.getContentPane().setBackground(Color.ORANGE); //设置背景颜色
a.setDefaultCloseOperation(a.EXIT_ON_CLOSE); //关掉窗口结束程序的运行
}
}
2.BorderLayout
使用此种布局方式将一个窗体的版面划分成东,西,南,北,中 5 个区域,可以直接将需要的组件放到这5个区域中
package com.java1234.chap09.sec04;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BorderLayoutTest {
public static void main(String[] args) {
JFrame jFrame=new JFrame("BorderLayout测试");
//jFrame.setLayout(new BorderLayout());
jFrame.setLayout(new BorderLayout(5,5));
jFrame.add(new JButton("东"),BorderLayout.EAST);
jFrame.add(new JButton("西"),BorderLayout.WEST);
jFrame.add(new JButton("南"),BorderLayout.SOUTH);
jFrame.add(new JButton("北"),BorderLayout.NORTH);
jFrame.add(new JButton("中"),BorderLayout.CENTER);
jFrame.setLocation(400, 200); // 设置容器的位置
jFrame.setSize(500,200); // 设置容器大小
jFrame.setVisible(true);