GUI编程
简介
GUI的核心技术:Swing AWT
AWT
组件和容器
Frame
import java.awt.*;
/**
* GUI的第一个界面
*/
public class Demo01 {
public static void main(String[] args) {
//Frame
Frame frame = new Frame("我的第一个Java图像界面窗口");
//设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置背景颜色
frame.setBackground(Color.BLUE);
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
import java.awt.*;
/**
* 展示多个窗口
*/
public class Demo02 {
public static void main(String[] args) {
MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.CYAN);
MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.GREEN);
MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.orange);
MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.PINK);
}
}
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);
setVisible(true);
setBounds(x,y,w,h);
}
}
Panel
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Panel 可以看成是一个空间,但是不能单独存在
*/
public class Demo03 {
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(Color.pink);
//panel 设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(Color.GREEN);
frame.add(panel);
frame.setVisible(true);
//监听事件,监听窗口关闭事件
//适配器模式
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭的时候需要做的事情
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
布局管理器
流式布局
import java.awt.*;
/**
* 流式布局
*/
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.setSize(200,200);
//把按钮添加上去
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setVisible(true);
}
}
东西南北中
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);
}
}
表格布局
import java.awt.*;
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();
frame.setVisible(true);
}
}
练习
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Test {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
frame.setSize(500,500);
frame.setLocation(300,300);
frame.setBackground(Color.CYAN);
frame.setLayout(new GridLayout(2,1));
//4个面板
Panel p1 = new Panel(new BorderLayout());
Panel p2 = new Panel(new GridLayout(2,1));
Panel p3 = new Panel(new BorderLayout());
Panel p4 = new Panel(new GridLayout(2,2));
//上面
p1.add(new Button("East-1"),BorderLayout.EAST);
p1.add(new Button("West-1"),BorderLayout.WEST);
p2.add(new Button("p2-btn-1"));
p2.add(new Button("p2-btn-2"));
p1.add(p2,BorderLayout.CENTER);
//下面
p3.add(new Button("East-2"),BorderLayout.EAST);
p3.add(new Button("West-2"),BorderLayout.WEST);
for (int i = 0; i < 4; i++) {
p4.add(new Button("for-"+i));
}
p3.add(p4,BorderLayout.CENTER);
frame.add(p1);
frame.add(p3);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
事件监听
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 Demo01 {
public static void main(String[] args) {
//按下按钮,触发一些事件
Frame frame = new Frame();
Button button = new Button();
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
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 MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* 多个按钮,共享一个事件
*/
public class Demo02 {
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) {
System.out.println("按钮被点击了:msg=>"+e.getActionCommand());
}
}
输入框(TextField)监听
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Demo03 {
public static void main(String[] args) {
new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame(){
TextField textField = new TextField();
add(textField);
//监听这个文本框输入的文字
MyActionListener2 myActionListener2 = new MyActionListener2();
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()); //获得输入框的文本
}
}
简易计算器
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(10);
//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);
setVisible(true);
pack();
}
}
//监听器类
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) {
//获得加数和被加数
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
//将运算结果放到第三个框
num3.setText(""+(n1+n2));
//清除前两个框
num1.setText("");
num2.setText("");
}
}
优化
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(10);
//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);
setVisible(true);
pack();
}
}
//监听器类
class MyCalculatorListener implements ActionListener{
Calculator calculator = null;
//获取三个变量
public MyCalculatorListener(Calculator calculator){
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
//获得加数和被加数
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("");
}
}
鼠标监听
目的:想要实现鼠标画画
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,400);
//存鼠标的点
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.GREEN);
g.fillOval(point.x,point.y,10,10);
}
}
//添加一个点到界面上
public void addPoint(Point point){
points.add(point);
}
private class MyMouseListener extends MouseAdapter {
//鼠标点击
@Override
public void mousePressed(MouseEvent e) {
MyFrame myFrame = (MyFrame) e.getSource();
//鼠标的点
myFrame.addPoint(new Point(e.getX(),e.getY()));
//每次点击鼠标都要重新画一次
myFrame.repaint();
}
}
}
窗口监听
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame(){
setVisible(true);
setBackground(Color.CYAN);
setBounds(100,100,600,600);
addWindowListener(new MyWindowListener());
}
class MyWindowListener extends WindowAdapter{
//激活窗口
@Override
public void windowActivated(WindowEvent e) {
System.out.println("WindowActivated");
}
//关闭窗口
@Override
public void windowClosing(WindowEvent e) {
//setVisible(false); //隐藏窗口
System.exit(0);
System.out.println("windowClosing");
}
}
}
键盘监听
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
super();
setBounds(1,1,300,400);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
//键盘按下
@Override
public void keyPressed(KeyEvent e) {
//获得按下的键是哪一个
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP){
System.out.println("上键");
}
}
});
}
}
Swing
窗口 面板
import javax.swing.*;
import java.awt.*;
public class Demo01 {
//init(); 初始化
public void init(){
JFrame jFrame = new JFrame();
jFrame.setVisible(true);
jFrame.setBounds(100,100,500,500);
jFrame.setBackground(Color.CYAN);
//设置文字
JLabel label = new JLabel("Swing");
jFrame.add(label);
//关闭窗口
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo01().init();
}
}
import javax.swing.*;
import java.awt.*;
public class Demo02 {
public static void main(String[] args) {
new MyJFrame2().init();
}
}
class MyJFrame2 extends JFrame{
public void init(){
this.setBounds(100,100,500,500);
this.setVisible(true);
JLabel label = new JLabel("Swing");
this.add(label);
//让文本标签居中
label.setHorizontalAlignment(SwingConstants.CENTER);
//获得一个容器
Container container = this.getContentPane();
container.setBackground(Color.GREEN);
}
}
JDialog弹窗
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* JDialog弹窗
*/
//主窗口
public class Demo03 extends JFrame {
public Demo03(){
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//容器
Container container = this.getContentPane();
//绝对布局
container.setLayout(null);
//按钮
JButton button = new JButton("点击弹窗");
button.setBounds(30,30,100,50);
//点击这个按钮的时候,弹出一个弹窗
button.addActionListener(new ActionListener() { //监听器
@Override
public void actionPerformed(ActionEvent e) {
//弹窗
new MyJDialogDemo();
}
});
container.add(button);
}
public static void main(String[] args) {
new Demo03();
}
}
//弹窗的窗口
class MyJDialogDemo extends JDialog{
public MyJDialogDemo(){
this.setVisible(true);
this.setBounds(100,100,300,300);
Container container = this.getContentPane();
container.setLayout(null);
container.add(new Label("JDialog"));
}
}
Icon ImageIcon标签
import javax.swing.*;
import java.awt.*;
public class Demo04 extends JFrame implements Icon {
private int width;
private int height;
public Demo04(){
}
public Demo04(int width,int height){
this.width = width;
this.height = height;
}
public void init(){
Demo04 icon = new Demo04(15, 15);
//图标放在标签,也可以放在按钮上
JLabel label = new JLabel("icontest",icon, SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo04().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;
}
}
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class Demo05 extends JFrame {
public Demo05(){
//获取图片的地址
JLabel label = new JLabel("ImageIcon");
URL url = Demo05.class.getResource("gy.jpg");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(100,100,1000,1000);
}
public static void main(String[] args) {
new Demo05();
}
}
文本域JScroll面板
import javax.swing.*;
import java.awt.*;
/**
* JScroll
*/
public class Demo07 extends JFrame {
public Demo07(){
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(20,50);
textArea.setText("啊啊啊啊啊啊啊啊啊啊啊啊");
//Scroll面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo07();
}
}
图片按钮 单选框 多选框
import javax.swing.*;
import java.awt.*;
import java.net.URL;
/**
* 图片按钮
*/
public class Demo08 extends JFrame {
public Demo08(){
Container container = this.getContentPane();
//将一个图片变为图标
URL resource = Demo08.class.getResource("gy.jpg");
ImageIcon imageIcon = new ImageIcon(resource);
//将图标放在按钮上
JButton button = new JButton();
button.setIcon(imageIcon);
button.setToolTipText("图片按钮");
container.add(button);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo08();
}
}
import javax.swing.*;
import java.awt.*;
/**
* 单选按钮
*/
public class Demo09 extends JFrame {
public Demo09(){
Container container = this.getContentPane();
//单选框
JRadioButton radioButton1 = new JRadioButton("JRadioButton01");
JRadioButton radioButton2 = new JRadioButton("JRadioButton02");
JRadioButton radioButton3 = new JRadioButton("JRadioButton03");
//由于单选框只能选择一个,分组,一个组中只能选择一个
ButtonGroup group = new ButtonGroup();
group.add(radioButton1);
group.add(radioButton2);
group.add(radioButton3);
container.add(radioButton1,BorderLayout.CENTER);
container.add(radioButton2,BorderLayout.NORTH);
container.add(radioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo09();
}
}
import javax.swing.*;
import java.awt.*;
/**
* 多选按钮
*/
public class Demo10 extends JFrame {
public Demo10(){
Container container = this.getContentPane();
//多选框
JCheckBox checkBox1 = new JCheckBox("JCheckBox01");
JCheckBox checkBox2 = new JCheckBox("JCheckBox02");
container.add(checkBox1,BorderLayout.NORTH);
container.add(checkBox2,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo10();
}
}
下拉框 列表框
import javax.swing.*;
import java.awt.*;
/**
* 下拉框
*/
public class Demo11 extends JFrame {
public Demo11(){
Container container = this.getContentPane();
JComboBox comboBox = new JComboBox();
comboBox.addItem(null);
comboBox.addItem("1");
comboBox.addItem("2");
comboBox.addItem("3");
container.add(comboBox);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo11();
}
}
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
/**
* 列表框
* 展示信息,一般是动态扩容
*/
public class Demo12 extends JFrame {
public Demo12(){
Container container = this.getContentPane();
//生成列表的内容
//String[] contents = {"1","2","3"};
Vector vector = new Vector();
//列表中需要放入内容
JList jList = new JList(vector);
vector.add("1");
vector.add("2");
vector.add("3");
container.add(jList);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo12();
}
}
文本框 密码框 文本域
import javax.swing.*;
import java.awt.*;
/**
* 文本框
*/
public class Demo13 extends JFrame {
public Demo13(){
Container container = this.getContentPane();
JTextField textField1 = new JTextField("ggggg");
JTextField textField2 = new JTextField("yyyyy",20);
container.add(textField1,BorderLayout.NORTH);
container.add(textField2,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo13();
}
}
import javax.swing.*;
import java.awt.*;
/**
* 密码框
*/
public class Demo14 extends JFrame {
public Demo14(){
Container container = this.getContentPane();
JPasswordField jPasswordField = new JPasswordField();
jPasswordField.setEchoChar('*');
container.add(jPasswordField);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo14();
}
}
import javax.swing.*;
import java.awt.*;
/**
* 文本域
*/
public class Demo15 extends JFrame {
public Demo15(){
Container container = this.getContentPane();
JTextArea textArea = new JTextArea(10, 10);
textArea.setText("111111111111111111111111");
container.add(textArea);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo15();
}
}
贪吃蛇实例
import javax.swing.*;
//游戏的主启动类
public class StartGame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setResizable(false); //窗口大小不可变
frame.setBounds(10,10,900,720);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//游戏界面应该在面板上
frame.add(new GamePanel());
frame.setVisible(true);
}
}
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
//相对路径 header.png
//绝对路径 /statics/header.png
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 URL downURL = Data.class.getResource("statics/down.png");
public static URL leftURL = Data.class.getResource("statics/left.png");
public 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);
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);
}
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];
int[] snakeY = new int[500];
String fx; //蛇头的方向
//食物的坐标
int foodX;
int foodY;
Random random = new Random();
int score; //成绩
//游戏状态:开始 停止
boolean isStart = false; //默认停止
//游戏状态:默认未失败
boolean isFail = false;
//定时器 以毫秒为单位
Timer timer = new Timer(100,this); //100毫秒执行一次
//构造器
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,32);
g.drawString("分数:"+score,750,52);
//食物
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]);
}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]);
}
//身体
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,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++; //长度加1
//分数加10
score = 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];
}
//走向
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();
}
//键盘监听事件
@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) {
}
}
标签:java,GUI,编程,add,frame,import,new,public
From: https://www.cnblogs.com/gy486926/p/17627302.html