一、组件
- 窗口
- 弹窗
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件
- 鼠标
- 键盘事件
- 破解工具
二、简介
- GUI的核心技术:Swing AWT
- 因为界面不美观。
- 需要jre环境!
- 为什么我们要学习?
- 可以写出自己心中想要的一-些小工具
- 工作时候,也可能需要维护到swing界面,概率极小!
- 了解MVC架构,了解监听!
三、AWT
3.1、Awt介绍
- 包含了很多类和接口!GUI!
- 元素:窗口,按钮,文本框
- java.awt

3.2、组件和容器
1. 窗口frame
//GUI的第一个界面
public class TestFrame {
public static void main(String[] args) {
//Frame,JDK,看源码
Frame frame = new Frame("我的第一个Java图像界面窗口");
//需要设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置背景颜色
frame.setBackground(new Color(99, 206, 227));
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
//展示多个窗口 new
public class TestFrame2 {
public static void main(String[] args) {
MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.blue);
MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.yellow);
MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.red);
MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.magenta);
}
}
class MyFrame extends Frame{
static int id = 0; //可能存在多个窗口,需要一个计数器
public MyFrame(int x, int y, int w, int h, Color color) throws HeadlessException {
super("MyFrame "+(++id));
setBackground(color);
setBounds(x,y,w,h);
setVisible(true);
}
}
//问题:发现窗口关闭不掉,只能停止java程序!
2. 面板panel
//Panel 可以看成是一个空间,但是不能单独存在
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame();
//布局的概念
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//坐标、颜色
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(54, 205, 201));
//panel设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(72, 194, 59));
//添加到面板frame.add(panel);
frame.add(panel);
frame.setVisible(true);
//监听事件,监听窗口关闭时间 System.exit(0)
//适配器模式:
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭的时候需要做的事情
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
//解决:成功解决了关闭事件,窗口可以直接关闭!
3. 布局管理器
-
流式布局
public class TestFlowLayout { public static void main(String[] args) { Frame frame = new Frame(); //组件-按钮 Button button1 = new Button("button1"); Button button2 = new Button("button2"); Button button3 = new Button("button3"); //设置为流式布局 frame.setLayout(new FlowLayout()); //frame.setLayout(new FlowLayout(FlowLayout.LEFT)); frame.setLayout(new FlowLayout(FlowLayout.RIGHT)); frame.setSize(200,200); //把按钮添加上去 frame.add(button1); frame.add(button2); frame.add(button3); frame.setVisible(true); } } -
东西南北中
public class TestBorderLayout { public static void main(String[] args) { Frame frame = new Frame("TestBorderLayout"); Button east = new Button("East"); Button west = new Button("West"); Button south = new Button("South"); Button north = new Button("north"); Button center = new Button("Center"); frame.add(east,BorderLayout.EAST); frame.add(west,BorderLayout.WEST); frame.add(south,BorderLayout.SOUTH); frame.add(north,BorderLayout.NORTH); frame.add(center,BorderLayout.CENTER); frame.setSize(200,200); frame.setVisible(true); } } -
表格布局
public class TestGridLayout { public static void main(String[] args) { Frame frame = new Frame("TestGridLayout"); Button btn1 = new Button("btn1"); Button btn2 = new Button("btn2"); Button btn3 = new Button("btn3"); Button btn4 = new Button("btn4"); Button btn5 = new Button("btn5"); Button btn6 = new Button("btn6"); frame.setLayout(new GridLayout(3,2)); frame.add(btn1); frame.add(btn2); frame.add(btn3); frame.add(btn4); frame.add(btn5); frame.add(btn6); frame.pack(); //Java函数,自动选择最优布局 frame.setVisible(true); } }
4、课堂练习
- 题目及分析

-
代码
//课堂练习详解 public class ExerciseDemo { public static void main(String[] args) { //总 Frame Frame frame = new Frame(); frame.setSize(400,300); frame.setLocation(300,400); frame.setBackground(Color.BLACK); frame.setVisible(true); frame.setLayout(new GridLayout(2,1)); //4个面板 Panel panel1 = new Panel(new BorderLayout()); Panel panel2 = new Panel(new GridLayout(2,1)); Panel panel3 = new Panel(new BorderLayout()); Panel panel4 = new Panel(new GridLayout(2,2)); //上面 panel1.add(new Button("East-0"),BorderLayout.EAST); panel1.add(new Button("West-0"),BorderLayout.WEST); panel2.add(new Button("P2-btn-0")); panel2.add(new Button("P2-btn-1")); panel1.add(panel2,BorderLayout.CENTER); //下面 panel3.add(new Button("East-1"),BorderLayout.EAST); panel3.add(new Button("West-1"),BorderLayout.WEST); for (int i = 0; i < 4; i++) { panel4.add(new Button("P4-btn-"+i)); } panel3.add(panel4, BorderLayout.CENTER); frame.add(panel1); frame.add(panel3); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } -
结果

5、总结
- Frame是一个顶级窗口
- Panel无法单独显示,必须添加到某个容器中。
- 布局管理器:流式、东西南北中、表格
- 大小,定位,背景颜色,可见性,监听!
3.3、事件监听
定义:当某件事情发生的时间,干什么?
1. 按钮监听
(1) 单个按钮的监听
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮,触发一些事件
Frame frame = new Frame();
Button button = new Button();
//因为addActionListener()需要一个ActionListener,所以需要构造一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
frame.pack(); //自适应
windowClose(frame); //关闭窗口
frame.setVisible(true);
}
//关闭窗口的事件
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//事件监听
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
(2) 多个按钮,共享一个事件
public class TestActionEvent02 {
public static void main(String[] args) {
//两个按钮,实现同一个监听:开始、停止
Frame frame = new Frame("开始-停止");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//可以显式地定义触发会返回的命令,否则会触发默认值
button2.setActionCommand("button2-stop");
MyMonitor myMonitor = new MyMonitor();
button1.addActionListener(myMonitor);
button2.addActionListener(myMonitor);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack(); //自适应
frame.setVisible(true);
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// e.getActionCommand() 获得了按钮的信息
System.out.println("按钮被点击了:msg"+e.getActionCommand());
if(e.getActionCommand().equals("start")){
}
}
}
2. 输入框TextField监听
(1) 简单的文本框监听
public class TestText01 {
public static void main(String[] args) {
//启动!
new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame(){
TextField textField = new TextField();
add(textField);
//监听文本框输入的文字
MyActionListener2 myActionListener2 = new MyActionListener2();
//按下enter就会触发这个输入框的事件
textField.addActionListener(myActionListener2);
//设置替换编码
textField.setEchoChar('*');
setVisible(true);
pack();
}
}
class MyActionListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField) e.getSource(); //获得一些资源,返回一个对象
System.out.println(field.getText()); //获得输入框中的文本
field.setText(""); //清空文本框
}
}
(2) 简易计算器,组合+内部类回顾复习!
- 面向过程写法
//简易计算器
public class TestCalculator {
public static void main(String[] args) {
new Calculator();
}
}
//计算器类
class Calculator extends Frame{
public Calculator(){
//3个文本框
TextField num1 = new TextField(10); //字符数
TextField num2 = new TextField(10); //字符数
TextField num3 = new TextField(20); //字符数
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(num1,num2,num3));
//1个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
//监听器类
class MyCalculatorListener implements ActionListener{
//获取三个变量
private TextField num1,num2,num3;
public MyCalculatorListener(TextField num1, TextField num2, TextField num3){
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
@Override
public void actionPerformed(ActionEvent e) {
//1. 获得两个加数
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
//2. 将两个值进行加法运算后,放到第三个框
num3.setText(""+(n1+n2));
//3. 清除前两个框的内容
num1.setText("");
num2.setText("");
}
}
- 完全改造为面向对象写法(opp原则:组合,大于继承!)
//简易计算器
public class TestCalculator02 {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
//计算器类
class Calculator extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadFrame(){
TextField num1 = new TextField(10); //字符数
TextField num2 = new TextField(10); //字符数
TextField num3 = new TextField(20); //字符数
Button button = new Button("=");
Label label = new Label("+");
button.addActionListener(new MyCalculatorListener(this));
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
//监听器类
class MyCalculatorListener implements ActionListener{
//获取计算器这个对象,在一个类中组合另一个类
Calculator calculator = null;
public MyCalculatorListener(Calculator calculator){
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
//1. 获得两个加数
//2. 将两个值进行加法运算后,放到第三个框
//3. 清除前两个框的内容
int n1 = Integer.parseInt(calculator.num1.getText());
int n2 = Integer.parseInt(calculator.num2.getText());
calculator.num3.setText(""+(n1+n2));
calculator.num1.setText("");
calculator.num2.setText("");
}
}
- 内部类写法(更好的包装)
//简易计算器
public class TestCalculator03 {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
//计算器类
class Calculator03 extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadFrame(){
num1 = new TextField(10); //字符数
num2 = new TextField(10); //字符数
num3 = new TextField(20); //字符数
Button button = new Button("=");
Label label = new Label("+");
button.addActionListener(new MyCalculatorListener());
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
//监听器类(内部类)
//内部类最大的好处,就是可以畅通无阻的访问外部类的属性和方法!
public class MyCalculatorListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//1. 获得两个加数
//2. 将两个值进行加法运算后,放到第三个框
//3. 清除前两个框的内容
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
num3.setText(""+(n1+n2));
num1.setText("");
num2.setText("");
}
}
}
3. 画笔paint
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFrame();
}
}
class MyPaint extends Frame{
public void loadFrame(){
setBounds(200,200,600,500);
setVisible(true);
}
@Override
public void paint(Graphics g) {
//画笔需要有颜色,可以画画
g.setColor(Color.red);
//g.drawOval(100,100,100,100); //空心圆
g.fillOval(100,100,100,100); //实心圆
g.setColor(Color.green);
g.fillRect(150,200,200,200); //实心矩形
//养成习惯,画笔用完,将其还原到最初的颜色
}
}
4. 鼠标监听
- 思路

- 代码
//鼠标监听事件
public class TestMouseListener {
public static void main(String[] args) {
new MyFrame("画图");
}
}
//自己的类
class MyFrame extends Frame{
//画画需要画笔,需要监听鼠标的当前位置,需要集合来存储这个点
ArrayList points;
public MyFrame(String title){
super(title);
setBounds(200,200,400,300);
//存鼠标点击的点
points = new ArrayList<>();
setVisible(true);
//鼠标监听器,正对着这个窗口
this.addMouseListener(new MyMouseListener());
}
@Override
public void paint(Graphics g) {
//画画,监听鼠标的事件
Iterator iterator = points.iterator();
while(iterator.hasNext()){
Point point = (Point) iterator.next();
g.setColor(Color.blue);
g.fillOval(point.x,point.y,10,10);
}
}
//添加一个点到界面上
public void addPaint(Point point){
points.add(point);
}
//适配器模式
private class MyMouseListener extends MouseAdapter {
//鼠标:按下,弹起,按住不放
@Override
public void mousePressed(MouseEvent e) {
MyFrame myFrame = (MyFrame) e.getSource();
//这里我们点击的时候,就会在界面产生一个点!画
//这个点就是鼠标的点;
myFrame.addPaint(new Point(e.getX(),e.getY()));
//每次点击鼠标都需要重画一次
myFrame.repaint(); //刷新 30帧 60帧
}
}
}
- 结果

5. 窗口监听
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame(){
setBackground(Color.blue);
setBounds(100,100,200,200);
setVisible(true);
//addWindowListener(new MyWindowListener());
this.addWindowListener(
//匿名内部类,建议这样写
new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) { //不容易监听
System.out.println("windowOpened");
}
@Override
public void windowClosing(WindowEvent e) { //关闭窗口
System.out.println("windowClosing");
System.exit(0); //正常退出
}
@Override
public void windowClosed(WindowEvent e) { //不容易监听
System.out.println("windowClosed");
}
@Override
public void windowActivated(WindowEvent e) { //激活窗口
WindowFrame source = (WindowFrame) e.getSource();
source.setTitle("被激活了");
System.out.println("windowActivated");
}
/* 以下四个不常用到
@Override
public void windowDeactivated(WindowEvent e) {
super.windowDeactivated(e);
}
@Override
public void windowStateChanged(WindowEvent e) {
super.windowStateChanged(e);
}
@Override
public void windowGainedFocus(WindowEvent e) {
super.windowGainedFocus(e);
}
@Override
public void windowLostFocus(WindowEvent e) {
super.windowLostFocus(e);
}
*/
/* 注释部分为图标相关的
@Override
public void windowIconified(WindowEvent e) {
super.windowIconified(e);
}
@Override
public void windowDeiconified(WindowEvent e) {
super.windowDeiconified(e);
}
*/
}
);
}
class MyWindowListener extends WindowAdapter{
@Override
public void windowClosing(WindowEvent e) {
setVisible(true); //隐藏窗口:通过按钮,隐藏当前窗口
System.exit(0); //正常退出
}
}
}
6. 键盘监听
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
setBounds(1,2,300,400);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
//键盘按下
@Override
public void keyPressed(KeyEvent e) {
//获得键盘按下的键哪一个,键盘当前的码
int keyCode = e.getKeyCode(); //不需要去记录这个值,直接使用静态属性:VK_XXX
System.out.println(keyCode);
if(keyCode == KeyEvent.VK_UP){
System.out.println("你按下了上键");
}
//根据按下的不同操作,产生不同的结果
}
});
}
}
四、Swing
3.1、JFrame窗体
public class JFrameDemo {
//init(); 初始化
public void init(){
//顶级窗口
JFrame jf = new JFrame("这是一个JFrame窗口");
jf.setVisible(true);
jf.setBounds(100,100,200,200);
jf.setBackground(Color.cyan);
//设置文字
JLabel label = new JLabel("这是一个Java学习历程");
jf.add(label);
//让文本标签居中
label.setHorizontalAlignment(SwingConstants.CENTER);
//容器实例化
Container container = jf.getContentPane();
container.setBackground(Color.yellow);
//关闭事件
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//建立一个窗口
new JFrameDemo().init();
}
}
3.2、JDialog弹窗
//主窗口
public class DialogDemo extends JFrame {
public DialogDemo(){
this.setVisible(true);
this.setSize(700,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//容器,绝对布局
Container container = this.getContentPane();
container.setLayout(null);
//按钮
JButton button = new JButton("点击弹出一个对话框");
button.setBounds(30,30,200,50);
//点击按钮,弹出一个弹窗
button.addActionListener(new ActionListener() { //监听器
@Override
public void actionPerformed(ActionEvent e) {
//弹窗
new MyDialogDemo();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo();
}
}
//弹窗的窗口
class MyDialogDemo extends JDialog{
public MyDialogDemo(){
this.setVisible(true);
this.setBounds(100,100,500,500);
// this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 默认可以退出关闭
Container container = this.getContentPane();
// container.setLayout(null); 设置布局为空后,需要调用JLabel.setLocation() 和setsize()方法来定义大小和位置
container.add(new Label("这是一个Java学习历程"));
}
}
3.3、标签
1. JLabel
new JLabel("xxx");
2. 图标Icon
//图标,需要实现类,继承JFrame
public class IconDemo extends JFrame implements Icon {
private int width;
private int height;
public IconDemo(){} //无参构造
public IconDemo(int width, int height){
this.width = width;
this.height = height;
}
public void init(){
IconDemo iconDemo = new IconDemo(15,15);
//图标可以放在标签上,也可以放在按钮上
JLabel label = new JLabel("IconTest",iconDemo,SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
}
public static void main(String[] args) {
new IconDemo().init();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fillOval(x,y,width,height);
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
}
3. 图片Icon
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
//获取图片的地址
JLabel label = new JLabel("ImageIcon");
URL url = ImageIconDemo.class.getResource("tx.jpg");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}
3.4、面板
1. JPanel
public class JPanelDemo extends JFrame {
public JPanelDemo() {
Container container = this.getContentPane();
container.setLayout(new GridLayout(2,1,10,10)); //后面两个参数表示间距
JPanel panel1 = new JPanel(new GridLayout(1,3));
JPanel panel2 = new JPanel(new GridLayout(1,2));
JPanel panel3 = new JPanel(new GridLayout(2,1));
JPanel panel4 = new JPanel(new GridLayout(3,2));
panel1.add(new JButton("1"));
panel1.add(new JButton("1"));
panel1.add(new JButton("1"));
panel2.add(new JButton("2"));
panel2.add(new JButton("2"));
panel3.add(new JButton("3"));
panel3.add(new JButton("3"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
container.add(panel1);
container.add(panel2);
container.add(panel3);
container.add(panel4);
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JPanelDemo();
}
}
2. JScrollPanel
public class JScrollPanelDemo extends JFrame {
public JScrollPanelDemo() {
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(20,50);
textArea.setText("这是一个Java学习历程");
//JScroll面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setVisible(true);
this.setBounds(100,100,300,350);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JScrollPanelDemo();
}
}
3.5、按钮
1. 图片按钮
public class JButtonDemo01 extends JFrame {
public JButtonDemo01() {
Container container = this.getContentPane();
//将一个图片变成图标
URL url = ImageIconDemo.class.getResource("tx.jpg");
Icon icon = new ImageIcon(url);
//把这个图标放在按钮上
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
button.setHorizontalAlignment(SwingConstants.CENTER);
//把按钮加到容器上
container.add(button);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,300);
}
public static void main(String[] args) {
new JButtonDemo01();
}
}
2. 单选按钮
public class JButtonDemo02 extends JFrame {
public JButtonDemo02() {
Container container = this.getContentPane();
//将一个图片变成图标
URL url = JButtonDemo02.class.getResource("txx.jpg");
ImageIcon icon = new ImageIcon(url);
//单选框
JRadioButton radioButton1 = new JRadioButton("radioButton01");
JRadioButton radioButton2 = new JRadioButton("radioButton02");
JRadioButton radioButton3 = new JRadioButton("radioButton03");
//由于单选框只能选择一个,因此往往进行分组,一个分组中只能选择一个
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);
//把按钮加到容器上
container.add(radioButton1,BorderLayout.CENTER);
container.add(radioButton2,BorderLayout.NORTH);
container.add(radioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,300);
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
3. 复选按钮
public class JButtonDemo03 extends JFrame {
public JButtonDemo03() {
Container container = this.getContentPane();
//将一个图片变成图标
URL url = JButtonDemo03.class.getResource("txx.jpg");
ImageIcon icon = new ImageIcon(url);
//多选框
JCheckBox checkBox01 = new JCheckBox("checkBox01");
JCheckBox checkBox02 = new JCheckBox("checkBox02");
//把按钮加到容器上
container.add(checkBox01,BorderLayout.NORTH);
container.add(checkBox02,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,300);
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
3.6、列表
1. 下拉框
public class TestComboBoxDemo01 extends JFrame {
public TestComboBoxDemo01(){
Container container = this.getContentPane();
JComboBox status = new JComboBox();
status.addItem(null);
status.addItem("正在热映");
status.addItem("已下架");
status.addItem("即将上映");
container.add(status);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,300);
}
public static void main(String[] args) {
new TestComboBoxDemo01();
}
}
2. 列表框
public class TestComboBoxDemo02 extends JFrame {
public TestComboBoxDemo02(){
Container container = this.getContentPane();
//生成列表的内容
//String[] contents = {"1","2","3"};
Vector contents = new Vector();
//列表中需要放入内容
JList jList = new JList(contents);
contents.add("zhangsan");
contents.add("lisi");
contents.add("wangwu");
container.add(jList);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,300);
}
public static void main(String[] args) {
new TestComboBoxDemo02();
}
}
3. 应用场景
- 选择地区,或者一些单个选项
- 列表,展示信息,一般是动态扩容!
3.7、文本框
1. 文本框
public class TestTextDemo01 extends JFrame {
public TestTextDemo01(){
Container container = this.getContentPane();
TextField textField1 = new TextField("hello");
TextField textField2 = new TextField("world",20);
container.add(textField1,BorderLayout.NORTH);
container.add(textField2,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,300);
}
public static void main(String[] args) {
new TestTextDemo01();
}
}
2. 密码框
public class TestTextDemo02 extends JFrame {
public TestTextDemo02(){
Container container = this.getContentPane();
//写在面板里会更合适
JPasswordField passwordField = new JPasswordField(); //***
passwordField.setEchoChar('*');
container.add(passwordField);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,300);
}
public static void main(String[] args) {
new TestTextDemo02();
}
}
3. 文本域
public class JScrollPanelDemo extends JFrame {
public JScrollPanelDemo() {
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(20,50);
textArea.setText("这是一个Java学习历程");
//JScroll面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setVisible(true);
this.setBounds(100,100,300,350);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JScrollPanelDemo();
}
}
五、贪吃蛇
5.1、前言
帧,如果时间片足够小,就是动画,一秒30帧、60帧。连起来是动画,拆开就是静态的图片!
5.2、实现效果
-
按下空格暂停或者重新开始
-
上下左右控制方向,并且不允许反向移动
-
长度会随着食物的吃下而增加
-
使用定时器Timer实现定时刷新
-
累计长度和分数
5.3、实现思路
-
定义这个功能需要的数据
-
绘制这个功能需要的图形
-
添加监听这个功能需要的事件(帧率事件)
5.4、实现代码
1. Data.java 游戏的数据中心,用来初始化需要的图片
package com.cwlin.snake;
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
//相对路径 tx.jpg
//绝对路径 / 相当于当前的项目
public static URL headerURL = Data.class.getResource("statics/header.png");
public static ImageIcon header = new ImageIcon(headerURL);
public static URL upURL = Data.class.getResource("statics/up.png");
public static ImageIcon up = new ImageIcon(upURL);
public static URL downURL = Data.class.getResource("statics/down.png");
public static ImageIcon down = new ImageIcon(downURL);
public static URL leftURL = Data.class.getResource("statics/left.png");
public static ImageIcon left = new ImageIcon(leftURL);
public static URL rightURL = Data.class.getResource("statics/right.png");
public static ImageIcon right = new ImageIcon(rightURL);
public static URL bodyURL = Data.class.getResource("statics/body.png");
public static ImageIcon body = new ImageIcon(bodyURL);
public static URL foodURL = Data.class.getResource("statics/food.png");
public static ImageIcon food = new ImageIcon(foodURL);
}
2. StartGame.java 游戏的主启动类,主要实现窗口的加载,以及添加GamePanel面板到窗口
package com.cwlin.snake;
import javax.swing.*;
//游戏的主启动类
public class StartGame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(10,10,915,730); //900*720尺寸是算出来的
frame.setResizable(false); //窗口大小不可变
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//正常游戏界面都应该在面板上
frame.add(new GamePanel());
frame.setVisible(true);
}
}
3. GamePanel.java 游戏最核心的功能实现部分,包括:
(1) 功能需求
- 定义需要的数据
- 绘制图像
- 实现键盘监听和事件监听
(2) 功能模块

(3) 功能实现
package com.cwlin.snake;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
public class GamePanel extends JPanel implements KeyListener, ActionListener {
//定义蛇的数据结构
int length; //蛇的长度
int[] snakeX = new int[600]; //蛇的X坐标25*25
int[] snakeY = new int[500]; //蛇的Y坐标25*25
String direction; //初始方向
//定义食物的坐标
int foodX;
int foodY;
Random random = new Random();
//游戏积分
int score;
//游戏的当前状态:开始、停止
boolean isStart = false; //游戏默认的当前状态
//游戏的失败状态:失败、正常
boolean isFail = false; //游戏默认的失败状态
//定时器:以ms为单位
Timer timer = new Timer(100,this); //100ms刷新一次
//构造器,调用init()
public GamePanel() {
init();
//获得焦点和键盘事件
this.setFocusable(true); //获得焦点事件
this.addKeyListener(this); //获得键盘监听事件
timer.start(); //游戏一开始定时器就启动
}
//初始化方法
public void init(){
length = 3;
snakeX[0] = 100; snakeY[0] = 100; //脑袋的坐标
snakeX[1] = 75; snakeY[1] = 100; //第一个身体的坐标
snakeX[2] = 50; snakeY[2] = 100; //第二个身体的坐标
direction = "right"; //初始方向向右
foodX = 25 + 25 * random.nextInt(34); //把食物随机放置在界面上
foodY = 75 + 25 * random.nextInt(24);
score = 0; //积分初始为0
isStart = false; //默认是停止状态
isFail = false; //默认是正常状态
}
//绘制面板,游戏中的所有东西都是用这个画笔来画
@Override
protected void paintComponent(Graphics g) {
//清屏
super.paintComponent(g);
//绘制静态面板
this.setBackground(Color.WHITE);
Data.header.paintIcon(this,g,25,11); //头部广告栏
g.fillRect(25,75,850,600); //默认的游戏界面
//画积分
g.setColor(Color.white); //设置颜色
g.setFont(new Font("微软雅黑",Font.BOLD,18)); //设置字体
g.drawString("长度 " + length,750,35);
g.drawString("积分 " + score,750,50);
//画食物
Data.food.paintIcon(this,g,foodX,foodY);
//把小蛇画上去
switch (direction) {
case "right" -> Data.right.paintIcon(this, g, snakeX[0], snakeY[0]); //蛇头初始化向右,需要通过方向来判断
case "left" -> Data.left.paintIcon(this, g, snakeX[0], snakeY[0]); //蛇头初始化向左,需要通过方向来判断
case "up" -> Data.up.paintIcon(this, g, snakeX[0], snakeY[0]); //蛇头初始化向上,需要通过方向来判断
case "down" -> Data.down.paintIcon(this, g, snakeX[0], snakeY[0]); //蛇头初始化向下,需要通过方向来判断
}
for (int i = 1; i < length; ++i){
Data.body.paintIcon(this,g,snakeX[i],snakeY[i]); //第i个身体
}
//游戏状态
if(isFail){
g.setColor(Color.RED); //设置颜色
g.setFont(new Font("楷体",Font.BOLD,40)); //设置字体
g.drawString("失败,请按下空格重新开始!",200,350);
}else if (!isStart){
g.setColor(Color.white); //设置颜色
g.setFont(new Font("楷体",Font.BOLD,40)); //设置字体
g.drawString("请按下空格开始游戏!",250,350);
}
}
//键盘监听事件
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode(); //获得键盘按键
if (keyCode == KeyEvent.VK_SPACE){ //如果按下的是空格
if (isFail){ //重新开始游戏
//isFail = false; 已经在init()中进行处理
init();
}
isStart = !isStart; //当前状态取反
repaint();
}
//小蛇移动,且不允许反向移动
if(keyCode == KeyEvent.VK_UP){
if (!direction.equals("down"))
direction = "up";
}else if(keyCode == KeyEvent.VK_DOWN){
if (!direction.equals("up"))
direction = "down";
}else if(keyCode == KeyEvent.VK_LEFT){
if (!direction.equals("right"))
direction = "left";
}else if(keyCode == KeyEvent.VK_RIGHT){
if (!direction.equals("left"))
direction = "right";
}
}
//事件监听——通过固定事件来刷新,1s=10次
@Override
public void actionPerformed(ActionEvent e) {
if(isStart && !isFail){ //如果游戏是开始状态,就让小蛇动起来
//吃食物
if (snakeX[0] == foodX && snakeY[0] == foodY){
//长度 +1
length++;
//分数 +10
score += 10;
//再次随机食物的位置
foodX = 25 + 25 * random.nextInt(34);
foodY = 75 + 25 * random.nextInt(24);
}
//身体移动
for (int i = length-1; i>0 ; --i){ //后一节移到前一节的位置
snakeX[i] = snakeX[i-1];
snakeY[i] = snakeY[i-1];
}
//脑袋移动,同时进行边界判断
switch (direction) {
case "right" -> {
snakeX[0] += 25;
if (snakeX[0] > 850) {
snakeX[0] = 25;
}
}
case "left" -> {
snakeX[0] -= 25;
if (snakeX[0] < 25) {
snakeX[0] = 850;
}
}
case "up" -> {
snakeY[0] -= 25;
if (snakeY[0] < 75) {
snakeY[0] = 650;
}
}
case "down" -> {
snakeY[0] += 25;
if (snakeY[0] > 650) {
snakeY[0] = 75;
}
}
}
//失败判断
for (int i = 1; i < length; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
isFail = true;
isStart = false;
break;
}
}
repaint(); //重画页面
}
timer.start(); //定时器开启
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
}
本文详细介绍了GUI编程中的关键组件如窗口、面板、文本框等的使用,以及AWT和Swing的区别与应用,涵盖了组件设计、布局管理、事件监听和基本工具的实战。通过学习,你可以创建个性化工具并理解MVC架构。
1万+

被折叠的 条评论
为什么被折叠?



