• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
keaiduojava
博客园    首页    新随笔    联系   管理    订阅  订阅

GUI编程

GUI编程

组件:窗口、弹窗、面板、文本框、列表框、按钮、图片、监听事件、鼠标、键盘事件、外挂(Java)

1.简介

GUI的核心技术:Swing AWT,

  1. 因为界面不美观
  2. 需要jre环境!

为什么我们要学习?

它是 MVC架构的基础

以后学习MVC的架构,在 GUI 编程里面会发现很多思想

包括 监听器 的思想

  1. 可以写出自己心中想要的一些小工具
  2. 工作时候,也可能需要维护到 swing 界面,概率极小!
  3. 了解 MVC 架构 ,了解监听!

2.AWT

  1. 它是 Swing 的前身
  2. 它 里面有大量原生的代码,会用得到
  3. 它和 Swing 的逻辑十分相似

2.1AWT介绍

AWT:抽象的窗口工具:包含了很多类和接口;AWT 里面有各种各样的元素(元素:窗口,按钮,文本框);java.awt 包


GUI:图形用户界面编程(画窗口的)

Eeclipse:用java写的

java知识和类

2.2组件和容器

1.Frame

package com.lin.demo01;

import java.awt.*;

//GUI的第一个界面
public class TestFrame {
    public static void main(String[] args) {
        //Frame对象,JDK,看源码!
        Frame frame = new Frame("我的第一个Java图形界面窗口");

        //需要设置可见性
        frame.setVisible(true);

        //设置窗口大小
        frame.setSize(400,400);

        //设置背景颜色 Color
        frame.setBackground(new Color(38, 82, 57));

        //弹出的初始位置
        frame.setLocation(200,200);

        //设置大小固定
        frame.setResizable(false);
    }
}

发现,点击X按钮是关不掉窗口的(因为我们还没设置对应的点击事件呢)停止java程序!

尝试回顾封装:

package com.lin.demo01;

import java.awt.*;

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){
        super("Myframe"+(++id));
        setBackground(color);
        setBounds(x,y,w,h);
        setVisible(true);
    }
}

2.面板Panel

解决了关闭事件!

package com.lin.demo01;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class TestPanel {
    //Panel可以看成一个空间,但是不能单独存在
    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(82, 154, 189));

        //panel设置坐标,相对于frame
        panel.setBounds(50,50,400,400);
        panel.setBackground(new Color(196, 90, 166));

        //frame.add
        frame.add(panel);

        frame.setVisible(true);

        //监听窗口关闭事件System.exit(0)
        //适配器模式
        frame.addWindowListener(new WindowAdapter() {
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }
}

现在点击X就可以正常关闭frame窗口了。

2.3布局管理器

  • 流式布局(左、中、右)
package com.lin.demo01;

import java.awt.*;

public class TestLayout {
    public static void main(String[] args) {
        Frame frame = new Frame();

        //组件-按钮
        Button button1 = new Button("button1");
        Button button2 = new Button("button1");
        Button button3 = new Button("button1");

        //设置为流式布局
        //frame.setLayout(new FlowLayout());
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));

        frame.setSize(200,200);
        //把按钮添加上去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);

        frame.setVisible(true);
    }
}
  • 东西南北中
package com.lin.demo01;

import java.awt.*;

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);
    }
}

  • 表格布局Grid
package com.lin.demo01;

import java.awt.*;

public class TestGrid {
    public static void main(String[] args) {
        Frame frame = new Frame("testBorderLayout");

        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);
    }
}

总结:
1.Frame是一个顶级窗口
2.Panel无法单独显示,必须添加到某个容器中。
3.布局管理器
	1.流式
	2.东西南北中
	3.表格
4.大小、定位、背景颜色、可见性、监听!

2.4事件监听

事件监听:当某个事情发生的时候,干什么?

package com.lin.demo02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestAction {
    public static void main(String[] args) {
        //按下按钮,触发一些事件
        Frame frame = new Frame();
        Button button = new Button();

        //因为,addActionListener需要一个ActionListener,所以我们需要构造一个ActionListener

        MyActionLis.tener 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");
    }
}

多个按钮共享一个监听事件

package com.lin.demo02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestAction02 {
    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);
        windowClose(frame);
    }
    //关闭窗体事件
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

//事件监听
class MyMonitor implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        //e.getActionCommand() 获得按钮信息
        System.out.println("按钮被点击了+msg:"+e.getActionCommand());
    }
}

2.5输入框TextField监听

package com.lin.demo02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestText01 {
    public static void main(String[] args) {
        //启动!
        new MyFrame();
    }
}

class MyFrame extends Frame{
    public MyFrame(){
        TextField textField = new TextField();
        add(textField);

        //监听这个文本框输入的文字
        MyActionListener03 myActionListener03 = new MyActionListener03();
        //按下enter,就会触发这个输入框的事件
        textField.addActionListener(myActionListener03);

        //设置替换编码,表面显示为*,实际还是输入的内容
        textField.setEchoChar('*');

        setVisible(true);
        pack();
    }
}

class MyActionListener03 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field = (TextField) e.getSource();//获得一些资源,返回的一个对象
        System.out.println(field.getText());//获得输入框中的文本
        field.setText("");//enter之后设置为空;null是对象,""是字符串
    }
}

2.6简易计算器,组合+内部类回顾复习!

oop原则:组合,大于继承!

class A{
    public B b;
}

目前代码

package com.lin.demo02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//简易计算器
public class TestCalc {
    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("");
    }
}

完全改造为面向对象写法

package com.lin.demo02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

//计算器类
class Calculator extends Frame {
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
        //3 文本框
        num1 = new TextField(10);//字符数
        num2 = new TextField(10);//字符数
        num3 = new TextField(20);//字符数

        //1 按钮
        Button button = new Button("=");
        //给按钮添加监听事件
        button.addActionListener(new MyCalculatorListener(this));
        //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{
    //获取计算器这个对象,在一个类中组合另一个类
    Calculator calculator = null;
    public MyCalculatorListener(Calculator calculator){
        this.calculator = calculator;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //1.获得加数和被加数
        int n1 = Integer.parseInt(calculator.num1.getText());
        int n2 = Integer.parseInt(calculator.num2.getText());
        //2.将值加法运算后放到第三个框
        calculator.num3.setText(""+(n1+n2));
        //3.清除前两个框
        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}

内部类

更好的包装

package com.lin.demo02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

//计算器类
class Calculator extends Frame {
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
        //3 文本框
        num1 = new TextField(10);//字符数
        num2 = new TextField(10);//字符数
        num3 = new TextField(20);//字符数

        //1 按钮
        Button button = new Button("=");
        //给按钮添加监听事件
        button.addActionListener(new MyCalculatorListener());
        //1 标签
        Label label = new Label("+");

        //布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);
    }

    //监听器类
    //内部类最大的好处就是可以畅通无阻的访问外部类的属性和方法!
    private class MyCalculatorListener implements ActionListener{

        @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("");
        }
    }

}

2.7画笔

package com.lin.demo02;

import java.awt.*;

public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}

class MyPaint extends Frame{
    public void loadFrame(){
        setBounds(200,200,600,400);
        setVisible(true);
    }
    //画笔
    @Override
    public void paint(Graphics g) {
        //super.paint(g);
        //画笔,需要有颜色,画笔可以画画
        g.setColor(Color.red);
        //g.drawOval(100,100,100,100);
        g.fillOval(100,100,100,100);//实心圆

        g.setColor(Color.green);
        g.fillRect(180,200,200,100);
        
        //养成习惯,画笔用完,将它还原到最初的颜色
        
    }
}

2.8鼠标监听

目的:想要实现鼠标画画

package com.lin.demo03;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;

//鼠标监听
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<>();

        //鼠标监听器,正对这个窗口
        this.addMouseListener(new MyMouseListener());

        setVisible(true);
    }

    @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);
        }
    }
    //适配器模式
    private class MyMouseListener extends MouseAdapter{
        //鼠标 按下、弹起、按住不放

        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame myFrame = (MyFrame) e.getSource();
            //这个我们点击的时候,就会在界面上产生一个点!画
            //这个点就是鼠标的点
            myFrame.points.add(new Point(e.getX(),e.getY()));

            //每次点击鼠标都需要重新画一遍
            myFrame.repaint();//刷新  30帧  60帧
        } 
    }
}

2.9窗口监听

package com.lin.demo03;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestWindowListener {
    public static void main(String[] args) {
        new WindowFrame();
    }
}

class WindowFrame extends Frame {
    public WindowFrame() {
        setBackground(Color.blue);
        setBounds(100, 100, 200, 100);
        setVisible(true);
        //addWindowListener(new MyWindowListener());

        this.addWindowListener(
                new WindowAdapter() {
                    //关闭窗口
                    @Override
                    public void windowClosing(WindowEvent e) {
                        System.out.println("windowClosing");
                        System.exit(0);
                    }

                    //激活窗口
                    @Override
                    public void windowActivated(WindowEvent e) {
                        WindowFrame source = (WindowFrame) e.getSource();
                        source.setTitle("被激活了");
                        System.out.println("windowActivated");
                    }
                }
        );
    }
}

2.10键盘监听

package com.lin.demo03;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

//键
public class TestKsyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}

class KeyFrame extends Frame {
    public KeyFrame(){
        setBounds(100,200,400,300);
        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("按压上键");
                        }
                        //根据按下不同操作,产生不同的结果
                    }
                }
        );
    }
}

3.Swing

3.1窗口JFrame、面板

package com.lin.demo04;

import com.sun.xml.internal.bind.v2.schemagen.xmlschema.TypeHost;

import javax.swing.*;
import java.awt.*;

public class JFrameDemo extends JFrame{
    //init;初始化
    public void init(){
        //顶级窗口
        JFrame jframe = new JFrame("这是一个JFrame窗口");
        this.setVisible(true);
        //jframe.setBounds(100,100,200,200);
        //jframe.setBackground(Color.yellow);
        //设置文字JLabel
        JLabel jlabel = new JLabel("欢迎学习JFrame",SwingConstants.CENTER);
        this.add(jlabel);

        //容器实例化
        Container container = this.getContentPane();//获得一个容器
        container.setBackground(Color.BLUE);
        //关闭事件
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        //建立一个窗口
        new JFrameDemo().init();
    }
}

3.2弹窗JDialog

JDialog:用来被弹出,默认就有关闭事件

package com.lin.demo04;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//主窗口
public class DialogDemo extends JFrame {
    public DialogDemo(){
        this.setVisible(true);
        this.setSize(700,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //JFrame放东西,容器
        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 container1 = this.getContentPane();
        //container1.setLayout(null);

        JLabel label1 = new JLabel("弹出窗口",SwingConstants.CENTER);
        label1.setSize(100,50);
        container1.add(label1);
    }
}

3.3标签

label

new JLabel("xxx");

图标Icon

package com.lin.demo04;

import javax.swing.*;
import java.awt.*;

//图标,需要实现类,Frame继承
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(){
        this.setBounds(100,100,700,500);
        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);
    }

    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;
    }
}

图片Icon

package com.lin.demo04;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class ImageIcon01 extends JFrame {
    public ImageIcon01(){
        //获取图片的地址
        JLabel label = new JLabel("ImageIcon");
        URL url = ImageIcon01.class.getResource("p1.jpg");//获取当前类下资源

        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);

        Container container = getContentPane();
        container.add(label);
        setBounds(200,200,500,400);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new ImageIcon01();
    }
}

3.4面板

JPanel

package com.lin.demo05;

import javax.swing.*;
import java.awt.*;

public class JPanel01 extends JFrame {
    public JPanel01(){
        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));
        panel1.add(new JButton("11"));
        panel1.add(new JButton("12"));
        panel1.add(new JButton("13"));
        panel2.add(new JButton("21"));
        panel2.add(new JButton("22"));
        panel3.add(new JButton("31"));
        panel3.add(new JButton("32"));

        container.add(panel1);
        container.add(panel2);
        container.add(panel3);

        setVisible(true);
        setSize(500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JPanel01();
    }
}

JScroll滚动条

package com.lin.demo05;

import javax.swing.*;
import java.awt.*;

public class JScrollDemo extends JFrame {
    public JScrollDemo(){
        Container container = this.getContentPane();
        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        textArea.setText("欢迎学习java");

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

        this.setVisible(true);
        setBounds(200,200,600,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollDemo();
    }
}

3.5按钮

  • 图片按钮
package com.lin.demo05;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class JButtonDemo01 extends JFrame {
    public JButtonDemo01(){
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL url = JButtonDemo01.class.getResource("p1.jpg");
        ImageIcon icon = new ImageIcon(url);

        //把图标放在按钮上
        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("图片按钮");

        //add
        container.add(button);
        setVisible(true);
        setSize(500,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JButtonDemo01();
    }
}
  • 单选按钮
package com.lin.demo05;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class JButtonDemo02 extends JFrame {
    public JButtonDemo02(){
        Container container = this.getContentPane();

        //单选框
        JRadioButton radioButton01 = new JRadioButton("男");
        JRadioButton radioButton02 = new JRadioButton("女");

        //由于单选框只能选择一个,分组,一个分组中只能选择一个
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton01);
        group.add(radioButton02);

        container.add(radioButton01,BorderLayout.NORTH);
        container.add(radioButton02,BorderLayout.SOUTH);

        setVisible(true);
        setBounds(200,200,500,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JButtonDemo02();
    }
}
  • 复选按钮
package com.lin.demo05;

import javax.swing.*;
import java.awt.*;

public class JButtonDemo03 extends JFrame {
    public JButtonDemo03(){
        Container container = this.getContentPane();

        //多选框
        JCheckBox checkBox01 = new JCheckBox("checkBox01");
        JCheckBox checkBox02 = new JCheckBox("checkBox02");

        container.add(checkBox01,BorderLayout.NORTH);
        container.add(checkBox02,BorderLayout.SOUTH);

        setVisible(true);
        setBounds(200,200,500,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JButtonDemo03();
    }
}

3.6列表

  • 下拉框
package com.lin.demo06;

import javax.swing.*;
import java.awt.*;

public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01(){

        Container container = this.getContentPane();
        JComboBox status = new JComboBox();
        status.addItem("正在热映");
        status.addItem("已下架");
        status.addItem("即将上映");

        container.add(status);

        this.setVisible(true);
        setBounds(300,300,600,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestComboboxDemo01();
    }
}
  • 列表框
package com.lin.demo06;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class TestComboboxDemo02 extends JFrame {
    public TestComboboxDemo02(){

        Container container = this.getContentPane();

        //生成列表内容  稀疏数组
        //String[] content = {"1","2","3"};

        Vector content = new Vector();
        //列表中需要放入内容
        JList list = new JList(content);

        content.add("zhangsan");
        content.add("lisi");
        content.add("wangwu");

        container.add(list);

        this.setVisible(true);
        setBounds(300,300,600,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestComboboxDemo02();
    }
}
  • 应用场景
    • 选择地区,或者一些单个选项
    • 列表,展示信息;一般是动态扩容!

3.7文本框

  • 文本框
package com.lin.demo06;

import javax.swing.*;
import java.awt.*;

public class TestTextDemo01 extends JFrame {
    public TestTextDemo01(){

        Container container = this.getContentPane();

        JTextField textField = new JTextField("hello");
        JTextField textField2 = new JTextField("world",20);
        container.add(textField,BorderLayout.NORTH);
        container.add(textField2,BorderLayout.SOUTH);

        this.setVisible(true);
        setBounds(300,300,600,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestTextDemo01();
    }
}
  • 密码框
package com.lin.demo06;

import javax.swing.*;
import java.awt.*;

public class TestTextDemo02 extends JFrame {
    public TestTextDemo02(){

        Container container = this.getContentPane();

        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar('*');
        container.add(passwordField);

        this.setVisible(true);
        setBounds(300,300,600,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestTextDemo02();
    }
}
  • 文本域
package com.lin.demo06;

import javax.swing.*;
import java.awt.*;

public class TestTextDemo03 extends JFrame {
    public TestTextDemo03(){
        Container container = this.getContentPane();

        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        textArea.setText("欢迎学习java");

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

        this.setVisible(true);
        setBounds(300,300,600,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestTextDemo03();
    }
}

贪吃蛇

帧,如果时间片足够小,就是动画,一秒30帧 60帧。连起来是动画,拆开就是静态的图片!

键盘监听

定时器Timer

步骤:

  1. 定义数据

  2. 画上去

  3. 监听事件

    键盘

    事件

package com.lin.Snake;

import javax.swing.*;

//游戏的主启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setBounds(10,10,900,720);
        frame.setResizable(false);//窗口大小不可变
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //正常的游戏界面都应该在面板上
        frame.add(new GamePanel());
    }
}
package com.lin.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 fx;

    //食物的坐标
    int foodX;
    int foodY;
    Random random = new Random();

    //成绩
    int score;

    //游戏当前的状态:开始或者停止
    boolean isStart = false;//默认暂停
    boolean isFail = false;//游戏失败状态

    //定时器 以ms为单位1000ms = 1s
    Timer timer = new Timer(500,this);//100ms执行一次!

    //构造器
    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;//第二个身体的坐标
        fx = "R";//初始方向向右

        //把食物随机分布在界面上
        foodX = 25+25*random.nextInt(34);
        foodY = 75+25*random.nextInt(24);

        score = 0;
    }

    //绘制面板,我们游戏中的所有东西都是用这个画笔来画
    @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,55);

        //画食物
        Data.food.paintIcon(this,g,foodX,foodY);


        //把小蛇画上去
        if(fx.equals("R")){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右,需要通过方向来判断
        }else if(fx.equals("L")){
            Data.left.paintIcon(this, g, snakeX[0],snakeY[0]);
        }if(fx.equals("U")){
            Data.up.paintIcon(this, g, snakeX[0],snakeY[0]);
        }if(fx.equals("D")){
            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]);
        }

        //游戏状态
        if(!isStart){
            g.setColor(Color.white);
            //设置字体
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("按下空格开始游戏",300,300);
        }
        if (isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("游戏失败,按下空格重新开始",300,300);
        }
    }

    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//获得键盘按键是哪一个
        if(keyCode == KeyEvent.VK_SPACE){//如果按下的是空格键
            if(isFail){
                //重新开始
                isFail = false;
                init();
            }else{
                isStart = !isStart;//取反
            }
            repaint();
        }

        //小蛇移动
        if(keyCode == KeyEvent.VK_UP){
            fx = "U";
        }else if(keyCode == KeyEvent.VK_DOWN){
            fx = "D";
        }else if(keyCode == KeyEvent.VK_LEFT){
            fx = "L";
        }else if(keyCode == KeyEvent.VK_RIGHT){
            fx = "R";
        }
    }
    @Override
    public void keyTyped(KeyEvent e) {}
    @Override
    public void keyReleased(KeyEvent e) {}

    //事件监听--需要通过固定事件来刷新,1s 10次
    @Override
    public void actionPerformed(ActionEvent e) {
        if(isStart && !isFail){//如果游戏是开始状态就让小蛇动起来!

            //吃食物
            if(snakeX[0] == foodX && snakeY[0] == foodY){
                length++;//长度 + 1
                score += 10;//分数 + 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];
            }

            //走向
            if(fx.equals("R")){
                snakeX[0] = snakeX[0]+25;
                if(snakeX[0] > 850){snakeX[0] = 25;}//边界判断
            }else if(fx.equals("L")){
                snakeX[0] = snakeX[0]-25;
                if(snakeX[0] < 25){snakeX[0] = 850;}//边界判断
            }else if(fx.equals("U")){
                snakeY[0] = snakeY[0]-25;
                if(snakeY[0] < 75){snakeY[0] = 650;}//边界判断
            }else if(fx.equals("D")){
                snakeY[0] = 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;
                }
            }


            repaint();//重画页面
        }
        timer.start();//定时器开启!
    }
}
package com.lin.Snake;

import javax.swing.*;
import java.net.URL;

//数据中心
public class Data {
    //相对路径p1.jpg
    //绝对路径  / 相当于当前项目
    private static URL headerURL = Data.class.getResource("statics/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);

    private static URL upURL = Data.class.getResource("statics/up.png");
    private static URL downURL = Data.class.getResource("statics/down.png");
    private static URL leftURL = Data.class.getResource("statics/left.png");
    private static URL rightURL = Data.class.getResource("statics/right.png");
    public static ImageIcon up = new ImageIcon(upURL);
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);

    private static URL bodyURL = Data.class.getResource("statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);

    private static URL foodURL = Data.class.getResource("statics/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);

}

posted on 2023-03-09 21:06  ·草莓味的可爱多  阅读(3)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3