Lesson17:JAVA GUI

Day17:JAVA GUI编程

  • GUI核心技术:Swing、AWT

  • 按住CTRL+鼠标左键才能进入类源码

AWT

Frame

image-20210701214519025

package test;

import java.awt.*;

public class MyFrame extends Frame {

  static int id = 1;

  public MyFrame(int x,int y,int w,int h,Color color){
      super("MyFrame"+(id++));
      setLocation(x,y);
      setSize(w,h);
      setBackground(color);
      setResizable(false);
      setVisible(true);
  }

  public static void main(String[] args) {
      MyFrame myFrame1 = new MyFrame(100, 100, 400, 400, Color.BLUE);
      MyFrame myFrame2 = new MyFrame(500, 100, 400, 400, Color.BLACK);
      MyFrame myFrame3 = new MyFrame(100, 500, 400, 400, Color.CYAN);
      MyFrame myFrame4 = new MyFrame(500, 500, 400, 400, Color.GREEN);
      System.out.println(id);
  }

}

Panel

panel不能单独存在

package test;

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

public class TestPlane {

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

      //设置布局(null为绝对布局)
      frame.setLayout(null);

      //坐标
      frame.setBounds(50,100,500,400);
      frame.setBackground(new Color(40,60,80));

      //panel设置坐标,相对于frame
      panel.setBounds(50,50,150,100);
      panel.setBackground(new Color(80,15,6));

      frame.add(panel);
      frame.setVisible(true);

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

布局管理器

  • 流式布局(左-》右)

package test;

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

public class TestFlowLayout {
  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.LEFT));
      frame.setLayout(new FlowLayout(FlowLayout.RIGHT));

      frame.setSize(500,500);

      frame.add(button1);
      frame.add(button2);
      frame.add(button3);

      frame.addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      frame.setVisible(true);
  }
}
  • 东西南北中

package test;

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

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

      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.setSize(500,500);

      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.addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      frame.setVisible(true);
  }
}
  • 网格布局

package test;

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

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

      Button b1 = new Button("b1");
      Button b2 = new Button("b2");
      Button b3 = new Button("b3");
      Button b4 = new Button("b4");
      Button b5 = new Button("b5");
      Button b6 = new Button("b6");

      frame.setLayout(new GridLayout(2,3));

      frame.setSize(500,500);

      frame.add(b1);
      frame.add(b2);
      frame.add(b3);
      frame.add(b4);
      frame.add(b5);
      frame.add(b6);

      frame.addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      //frame.pack();   //JAVA函数!作用是最优展示
      frame.setVisible(true);
  }
}

事件监听

package test.gui;

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 TestMonitor {
  public static void main(String[] args) {

      Frame frame = new Frame("多组件添加同一监听器");

      Button start = new Button("start");
      Button stop = new Button("stop");

      MyMonitor myMonitor = new MyMonitor();

      stop.setActionCommand("noStop-reset");

      start.addActionListener(myMonitor);
      stop.addActionListener(myMonitor);

      frame.add(start,BorderLayout.NORTH);
      frame.add(stop,BorderLayout.SOUTH);

      frame.addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });
      frame.pack();
      frame.setVisible(true);

  }
}

class MyMonitor implements ActionListener{
  @Override
  public void actionPerformed(ActionEvent e) {
      System.out.println("您点击了=>"+e.getActionCommand()+"按钮");
  }
}

简易计算器

最LOW的写法

package test.gui;

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 TestMyCalculator {
  public static void main(String[] args) {
      new MyCalculator();
  }
}

class MyCalculator extends Frame{
  public MyCalculator() throws HeadlessException {
      TextField operator1 = new TextField(10);
      TextField operator2 = new TextField(10);
      TextField result = new TextField(20);

      Button equalButton = new Button("=");
      equalButton.addActionListener(new MyCalculatorActionListener(operator1,operator2,result));

      Label plusLabel = new Label("+");

      setLayout(new FlowLayout());

      add(operator1);
      add(plusLabel);
      add(operator2);
      add(equalButton);
      add(result);

      addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      pack();
      setVisible(true);
  }
}

class MyCalculatorActionListener implements ActionListener{

  private TextField num1,num2,num3;

  public MyCalculatorActionListener(TextField num1,TextField num2,TextField num3) {
      this.num1=num1;
      this.num2=num2;
      this.num3=num3;
  }

  @Override
  public void actionPerformed(ActionEvent e) {
      //1.获取操作数一和操作数二
      int opr1 = Integer.parseInt(num1.getText());
      int opr2 = Integer.parseInt(num2.getText());

      //2.把计算结果赋给操作数三
      num3.setText(""+(opr1+opr2));

      //3.清空操作数一和操作数二
      num1.setText("");
      num2.setText("");
  }
}

面向对象写法

package test.gui;

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 TestMyCalculator {
  public static void main(String[] args) {
      new MyCalculator().openFrame();
  }
}

class MyCalculator extends Frame{

  TextField num1,num2,num3;

  public void openFrame(){

      num1 = new TextField(10);
      num2 = new TextField(10);
      num3 = new TextField(20);
      Label plusLabel = new Label("+");
      Button equalButton = new Button("=");

      equalButton.addActionListener(new MyCalculatorActionListener(this));
      addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      setLayout(new FlowLayout());
      add(num1);
      add(plusLabel);
      add(num2);
      add(equalButton);
      add(num3);
      pack();

      setVisible(true);

  }

}

class MyCalculatorActionListener implements ActionListener{

  MyCalculator calculator;

  public MyCalculatorActionListener(MyCalculator calculator) {
      this.calculator = calculator;
  }

  @Override
  public void actionPerformed(ActionEvent e) {
      //1.获取操作数一和操作数二
      int opr1 = Integer.parseInt(calculator.num1.getText());
      int opr2 = Integer.parseInt(calculator.num2.getText());

      //2.把计算结果赋给操作数三
      calculator.num3.setText(""+(opr1+opr2));

      //3.清空操作数一和操作数二
      calculator.num1.setText("");
      calculator.num2.setText("");
  }
}

内部类写法

package test.gui;

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 TestMyCalculator {
  public static void main(String[] args) {
      new MyCalculator().openFrame();
  }
}

class MyCalculator extends Frame{

  TextField num1,num2,num3;

  public void openFrame(){

      num1 = new TextField(10);
      num2 = new TextField(10);
      num3 = new TextField(20);
      Label plusLabel = new Label("+");
      Button equalButton = new Button("=");

      equalButton.addActionListener(new MyCalculatorActionListener());
      addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      setLayout(new FlowLayout());
      add(num1);
      add(plusLabel);
      add(num2);
      add(equalButton);
      add(num3);
      pack();

      setVisible(true);

  }

  private class MyCalculatorActionListener implements ActionListener{

      @Override
      public void actionPerformed(ActionEvent e) {

          int opr1 = Integer.parseInt(num1.getText());
          int opr2 = Integer.parseInt(num2.getText());

          num3.setText(""+(opr1+opr2));
          num1.setText("");
          num2.setText("");
      }
  }

}

画笔

package test.gui;

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

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

class MyPaint extends Frame{

  public void loadFrame(){

      addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      setBounds(200,200,600,480);
      setVisible(true);
  }

  @Override
  public void paint(Graphics g) {
      //super.paint(g);
      g.setColor(Color.red);
      //g.drawOval(200,200,150,150);
      g.fillOval(150,150,150,150);

      g.setColor(Color.green);
      g.fillRect(200,300,200,200);
  }
}

鼠标监听

package test.gui;

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

public class TestMouseListener {

  public static void main(String[] args) {
      new MyMouseListenerFrame("画图");
  }

}

class MyMouseListenerFrame extends Frame{

  ArrayList points;

  public MyMouseListenerFrame(String title) throws HeadlessException {
      super(title);

      points = new ArrayList<>();

      addMouseListener(new MyMouseListener());
      addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      setBounds(200,200,600,500);
      setVisible(true);
  }

  @Override
  public void paint(Graphics g) {

      Iterator iterator = points.iterator();
      while (iterator.hasNext()){
          Point point = (Point)iterator.next();
          g.setColor(Color.BLACK);
          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) {
          MyMouseListenerFrame mmlf = (MyMouseListenerFrame)e.getSource();
          mmlf.addPaint(new Point(e.getX(),e.getY()));
          mmlf.repaint();
      }
  }

}

窗口监听

addWindowListener(new WindowAdapter() {
  @Override
  public void windowClosing(WindowEvent e) {
      System.exit(0);
  }

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

键盘监听

package test.gui;

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

public class TestKeyListener {
  public static void main(String[] args) {
      new MyKeyFrame();
  }
}

class MyKeyFrame extends Frame{

  public MyKeyFrame() throws HeadlessException {

      setBounds(100,100,600,500);

      addKeyListener(new KeyAdapter() {
          @Override
          public void keyPressed(KeyEvent e) {
              int keyCode = e.getKeyCode();
              System.out.println(keyCode);
              if(keyCode == KeyEvent.VK_UP){
                  System.out.println("你按了上键");
              }
          }
      });
      addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });

      setVisible(true);
  }
}

Swing

AWT是基础,Swing是封装过的

窗口、面板

package test.swing;

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

public class TestSwingDemo {

  public void init(){
      JFrame jFrame = new JFrame();
      jFrame.setBounds(100,100,600,500);

      JLabel jLabel = new JLabel("文字");
      jLabel.setHorizontalAlignment(SwingConstants.CENTER);
      jFrame.add(jLabel);

      Container container = jFrame.getContentPane();
      container.setBackground(Color.CYAN);

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

  public static void main(String[] args) {
          new TestSwingDemo().init();
  }
}

弹窗

package test.swing;

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

public class DialogDemo extends JFrame {

  public DialogDemo() throws HeadlessException {

      setSize(600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      Container container = getContentPane();
      container.setLayout(null);

      JButton jButton = new JButton("弹出一个新窗口");
      jButton.setBounds(50,50,150,50);
      jButton.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
              new MyDialogDemo();
          }
      });

      container.add(jButton);

      setVisible(true);

  }

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

class MyDialogDemo extends JDialog{
  public MyDialogDemo() {
      setBounds(100,100,520,480);
      setVisible(true);
      Container container = getContentPane();
      container.setLayout(null);
      JLabel jLabel = new JLabel("这是个弹窗");
      jLabel.setSize(150,50);
      jLabel.setHorizontalAlignment(SwingConstants.CENTER);
      container.add(jLabel);
  }
}

Icon、ImageIcon标签

package test.swing;

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

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(10, 10);
      JLabel jLabel = new JLabel("icontest", iconDemo, SwingConstants.CENTER);

      Container container = getContentPane();
      container.add(jLabel);

      setVisible(true);
      setBounds(100,100,600,500);
      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 width;
  }

  @Override
  public int getIconHeight() {
      return height;
  }
}
package test.swing;

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

public class ImageIconDemo extends JFrame {

  public ImageIconDemo() throws HeadlessException {

      JLabel jLabel = new JLabel("imageIcon");
      URL url = ImageIconDemo.class.getResource("dnfgirl1.jpg");

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

      Container container = getContentPane();
      container.add(jLabel);

      setVisible(true);
      setBounds(100,100,600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

  }

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

}

面板与文本域

package test.swing;

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

public class JScrollDemo extends JFrame {
  public JScrollDemo() {
      JTextArea jTextArea = new JTextArea(20, 20);
      jTextArea.setText("这是文本域");

      JScrollPane jScrollPane = new JScrollPane(jTextArea);

      Container container = getContentPane();
      container.add(jScrollPane);

      setVisible(true);
      setBounds(100,100,600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  }

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

按钮

单选按钮

package test.swing;

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

public class JRadioButtonDemo extends JFrame {
  public JRadioButtonDemo() throws HeadlessException {
      Container container = getContentPane();
      URL resource = JRadioButtonDemo.class.getResource("dnfgirl1.jpg");
      Icon icon = new ImageIcon(resource);

      JRadioButton jRadioButton01 = new JRadioButton("按钮I");
      JRadioButton jRadioButton02 = new JRadioButton("按钮II");
      JRadioButton jRadioButton03 = new JRadioButton("按钮III");

      ButtonGroup buttonGroup = new ButtonGroup();
      buttonGroup.add(jRadioButton01);
      buttonGroup.add(jRadioButton02);
      buttonGroup.add(jRadioButton03);

      container.add(jRadioButton01,BorderLayout.NORTH);
      container.add(jRadioButton02,BorderLayout.CENTER);
      container.add(jRadioButton03,BorderLayout.SOUTH);

      setVisible(true);
      setBounds(100,100,600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  }

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

复选按钮

package test.swing;

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

public class JCheckBoxDemo extends JFrame {
  public JCheckBoxDemo() throws HeadlessException {
      Container container = getContentPane();
      URL resource = JRadioButtonDemo.class.getResource("dnfgirl1.jpg");
      Icon icon = new ImageIcon(resource);

      JCheckBox jCheckBox1 = new JCheckBox("复选框I");
      JCheckBox jCheckBox2 = new JCheckBox("复选框II");

      container.add(jCheckBox1,BorderLayout.NORTH);
      container.add(jCheckBox2,BorderLayout.SOUTH);

      setVisible(true);
      setBounds(100,100,600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  }

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

下拉框与列表框

package test.swing;

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

public class JComboBoxDemo extends JFrame {
  public JComboBoxDemo() throws HeadlessException {
      Container container = getContentPane();

      JComboBox jComboBox = new JComboBox();

      jComboBox.addItem(null);
      jComboBox.addItem("已完成");
      jComboBox.addItem("进行中");
      jComboBox.addItem("计划阶段");

      container.add(jComboBox);

      setVisible(true);
      setBounds(100,100,600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  }

  public static void main(String[] args) {
      new JComboBoxDemo();
  }
}
package test.swing;

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

public class JListDemo extends JFrame {
  public JListDemo() throws HeadlessException {
      Container container = getContentPane();

      //String[] data = {"1","2","3"};
      Vector datas = new Vector();

      JList jList = new JList(datas);

      datas.add("张三");
      datas.add("李四");
      datas.add("王五");

      container.add(jList);

      setVisible(true);
      setBounds(100,100,600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  }

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

文本框与密码框

package test.swing;

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

public class JTextFieldAndJPasswordFieldDemo extends JFrame {
  public JTextFieldAndJPasswordFieldDemo() throws HeadlessException {
      Container container = getContentPane();
      container.setLayout(new FlowLayout());

      JTextField jTextField1 = new JTextField("文本框I");
      JTextField jTextField2 = new JTextField("文本框II",20);

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

      container.add(jTextField1);
      container.add(jTextField2);
      container.add(passwordField);

      setVisible(true);
      setBounds(100,100,600,500);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  }

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

游戏实战

贪吃蛇

package test.snake;

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

public class Data {

  public static URL headURL = Data.class.getResource("head.png");
  public static ImageIcon head = new ImageIcon(headURL);

  public static URL headDownURL = Data.class.getResource("head-down.png");
  public static URL headUpURL = Data.class.getResource("head-up.png");
  public static URL headLeftURL = Data.class.getResource("head-left.png");
  public static URL headRightURL = Data.class.getResource("head-right.png");

  public static ImageIcon headDown = new ImageIcon(headDownURL);
  public static ImageIcon headUp = new ImageIcon(headUpURL);
  public static ImageIcon headLeft = new ImageIcon(headLeftURL);
  public static ImageIcon headRight = new ImageIcon(headRightURL);

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

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

//   public static void main(String[] args) {
//       if(headURL==null){
//           System.out.println("图片路径不正确:"+headURL.toString());
//       }else{
//           System.out.println("图片路径正确");
//       }
//   }

}
package test.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 = 0;
  int[] snakeX = new int[600];
  int[] snakeY = new int[500];

  String fx;

  boolean isStart = false;
  boolean isFail = false;

  int foodx;
  int foody;
  Random random = new Random();

  int score;

  Timer timer = new Timer(500,this);

  public GamePanel() {
      init();
      setFocusable(true);
      addKeyListener(this);
      timer.start();
  }

  public void init() {

      length = 3;
      snakeX[0] = 300;
      snakeY[0] = 250;
      snakeX[1] = 200;
      snakeY[1] = 250;
      snakeX[2] = 100;
      snakeY[2] = 250;
      fx = "R";

      foodx = 100 + 100*random.nextInt(20);
      foody = 100 + 100*random.nextInt(20);

      score = 0;

  }

  @Override
  protected void paintComponent(Graphics g) {
      super.paintComponent(g);   //清屏
      this.setBackground(Color.WHITE);

      Data.head.paintIcon(this, g, 25, 11);
      g.fillRect(25, 250, 1025, 660);

      g.setColor(Color.white);
      g.setFont(new Font("微软雅黑",Font.BOLD,20));
      g.drawString("长度 "+length,800,40);
      g.drawString("分数 "+score,800,60);

      Data.food.paintIcon(this,g,foodx,foody);

      if (fx.equals("R")) {
          Data.headRight.paintIcon(this, g, snakeX[0], snakeY[0]);
      } else if (fx.equals("L")) {
          Data.headLeft.paintIcon(this, g, snakeX[0], snakeY[0]);
      } else if (fx.equals("U")) {
          Data.headUp.paintIcon(this, g, snakeX[0], snakeY[0]);
      } else if (fx.equals("D")) {
          Data.headDown.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 == false) {
          g.setColor(Color.white);
          g.setFont(new Font("微软雅黑", Font.BOLD, 50));
          g.drawString("按下空格开始游戏!", 300, 500);
      }

      if (isFail) {
          g.setColor(Color.red);
          g.setFont(new Font("微软雅黑", Font.BOLD, 50));
          g.drawString("失败!按空格重新开始", 300, 500);
      }

  }

  @Override
  public void keyTyped(KeyEvent e) {}

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

      //repaint();
  }

  @Override
  public void keyReleased(KeyEvent e) {}

  @Override
  public void actionPerformed(ActionEvent e) {
      if(isStart && isFail==false){

          if(snakeX[0]-foodx<50 && snakeY[0]-foody<50){
              length++;
              score+=10;
              foodx = 100 + 100*random.nextInt(4);
              foody = 100 + 100*random.nextInt(4);
          }

          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]+100;
              if(snakeX[0]>1000){ snakeX[0] = 25; }
          }else if(fx.equals("L")){
              snakeX[0] = snakeX[0]-100;
              if(snakeX[0]<25){ snakeX[0] = 1000; }
          }else if(fx.equals("U")){
              snakeY[0] = snakeY[0]-100;
              if(snakeY[0]<200){ snakeY[0] = 800; }
          }else if(fx.equals("D")){
              snakeY[0] = snakeY[0]+100;
              if(snakeY[0]>800){ snakeY[0] = 200; }
          }

          for (int i=1;i<length;i++){
              if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
                  isFail = true;
              }
          }

          repaint();
      }
      timer.start();
  }
}
package test.snake;

import javax.swing.*;

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

      jFrame.add(new GamePanel());

      jFrame.setResizable(false); //设置窗口大小不可变
      jFrame.setBounds(10,10,1095,1000);
      jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

      jFrame.setVisible(true);
  }
}

 

posted @ 2021-08-15 23:52  Layman52  阅读(49)  评论(0)    收藏  举报