2、GUI

简介

基本

component祖宗

  • container
    • Window:Frame,Dialog
    • Panel: Applet
  • 各种零件:button、labelText、Area

AWT

  • import java.awt.*

基本

  • 窗口退出:
new Frame().addWindowListener(new WindowAdapter() {//匿名内部类,区别与lambda
    @Override
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
})
  • 基本:
public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame("我的一个GUI");                
        //设置窗口基本属性
        frame.setLocation(200,200);
        frame.setSize(400,400);//可以利用setBound代替
        frame.setBackground(new Color(255, 0, 0));             
        frame.setVisible(true);         
    }
}
  • 通过自定类实现,在构造器中不用在写frame.前缀继承Frame
public class TestFrame {
    public static void main(String[] args) {
        MyFrame myFrame3 = new MyFrame(200,400,200,200,Color.blue);
        MyFrame myFrame4 = new MyFrame(400,400,200,200,new Color(11, 238, 211));
    }
}
class MyFrame extends Frame{    //继承Frame
    static int id = 0;		//必须是static,要不然super报错
    public MyFrame(int x,int y,int weight,int height,Color color)  {
        super("名字:"+(++id));		//通过调用父类,也可以传递窗口名
        setBounds(x,y,weight,height);
        setBackground(color);
        setVisible(true);
    }
}

Panel

  • panel基本属性设置:
public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Panel panel = new Panel();
        frame.setLayout(null);//没有setlayout不显示panel

        frame.setBounds(200,200,500,500);
        frame.setBackground(Color.cyan);
        panel.setBounds(100,100,200,200);
        panel.setBackground(Color.red);
        frame.add(panel);

        frame.setVisible(true);
    }
}

按钮Layout

  • 流式布局
public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(100,100,500,500);
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
		
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));//流式布局       

        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        
        frame.setVisible(true);
    }
}
  • 东西南北中:
public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Button button1 = new Button("East");
        Button button2 = new Button("West");
        Button button3 = new Button("South");
        Button button4 = new Button("North");
        Button button5 = new Button("Center");
        
        frame.add(button1,BorderLayout.EAST);
        frame.add(button2,BorderLayout.WEST);
        frame.add(button3,BorderLayout.SOUTH);
        frame.add(button4,BorderLayout.NORTH);
        frame.add(button5,BorderLayout.CENTER);

        frame.setSize(500,500);
        frame.setVisible(true);
    }
}
  • 表格布局
public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setLayout(new GridLayout(2,3));
        
        for (int i = 1; i < 7; i++) {
            frame.add(new Button(""+i));
        }

        frame.setSize(500,500);
        frame.setVisible(true);
    }
}
  • 实战演练

ActionListener

  • 按钮增加监听,产生事件
public class Demo7 {
    public static void main(String[] args) {
        Frame frame = new Frame("myframe");
        frame.setBounds(200,200,500,500);

        Button button = new Button("1");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Don't click");
            }
        });

        frame.add(button);
        
        frame.setVisible(true);
    }
}
  • 按钮发送指令
public class Demo7 {
    public static void main(String[] args) {
        Frame frame = new Frame("myframe");
        frame.setBounds(200,200,500,500);

        Button b1 = new Button("start");
        b1.setActionCommand("red");		//点击button发送执行
        b1.addActionListener(new MyActionListener());

        frame.add(b1,BorderLayout.WEST);
        
        frame.setVisible(true);
    }
}
class MyActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("click -->"+e.getActionCommand());
    }
}

TextField

  • 代码:
public class Demo {
    public static void main(String[] args) {
        Frame frame = new Frame();
        TextField textField = new TextField();
        textField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getSource().toString());
            }
        });
        textField.setEchoChar('*');

        frame.add(textField);

        frame.setVisible(true);
    }
}

自制计算器

  • 简易:传递三个textfield

  • 传递对象

public class Test01 {
    public static void main(String[] args) {
        new MyCalcualtor();
    }
}
class MyCalcualtor extends Frame{	//监听:传递自己this。可以得到旗下的num1~3
    TextField num1 = new TextField(10);	//此变量不可在constructor中,否则监听器无法访问此变量
    TextField num2 = new TextField(10);
    TextField num3 = new TextField(10);
    public MyCalcualtor(){
        Label label = new Label("+");
        Button button = new Button("=");
        button.addActionListener(new MyCalculatorListener(this));
        setLayout(new FlowLayout(FlowLayout.LEFT));

        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);
    }
}
class MyCalculatorListener implements ActionListener{
    MyCalcualtor myCalcualtor= null;
    public MyCalculatorListener(MyCalcualtor myCalcualtor){
        this.myCalcualtor = myCalcualtor;
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        int n1 = Integer.parseInt(myCalcualtor.num1.getText());
        int n2 = Integer.parseInt(myCalcualtor.num2.getText());

        myCalcualtor.num3.setText(""+(n1+n2));
        myCalcualtor.num1.setText("");
        myCalcualtor.num2.setText("");
    }
}
  • 把监听成为内部类,直接可以访问外部的num1~3
public class TextCalc {
    public static void main(String[] args) {
        new Calculator().LoadFrame();
    }
}

class Calculator extends Frame {
    TextField num1,num2,num3;
    public void LoadFrame(){
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(10);
        Label label = new Label("+");
        Button button = new Button("=");
        //传递对象(包含本身的所有参数),this
        button.addActionListener(new MyCalculatorListener());

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

        setVisible(true);
        pack();
    }
    //内部类,就不用传递了,直接利用就行了。内部类的最大好处就是随便访问外部类
    private class MyCalculatorListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());

            num3.setText(""+(n1+n2));
            num1.setText("");
            num2.setText("");
        }
    }
}

paint

  • 利用画笔:
public class Demo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
class MyFrame extends Frame{
    public MyFrame(){
        setVisible(true);
    }
    @Override
    public void paint(Graphics g) {		//直接执行,不用调用  
        g.drawOval(100,100,200,100);	
    }
}

MouseAdapter

  • 画出点点
public class Demo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
class MyFrame extends Frame{
    ArrayList<Point> array = new ArrayList<>();
    public MyFrame(){
        setVisible(true);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                array.add(new Point(e.getX(),e.getY()));
                repaint();
            }
        });
    }
    @Override
    public void paint(Graphics g) {
        Iterator<Point> iterator = array.iterator();
        while (iterator.hasNext()){
            Point next = iterator.next();
            g.fillOval(next.x,next.y,10,10);
        }
    }
}

keyPressed

  • 代码:
public class Demo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
class MyFrame extends Frame{
    ArrayList<Point> array = new ArrayList<>();
    public MyFrame() {
        setVisible(true);
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyChar() == 0x41) System.out.println("A++");
                System.out.println(e.getKeyChar());
            }
        });
    }
}

Swing

JFrame

  • JFrame入门

jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

public class Test {
    public void init(){
        JFrame jf = new JFrame("JFrame的title");
        jf.add(new JLabel("label1"));        

        jf.setVisible(true);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//如果没有,可以关窗口,但是无法退出程序
    }
    public static void main(String[] args) {
        new Test().init();
    }
}

contentPane

  • 面板: this.getContentPane()代替之前的JFrame/Frame
public class Demo {
    public static void main(String[] args) {
        new MyFrame().init();
    }
}
class MyFrame extends JFrame{
    public void init(){
        Container contentPane = this.getContentPane();	
        //可以设置大小,背景。懒得设置
        add(new JLabel("this is a jlable"));        

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

JDialog

  • 代码:
class MyFrame extends JFrame{
    public void init(){
        Container contentPane = this.getContentPane();
        JButton button = new JButton("button");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog jDialog = new JDialog();
                jDialog.setVisible(true);
            }
        });
        contentPane.add(button);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

JLable配合Icon

  • Lable上显示icon
public class Demo extends JFrame implements Icon{
    private int height;
    private int width;

    public Demo(int height, int width){
        this.height = height;
        this.width = width;
        //jLable调用this(icon)
        getContentPane().add(new JLabel("jLable",this,SwingConstants.CENTER));
        setVisible(true);
    }

    public static void main(String[] args) {
        new Demo(300,300);
    }
    
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,height);
    }
    @Override
    public int getIconWidth() {
        return this.height;
    }
    @Override
    public int getIconHeight() {
        return this.height;
    }
}
  • 得到路径url → 通url得到图片 → 再镶嵌到JLable中
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container contentPane = getContentPane();
        URL url = Demo.class.getResource("JVM.jpg"); //先找到路径url
        ImageIcon imageIcon = new ImageIcon(url);         //由url新建图片
        JLabel jLabel = new JLabel("标签",imageIcon,SwingConstants.CENTER);          //图片导入jLable;
        
        contentPane.add(jLabel);
        setVisible(true);
    }
}

JPanel

public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container pane = getContentPane();
        JPanel jPanel = new JPanel(new GridLayout(2, 3));
        for (int i = 0; i < 6; i++) {
            jPanel.add(new JButton(""+i));
        }
        add(jPanel);
        setVisible(true);
    }
}

JButton

  • 图片按钮
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container pane = getContentPane();
        URL url = Demo.class.getResource("tx.png");
        ImageIcon icon = new ImageIcon(url);
        JButton jButton = new JButton(icon);

        pane.add(jButton);
        setVisible(true);
    }
}
  • 单选按钮
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container container = getContentPane();
        setLayout(new FlowLayout());
        ButtonGroup buttonGroup = new ButtonGroup();    //  ButtonGroup
        for (int i = 0; i < 4; i++) {
            JRadioButton button = new JRadioButton("" + i);//JRadioButton
            buttonGroup.add(button);
            container.add(button);
        }
        setVisible(true);
    }
}

Checkbox

  • 复选按钮
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container container = getContentPane();
        setLayout(new FlowLayout());
        for (int i = 0; i < 4; i++) {
            container.add(new Checkbox(""+i));
        }
        setVisible(true);
    }
}

JComboBox

  • 静态下拉框。jComboBox.addItem("adair")
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container container = getContentPane();
        JComboBox<String> jComboBox = new JComboBox<>();
        for (int i = 0; i < 4; i++) {
            jComboBox.addItem(""+i);
        }
        add(jComboBox);
        setVisible(true);
    }
}
  • 动态列表框
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container container = getContentPane();
        Vector<String> vector = new Vector<>();
        JList jList = new JList(vector);        
        vector.add("Integer");
        vector.add("String");
        vector.add("Character");
        container.add(jList);
        setVisible(true);
    }
}

JTextField

  • 文本框
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        Container container = getContentPane();
        JTextField jTextField = new JTextField(40);
        container.add(jTextField,BorderLayout.WEST);
        setVisible(true);
    }
}

JPasswordField

public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){//可以不用container
        JPasswordField jPasswordField = new JPasswordField(10);
        jPasswordField.setEchoChar('@');
        add(jPasswordField);
        setVisible(true);
    }
}
  • 文本域
public class Demo extends JFrame{
    public static void main(String[] args) {
        new Demo();
    }
    public Demo(){
        JTextArea jTextArea = new JTextArea(400, 400);
        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        add(jScrollPane);
        setVisible(true);
    }
}

贪吃蛇

  • 贪吃蛇的流程
    • 定义一个数据、初始化
    • 画上去
    • 监听事件:键盘
  • 主函数和其他函数
package com.adair.snake;

import javax.swing.*;

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

        frame.add(new GamePanel());

        frame.setResizable(false);
        frame.setBounds(10,10,900,750);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//一定要有        
    }
}

分割线

package com.adair.snake;

import com.adair.lesson04.ImageIconDemo;

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

public class Data {
    //相对路径vs绝对路径
    public static URL headerURL = Data.class.getResource("statics/header.jpg");
    public static ImageIcon header = new ImageIcon(headerURL);

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

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

    public static URL foodURL = Data.class.getResource("statics/food.jpeg");
    public static ImageIcon food = new ImageIcon(foodURL);
}
  • 狂神写的
public class GamePanel extends JPanel implements KeyListener, ActionListener {

    int length;
    String fx;
    int[] snakeX = new int[600];
    int[] snakeY = new int[500];
    
    int score;

    //食物的坐标
    int foodx,foody;
    Random random = new Random();

    boolean isStart = false;//游戏默认暂停
    boolean isFail = false;//是否失败

    Timer timer = new Timer(100,this);

    public GamePanel(){
        init();
        setFocusable(true);//获得焦点事件
        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);
        //设置背景颜色
        setBackground(Color.cyan);

        //画广告
        Data.header.paintIcon(this,g,25,11);//广告栏
        g.fillRect(25,75,850,600);//默认的游戏界面

        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑",Font.BOLD,25));
        g.drawString("长度:"+length,750,25);
        g.drawString("分数:"+score,750,55);

        //画蛇头
        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]);//初始向右
        }else if(fx.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);//初始向右
        }else if(fx.equals("D")){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);//初始向右
        }

        //画食物
        Data.food.paintIcon(this,g,foodx,foody);

        //画身体
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//第i个身体坐标
        }
        if(isStart == false){
            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);
        }
    }

    //事件监听,1s = 10次
    @Override
    public void actionPerformed(ActionEvent e) {
        if(isStart &&isFail == false){
            //吃食物
            if(snakeX[0] == foodx&&snakeY[0] ==foody){
                length ++;
                foodx = 25 + 25*random.nextInt(34);
                foody = 75 + 25*random.nextInt(24);

                score += 10;

            }
            //蛇的上一个身体赋值给下一个身体(逻辑上),还没有画出来
            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();
        }

    }

    @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_RIGHT){
            fx = "R";
        }else if(keyCode == KeyEvent.VK_LEFT){
            fx = "L";
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
  • 我写的
package com.adair.snake;

import javafx.scene.input.KeyCode;

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;

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

//需要什么添加什么,而不是狂有什么,你就去复制什么
public class GamePanel extends JPanel implements KeyListener, ActionListener {

    int[] snakeX = new int[60];
    int[] snakeY = new int[60];
    int length;
    String fx ;

    int foodx,foody;
    int score;

    Random random = new Random();

    boolean isStart;
    boolean isFail;


    Timer timer = new Timer(100,this);

    public GamePanel(){
        setBackground(Color.blue);
        setFocusable(true);
        init();
        addKeyListener(this);


        timer.restart();

    }
    public void init(){
        snakeX[0] = 100;  snakeY[0] = 100;
        snakeX[1] = 75;   snakeY[1] = 100;
        snakeX[2] = 50;   snakeY[2] = 100;
        length = 3;

        foodx = 25 + 25*random.nextInt(34);
        foody = 75 + 25*random.nextInt(24);

        isStart = false;
        isFail = false;

        score = 0;
        fx = "R";
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        //画广告和游戏背景
        Data.header.paintIcon(this,g,25,15);
        g.setColor(Color.cyan);
        g.fillRect(25,75,850,600);

        //画食物
        Data.food.paintIcon(this,g,foodx,foody);
        //画头
        if(fx.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(fx.equals("D")){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else 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]);
        }

        //画身体
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }


        if(!isStart){
            g.setColor(Color.yellow);
            g.setFont(new Font("微软雅黑",Font.BOLD,30));
            g.drawString("按空格开始,准备好呀",300,300);
        }
        //画分数score
        g.setColor(Color.yellow);
        g.setFont(new Font("微软雅黑",Font.BOLD,25));
        g.drawString("score : "+score,750,40);
        if(isFail){
            g.drawString("你失败了,按空格重新开始",300,300);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(isStart && !isFail){
            //吃食物
            if(snakeX[0] == foodx&& snakeY[0] == foody){
                length++ ;
                score += 10;

                foodx = 25 + 25*random.nextInt(34);
                foody = 75 + 25*random.nextInt(24);
            }
            //蛇进行移动
            if(fx.equals("U")){
                for (int i = length-1; i > 0 ; i--) {
                    snakeX[i] = snakeX[i-1];
                    snakeY[i] = snakeY[i-1];
                }
                snakeY[0] -= 25;
            }else if(fx.equals("D")){
                for (int i = length-1; i > 0 ; i--) {
                    snakeX[i] = snakeX[i-1];
                    snakeY[i] = snakeY[i-1];
                }
                snakeY[0] += 25 ;
            }else if(fx.equals("R")){
                for (int i = length-1; i > 0 ; i--) {
                    snakeX[i] = snakeX[i-1];
                    snakeY[i] = snakeY[i-1];
                }
                snakeX[0] += 25;
            }else if(fx.equals("L")){
                for (int i = length-1; i > 0 ; i--) {
                    snakeX[i] = snakeX[i-1];
                    snakeY[i] = snakeY[i-1];
                }
                snakeX[0] -= 25;
            }
            if(snakeX[0] > 850) snakeX[0] = 25;
            if(snakeX[0] < 25) snakeX[0] = 850;
            if(snakeY[0] < 75) snakeY[0] = 650;
            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();
        }

    }



    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_SPACE){
            if(!isFail){
                isStart = !isStart;
            }else {
                init();
                repaint();
            }

        }

        if(keyCode == VK_W){
            if(fx.equals("D")){

            }else {
                fx = "U";
            }
        }else if(keyCode == VK_S){
            if(fx.equals("U")){

            }else {
                fx = "D";
            }

        }else if(keyCode == VK_D){
            if(fx.equals("L")){

            }else {
                fx = "R";
            }
        }else if(keyCode == VK_A){
            if(fx.equals("R")){

            }else {
                fx = "L";
            }
        }
            repaint();



    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
  • 核心代码
package com.adair.demo01;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Date;

public class GamePanel extends JPanel implements KeyListener , ActionListener {
    int length ;
    String direction;
    int[] snakeX = new int[50];
    int[] snakeY = new int[50];

    Timer timer = new Timer(100,this);

    public GamePanel(){

        setBackground(Color.black);
        setFocusable(true);
        init();
        addKeyListener(this);
        timer.start();
    }
    public void init(){
        length = 3;
        direction = "R";
        snakeX[0] = 150; snakeY[0] = 150;
        snakeX[1] = 125; snakeY[1] = 150;
        snakeX[2] = 100; snakeY[2] = 150;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        //游戏背景、广告
        g.setColor(Color.cyan);
        Data.header.paintIcon(this,g,25,15);    //广告
        g.fillRect(25,75,850,600);      //贪吃蛇界面
        //画蛇头
        if(direction.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(direction.equals("D")){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (direction.equals("L")){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(direction.equals("R")){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        //画蛇身体
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        for (int i = length-1; i > 0 ; i--) {
            snakeX[i] = snakeX[i-1];
            snakeY[i] = snakeY[i-1];
        }
        if(direction.equals("U")){
            snakeY[0] -= 25;
        }else if(direction.equals("D")){
            snakeY[0] += 25;
        }else if(direction.equals("L")){
            snakeX[0] -= 25;
        }else if(direction.equals("R")){
            snakeX[0] += 25;
        }
        repaint();
    }


    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            direction = "U";
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            direction = "D";
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            direction = "L";
        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            direction = "R";
        }
    }
    @Override
    public void keyTyped(KeyEvent e) {    }     //由于实现是KeyListener接口,不可删除
    @Override
    public void keyReleased(KeyEvent e) {    }   //由于实现是KeyListener接口,不可删除
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值