GUI编程之贪吃蛇
一、GUI编程
已经快淘汰了
怎么学?
- 这是什么?
- 它怎么玩?
- 该如何在平时运用?
不是java强项,但可以做。
组件
- 窗口
- 弹窗
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件(web会有)
- 鼠标
- 键盘事件
1、简介
Gui的核心技术: Swing AWT
1.界面不美观
2.需要jre环境
为什么要学习?
- 可以写出自己心中想要的一些小工具
- 工作时候,也可能维护到swing界面,但概率极小。
- 了解MVC架构,了解监听!
2、AWT(Swing前身,讲底层的实现)
2.1 AWT介绍
- 包含了很多类和接口!GUI:图像用户界面。 Eeclipse:java环境写的
- 元素:窗口、按钮、文本框
- java.awt包里
2.2、组件和容器
1、Frame
package com.shuai.lesson1;import java.awt.*;//GUI的第一个界面public class TestFrame {public static void main(String[] args) {//Frame,JDK 看源码;Frame frame = new Frame("我的第一个java图形界面窗口");//设置可见性 w h 没有frame.setVisible(true);//设置窗口大小frame.setSize(400, 400);//背景颜色 ColorColor color = new Color(155, 89, 104);frame.setBackground(color);//弹出的初始位置frame.setLocation(200, 200);//设置大小固定frame.setResizable(false);}}
问题:窗口无法关闭—》java停止运行
尝试回顾封装:
package com.shuai.lesson1;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(500, 100, 200, 200, Color.RED);MyFrame myFrame4 = new MyFrame(700, 100, 200, 200, Color.BLACK);}}class MyFrame extends Frame{//除了Frame方法以外,还有自己的方法static int id = 0;//可能存在多个窗口,我们需要一个计数器//构造器封装一下public MyFrame(int x,int y, int w,int h,Color color){super("MyFrame+"+(++id));setBackground(color);setVisible(true);//相当于初始位置x,y和窗口大小w hsetBounds(x,y,w,h);setResizable(false);}}`
2、面板panel
解决了无法关闭问题,即调用addWindowsListener方法的子方法,并重写其中的WindowsClosing方法,来调用程序关闭的.exit(0)方法
package com.shuai.lesson1;import java.awt.*;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;//Panel 可以看成一个空间,但是不能单独存在,得放在Frame上public class TsetPanel {public static void main(String[] args) {//窗口Frame frame = new Frame();//布局的概念//面板Panel panel = new Panel();/*设置布局 不设置会默认置顶未设置Layout时,java默认为flowLayout布局的,设置为null即为清空布局管理器,之后添加组件,常常是设置组件左上角坐标相对于容器左上角(0,0)的x,y值来确定组件的位置,即使更改容器大小也不会改变位置。这种方式常常用于窗体大小固定的容器里。*/frame.setLayout(null);//坐标frame.setBounds(300,300,500,500);frame.setBackground(new Color(59, 164, 125));//panel 设置坐标,相对于Frame的坐标panel.setBounds(50,50,200,200);panel.setBackground(new Color(90, 46, 30));//frame.add(panel)frame添加面板frame.add(panel);//Panel经过三层继承,最终继承了Componentframe.setVisible(true);//监听时间,监听窗口关闭事件 System.exit(0)//适配器模式: new 重写的太多了 new其子类 本来new WindowsListener的,但是要重写的实在太多了frame.addWindowListener(new WindowAdapter() {//窗口点击关闭的时候需要做的事情@Overridepublic void windowClosing(WindowEvent e) {//结束程序System.exit(0);}});}}
2.3、布局管理器
流式布局 从左到右
package com.shuai.lesson1;import java.awt.*;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class TsetFlowLayout {public static void main(String[] args) {Frame frame = new Frame();//组件-按钮Button button1 = new Button("button1");Button button2 = new Button("button2");Button button3 = new Button("button3");//设置为流式布局//frame.setLayout(new FlowLayout());默认是中//frame.setLayout(new FlowLayout(FlowLayout.LEFT));frame.setLayout(new FlowLayout(FlowLayout.RIGHT));frame.setSize(200,200);frame.setVisible(true);frame.add(button1);frame.add(button2);frame.add(button3);frame.addWindowListener(new WindowAdapter() {//窗口点击关闭的时候需要做的事情@Overridepublic void windowClosing(WindowEvent e) {//结束程序System.exit(0);}});}}
东西南北中
package com.shuai.lesson1;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("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(300,300);frame.setVisible(true);frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});}}
表格布局三行两列这种Grid
package com.shuai.lesson1;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("TsetGridLayout");Button button1 = new Button("button1");Button button2 = new Button("button2");Button button3 = new Button("button3");Button button4 = new Button("button4");Button button5 = new Button("button5");Button button6 = new Button("button6");frame.setLayout(new GridLayout(3,2));frame.add(button1);frame.add(button2);frame.add(button3);frame.add(button4);frame.add(button5);frame.add(button6);frame.pack();//让布局变得好看frame.setVisible(true);frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});}}
<img src="image-20210225151302140.png" alt="image-20210225151302140" style="zoom: 50%;" />
练习 做出如下界面
<img src="image-20210225155103185.png" alt="image-20210225155103185" style="zoom:50%;" />
- 分析过程

- 代码实现
package com.shuai.lesson1;import jdk.nashorn.api.tree.NewTree;import java.awt.*;import java.io.FileOutputStream;public class TestLayoutLianxi {public static void main(String[] args) {Frame frame = new Frame("TestLayoutLianxi");frame.setSize(400,300);frame.setLocation(300,300);frame.setBackground(Color.BLUE);frame.setVisible(true);frame.setLayout(new GridLayout(2,1));Panel panel1 = new Panel(new BorderLayout());Panel panel2 = new Panel(new GridLayout(2,1));Panel panel3 = new Panel(new BorderLayout());Panel panel4 = new Panel(new GridLayout(2,2));Button button1 = new Button("BUTTON1");Button button2 = new Button("BUTTON2");Button button3 = new Button("BUTTON3");Button button4 = new Button("BUTTON4");Button button5 = new Button("BUTTON5");Button button6 = new Button("BUTTON6");Button button7 = new Button("BUTTON7");Button button8 = new Button("BUTTON8");Button button9 = new Button("BUTTON9");Button button10 = new Button("BUTTON10");panel1.add(button1,BorderLayout.EAST);panel1.add(button2,BorderLayout.WEST);panel2.add(button3);panel2.add(button4);panel1.add(panel2,BorderLayout.CENTER);panel3.add(button5,BorderLayout.EAST);panel3.add(button6,BorderLayout.WEST);panel4.add(button7);panel4.add(button8);panel4.add(button9);panel4.add(button10);panel3.add(panel4,BorderLayout.CENTER);frame.add(panel1);frame.add(panel3);}}
之前的知识总结
-
Frame是一个顶级窗口
-
Panel无法单独显示,必须添加到某个容器中
- 布局管理器
- 流失
- 东西南北中
- 表格
- 标题,大小,定位,背景颜色,可见性,监听
2.4、事件监听
事件监听:当某个事件发生的时候,干什么?
package com.shuai.lesson2;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 TestActionEvent {public static void main(String[] args) {//按下按钮,触发一些事件Frame frame = new Frame();Button button1 = new Button("button1");//因为addActionListener需要ActionListener,因此我们需要构造一个ActionListenerMyActionListener myActionListener = new MyActionListener();button1.addActionListener(new MyActionListener());frame.add(button1, BorderLayout.CENTER);frame.pack();frame.setVisible(true);windowsClosing(frame);}//关闭窗体的事件private static void windowsClosing(Frame frame){frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});}//事件监听static class MyActionListener implements ActionListener {@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("11");}}}
多个按钮共享一个事件
package com.shuai.lesson2;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.FileOutputStream;public class TestActionEvent2 {public static void main(String[] args) {//两个按钮,实现同一个监听Frame frame = new Frame("1111");Button button1 = new Button("start");Button button2 = new Button("stop");//可以显示的定义出发会返回的命令,如果不显示定义,则会走默认值//可以多个按钮只写一个监听类button1.setActionCommand("3333");My my = new My();button1.addActionListener(my);button2.addActionListener(my);frame.add(button1, BorderLayout.WEST);frame.add(button2, BorderLayout.EAST);frame.pack();frame.setVisible(true);}static class My implements ActionListener {@Overridepublic void actionPerformed(ActionEvent e) {//e.getActionCommand()获得按钮的信息System.out.println("按钮被点击了:msg" + e.getActionCommand());}}}
2.5、输入框事件监听TextField
输入框中输入的字,可以打印出来,并将输入的字全部删除。
package com.shuai.lesson2;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);//监听这个文本框输入的文字//按下回车键,就会触发这个输入框的事件,在下边的重写方法中重写的语句为 获得输入框的文本并打印textField.addActionListener(new My());//设置替换编码textField.setEchoChar('*');setVisible(true);pack();}}class My implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) {TextField text = (TextField) e.getSource();//获得一些资源,返回的一个对象System.out.println(text.getText());//获得输入框的文本//每次都设置为空 即每次文本框输入完以后,都会全部删除清零text.setText("");}}
2.6、简易计算器,组合+内部类回顾复习
oop原则:组合,大于继承
初始版本
package com.shuai.lesson2;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.TextEvent;public class TestCALC {public static void main(String[] args) {new Calculator();}}//计算器类class Calculator extends Frame {public Calculator() {//3个文本框TextField textField = new TextField(10);//字符数TextField textField1 = new TextField(10);//字符数TextField textField2 = new TextField(20);//字符数//1 个按钮Button button = new Button("=");button.addActionListener(new MyAL(textField,textField1,textField2));//1个标签Label label = new Label("+");setLayout(new FlowLayout());add(textField);add(label);add(textField1);add(button);add(textField2);pack();setVisible(true);}}//监听器类class MyAL implements ActionListener {//获取三个变量private TextField textField,textField1,textField2;public MyAL(TextField textField, TextField textField1, TextField textField2){this.textField = textField;this.textField1 = textField1;this.textField2 = textField2;}@Overridepublic void actionPerformed(ActionEvent e) {//1.获得加数和被加数int n = Integer.parseInt(textField.getText());int n1 = Integer.parseInt(textField1.getText());//2.将这个值加法运算后,放到第三个框textField2.setText(""+(n+n1));//3.清除前两个框textField.setText("");textField1.setText("");}}
改进版本
- 完全改造成面向对象
package com.shuai.lesson2;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.TextEvent;public class TestCALC {public static void main(String[] args) {new Calculator().loadFrame();}}//计算器类//方法class Calculator extends Frame {//属性TextField textField;TextField textField1;TextField textField2;//方法public void loadFrame() {//3个文本框textField = new TextField(10);//字符数textField1 = new TextField(10);//字符数textField2 = new TextField(20);//字符数//1 个按钮Button button = new Button("=");button.addActionListener(new MyAL(this));//1个标签Label label = new Label("+");setLayout(new FlowLayout());add(textField);add(label);add(textField1);add(button);add(textField2);pack();setVisible(true);}}//监听器类class MyAL implements ActionListener {/* //获取三个变量private TextField textField,textField1,textField2;public MyAL(TextField textField, TextField textField1, TextField textField2){this.textField = textField;this.textField1 = textField1;this.textField2 = textField2;}@Overridepublic void actionPerformed(ActionEvent e) {//1.获得加数和被加数int n = Integer.parseInt(textField.getText());int n1 = Integer.parseInt(textField1.getText());//2.将这个值加法运算后,放到第三个框textField2.setText(""+(n+n1));//3.清除前两个框textField.setText("");textField1.setText("");}}*///改进算法//获取计算器这个对象,在一个类中组合另外一个类Calculator calculator = null;public MyAL(Calculator calculator) {this.calculator = calculator;}@Overridepublic void actionPerformed(ActionEvent e) {//1.获得加数和被加数//2.将这个值加法运算后,放到第三个框//3.清除前两个框int text = Integer.parseInt(calculator.textField.getText());int text1= Integer.parseInt(calculator.textField1.getText());calculator.textField2.setText(""+(text1+text));calculator.textField.setText("");calculator.textField.setText("");}}
还得把如下所示的代码组合一下,传递监听器麻烦
Calculator calculator = null;public MyAL(Calculator calculator) {this.calculator = calculator;}
内部类
- 最大的好处,就是可以畅通无阻的访问外部的属性和方法
package com.shuai.lesson2;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.TextEvent;public class TestCALC {public static void main(String[] args) {new Calculator().loadFrame();}}//计算器类//方法class Calculator extends Frame {//属性TextField textField;TextField textField1;TextField textField2;//方法public void loadFrame() {//3个文本框textField = new TextField(10);//字符数textField1 = new TextField(10);//字符数textField2 = new TextField(20);//字符数//1 个按钮Button button = new Button("=");button.addActionListener(new MyAL());//1个标签Label label = new Label("+");setLayout(new FlowLayout());add(textField);add(label);add(textField1);add(button);add(textField2);pack();setVisible(true);}private class MyAL implements ActionListener {@Overridepublic void actionPerformed(ActionEvent e) {//1.获得加数和被加数//2.将这个值加法运算后,放到第三个框//3.清除前两个框int text = Integer.parseInt(textField.getText());int text1 = Integer.parseInt(textField1.getText());textField2.setText("" + (text1 + text));textField.setText("");textField.setText("");}}
2.7、画笔
package com.shuai.lesson3;import java.awt.*;public class TestPaint {public static void main(String[] args) {new MYpaint().loadFrame1();}}class MYpaint extends Frame{public void loadFrame1(){setBounds(200,200,600,400);setVisible(true);}@Overridepublic void paint(Graphics g) {//super.paint(g);有些类的父类有一些初始化操作,不能随便干掉//画笔,需要颜色,画笔可以画画g.setColor(Color.red);g.drawOval(100,100,100,100);g.fillOval(200,200,100,100);//实心的⚪g.setColor(Color.green);g.fillRect(300,300,40,20);g.drawRect(300,350,40,20);//养成习惯 画笔画完,将他还原到最初的颜色g.setColor(Color.BLACK);}}
2.8、鼠标监听
目的:想要实现鼠标画画!
package com.shuai.lesson3;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(100, 100, 500, 400);//存鼠标的点points = new ArrayList<>();//鼠标监听器,针对这个窗口setVisible(true);this.addMouseListener(new MyML());}@Overridepublic void paint(Graphics g) {//画画,监听鼠标的事件Iterator iterator = points.iterator();while (iterator.hasNext()){Point point = (Point) iterator.next();g.setColor(Color.BLUE);g.fillOval(point.x,point.y,10,10);}}//添加一个点到界面上public void addPaint(Point point){points.add(point);}//适配器模式private class MyML extends MouseAdapter {//鼠标 按下,弹起,按住不放@Overridepublic void mouseClicked(MouseEvent e) {MyFrame myframe = (MyFrame) e.getSource();//这里我们点击的时候,就会在界面产生一个点myframe.addPaint(new Point(e.getX(),e.getY()));//每次点击鼠标都需要重新画一遍myframe.repaint();//刷新}}}
2.9、窗口监听
package com.shuai.lesson3;import java.awt.*;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class TestWindow {public static void main(String[] args) {new WindowF();}}class WindowF extends Frame {public WindowF() {setBackground(Color.BLUE);setBounds(100, 100, 200, 200);setVisible(true);this.addWindowListener(//匿名内部类new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.out.println("windowsClosing");System.exit(0);}@Overridepublic void windowActivated(WindowEvent e) {WindowF source = (WindowF) e.getSource();source.setTitle("已激活");System.out.println("windowActivated");}});}/* @Overridepublic void windowClosing(WindowEvent e) {setVisible(false);// 隐藏窗口System.exit(0);//正常退出 1是非正常退出};*/}
2.10 键盘监听
package com.shuai.lesson3;import java.awt.*;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.sql.SQLOutput;//键public class TestKeyListener {public static void main(String[] args) {new KeyF();}}class KeyF extends Frame{public KeyF(){setBounds(0,0,300,400);setVisible(true);this.addKeyListener(new KeyAdapter() {//键盘按下@Overridepublic void keyPressed(KeyEvent e) {int keyCode = e.getKeyCode();//不需要去记录这个数值,直接使用静态属性VK_xxxSystem.out.println(keyCode);if (keyCode == KeyEvent.VK_UP){System.out.println("你按了上键盘");//根据不同的操作,进行不同的结果}}});}}
3、Swing(做界面)
3.1、窗口、面板JFrame
package com.shuai.lesson4;import javax.swing.*;import java.awt.*;public class JFrameDemo {//init();初始化public void init(){//顶级窗口JFrame jf = new JFrame("这是一个JFrame窗口");jf.setBounds(100,100,400,300);//设置文字Label->JLabeljf.setBackground(Color.BLUE);JLabel jl = new JLabel("JJJJJ");jf.add(jl);//让文本标签居中jl.setHorizontalAlignment(SwingConstants.CENTER);//容器实例化jf.getContentPane().setBackground(Color.red);jf.setVisible(true);//关闭事件jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}public static void main(String[] args) {//建立一个窗口new JFrameDemo().init();}}
3.2、弹窗
package com.shuai.lesson4;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.setBounds(100, 100, 400, 400);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//Jframe 放东西,容器Container contentPane = this.getContentPane();//绝对布局contentPane.setLayout(null);//设置背景contentPane.setBackground(Color.BLUE);//按钮JButton jButton = new JButton("点击弹出一个对话框");jButton.setBounds(30, 30, 200, 50);//点击按钮弹出弹框jButton.addActionListener(new ActionListener() {//监听器@Overridepublic void actionPerformed(ActionEvent e) {//弹窗new MyDialog();}});contentPane.add(jButton);}public static void main(String[] args) {new DialogDemo();}}//弹窗的窗口class MyDialog extends JDialog {public MyDialog() {this.setVisible(true);this.setBounds(100, 100, 500, 500);// this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);//JDialog退出只能是D0_ONTHING,HIDE,DISPOSE这三个中的一种//应该是默认就有关闭事件this.setTitle("这是一个弹窗");Container contentPane = this.getContentPane();contentPane.setLayout(null);contentPane.setBackground(Color.ORANGE);JLabel jjj = new JLabel("学习学习");contentPane.add(jjj);jjj.setBounds(20,20,50,50);}}
3.3、标签
label
new JLabel("xxx");
图标Icon
package com.shuai.lesson4;import javax.swing.*;import java.awt.*;//图标,需要实现类,Frame继承public class IconDemo extends JFrame implements Icon {private int width;private int hight;public IconDemo(){};//无参构造//有参构造public IconDemo(int width,int hight){this.width = width;this.hight = hight;};public void init(){IconDemo iconDemo = new IconDemo(15, 15);//图标可以放在标签,也可以放在按钮上!JLabel jLabel = new JLabel("标签",iconDemo,SwingConstants.CENTER);Container contentPane = getContentPane();contentPane.add(jLabel);this.setVisible(true);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {g.fillOval(x,y,width,hight);}@Overridepublic int getIconWidth() {return this.width;}@Overridepublic int getIconHeight() {return this.hight;}public static void main(String[] args) {new IconDemo().init();}}
图片
package com.shuai.lesson4;import javax.swing.*;import java.awt.*;import java.net.URL;public class ImageIconDemo extends JFrame {public ImageIconDemo(){JLabel jLabel = new JLabel("图片");URL resource = ImageIconDemo.class.getResource("4.png");ImageIcon imageIcon = new ImageIcon(resource);jLabel.setIcon(imageIcon);jLabel.setHorizontalAlignment(SwingConstants.CENTER);Container contentPane = getContentPane();contentPane.add(jLabel);this.setVisible(true);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);setBounds(100,100,800,800);}public static void main(String[] args) {new ImageIconDemo();}}
3.4、面板
JPanel
package com.shuai.lesson5;import javax.swing.*;import java.awt.*;public class JPanelDemo extends JFrame {public JPanelDemo(){Container contentPane = this.getContentPane();contentPane.setLayout(new GridLayout(2,1,10,10));//后边两个是间距JPanel jPanel = new JPanel(new GridLayout(1, 3));JPanel jPane2 = new JPanel(new GridLayout(1, 2));JPanel jPane3 = new JPanel(new GridLayout(1, 1));jPanel.add(new JButton("aaa"));jPanel.add(new JButton("bbb"));jPanel.add(new JButton("ccc"));jPane2.add(new JButton("111"));jPane2.add(new JButton("222"));jPane3.add(new JButton("---"));setBounds(100,100,500,400);setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);contentPane.add(jPanel);contentPane.add(jPane2);contentPane.add(jPane3);setVisible(true);contentPane.setBackground(Color.YELLOW);}public static void main(String[] args) {new JPanelDemo();}}
JScrollPanel
package com.shuai.lesson4;import javax.swing.*;import java.awt.*;public class JScrollPanelDemo extends JFrame {public JScrollPanelDemo(){Container contentPane = this.getContentPane();//文本域JTextArea jTextArea = new JTextArea(20, 50);jTextArea.setText("学习学习");//面板 并添加到contentpanecontentPane.add(new JScrollPane(jTextArea));this.setVisible(true);this.setBounds(100,100,400,300);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);contentPane.setBackground(Color.BLUE);}public static void main(String[] args) {new JScrollPanelDemo();}}
3.5、按钮
图片按钮
package com.shuai.lesson5;import javax.swing.*;import java.awt.*;import java.net.URL;public class JButtonDemo01 extends JFrame {public JButtonDemo01(){Container contentPane = this.getContentPane();//图片变为图标URL resource = JButtonDemo01.class.getResource("4.png");Icon icon = new ImageIcon(resource);JButton jButton = new JButton();jButton.setIcon(icon);//悬浮框jButton.setToolTipText("这是一个图片按钮");contentPane.add(jButton);this.setVisible(true);this.setBounds(100,100,400,300);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}public static void main(String[] args) {new JButtonDemo01();}}
单选按钮
package com.shuai.lesson5;import javax.swing.*;import java.awt.*;import java.net.URL;public class JButtonDemo02 extends JFrame {public JButtonDemo02(){Container contentPane = this.getContentPane();//图片变为图标URL resource = JButtonDemo01.class.getResource("4.png");Icon icon = new ImageIcon(resource);//单选框JRadioButton jrb01 = new JRadioButton("jrb01");JRadioButton jrb02 = new JRadioButton("jrb02");JRadioButton jrb03 = new JRadioButton("jrb03");//由于单选框只能选择一个,分组ButtonGroup buttonGroup = new ButtonGroup();buttonGroup.add(jrb01);buttonGroup.add(jrb02);buttonGroup.add(jrb03);contentPane.add(jrb01,BorderLayout.CENTER);contentPane.add(jrb02,BorderLayout.NORTH);contentPane.add(jrb03,BorderLayout.SOUTH);this.setVisible(true);this.setBounds(100,100,400,300);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}public static void main(String[] args) {new JButtonDemo02();}}
复选按钮
package com.shuai.lesson5;import javax.swing.*;import java.awt.*;import java.net.URL;public class JButtonDemo03 extends JFrame {public JButtonDemo03(){Container contentPane = this.getContentPane();//图片变为图标URL resource = JButtonDemo01.class.getResource("4.png");Icon icon = new ImageIcon(resource);//多选框JCheckBox jcb1 = new JCheckBox("jcb1");JCheckBox jcb2 = new JCheckBox("jcb2");JCheckBox jcb3 = new JCheckBox("jcb3");//流式布局contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));contentPane.add(jcb1);contentPane.add(jcb2);contentPane.add(jcb3);//东西南北中布局/*contentPane.add(jcb1,BorderLayout.NORTH);contentPane.add(jcb2,BorderLayout.CENTER);contentPane.add(jcb3,BorderLayout.SOUTH);*/this.setVisible(true);this.setBounds(100,100,400,300);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}public static void main(String[] args) {new JButtonDemo03();}}
3.6、列表
下拉框
package com.shuai.lesson6;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);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);this.setBounds(100,100,500,400);}public static void main(String[] args) {new TestComboboxDemo01();}}
列表框
package com.shuai.lesson6;import javax.swing.*;import java.awt.*;import java.util.Vector;public class TestComboboxDemo02 extends JFrame {public TestComboboxDemo02(){Container container = this.getContentPane();//生成列表的内容// String[] contents = {"1","2","3"};//列表中需要的内容Vector contents = new Vector();JList jList = new JList(contents);JList jList1 = new JList(contents);contents.add("2222");contents.add("333");container.add(jList);this.setVisible(true);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);this.setBounds(100,100,500,400);}public static void main(String[] args) {new TestComboboxDemo02();}}
应用场景
- 选择地区,或者一些单个选项
- 列表,展示信息,一般是动态扩展
3.7、文本框
文本框
package com.shuai.lesson6;import javax.swing.*;import java.awt.*;public class TestTextDemo01 extends JFrame {public TestTextDemo01(){Container container = this.getContentPane();//不布局只会出现WORLD,且位置不对this.setLayout(new FlowLayout(FlowLayout.RIGHT));JTextField jTextField1 = new JTextField("HELLO");JTextField jTextField2 = new JTextField("WORLD",20);container.add(jTextField1);container.add(jTextField2);this.setVisible(true);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);this.setBounds(100,100,400,300);}public static void main(String[] args) {new TestTextDemo01();}}
密码框
package com.shuai.lesson6;import javax.swing.*;import java.awt.*;public class TestTextDemo02 extends JFrame {public TestTextDemo02(){Container container = this.getContentPane();JPasswordField jPasswordField = new JPasswordField();//---jPasswordField.setEchoChar('-');container.add(jPasswordField);this.setVisible(true);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);this.setBounds(100,100,400,300);}public static void main(String[] args) {new TestTextDemo02();}}
文本域
//文本域JTextArea jTextArea = new JTextArea(20, 50);jTextArea.setText("学习学习");//面板 并添加到contentpanecontentPane.add(new JScrollPane(jTextArea))
4、贪吃蛇
启动
1 package com.dong.sanke; 2 3 import javax.swing.*; 4 5 public class SnakeDemo { 6 public static void main(String[] args) { 7 JFrame frame = new JFrame(); 8 frame.setBounds(10,10,900,720); 9 frame.setResizable(false); 10 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 11 12 13 frame.add(new SnakePanel()); 14 15 16 frame.setVisible(true); 17 } 18 }
主方法
1 package com.dong.sanke; 2 3 import javax.swing.*; 4 import java.awt.*; 5 import java.awt.event.ActionEvent; 6 import java.awt.event.ActionListener; 7 import java.awt.event.KeyEvent; 8 import java.awt.event.KeyListener; 9 import java.util.Random; 10 11 public class SnakePanel extends JPanel implements KeyListener , ActionListener { 12 int length; 13 int[] snakeX = new int[600]; 14 int[] snakeY = new int[500]; 15 String fx ; 16 boolean isStart ; 17 boolean isFail; 18 Timer timer =new Timer(100,this); 19 Random random = new Random(); 20 int foodx; 21 int foody; 22 int socer; 23 public SnakePanel() { 24 init(); 25 this.setFocusable(true);//获得焦点事件 26 this.addKeyListener(this);//获得键盘键盘监听事件 27 timer.start(); 28 } 29 //初始化 30 public void init(){ 31 length = 3; 32 snakeX[0]=100;snakeY[0]=100; 33 snakeX[1]=75;snakeY[1]=100; 34 snakeX[2]=50;snakeY[2]=100; 35 fx = "R"; 36 isStart = false; 37 foodx = 25+25*random.nextInt(34); 38 foody = 75+25*random.nextInt(34); 39 socer = 10; 40 } 41 //画画 42 @Override 43 protected void paintComponent(Graphics g) { 44 super.paintComponents(g); 45 this.setBackground(Color.WHITE); 46 Date.header.paintIcon(this,g,25,11); 47 g.fillRect(25,75,850,600); 48 g.setColor(Color.cyan); 49 g.setFont(new Font("微软雅黑",Font.BOLD,18)); 50 g.drawString("长度"+length,750,35); 51 g.drawString("分数"+socer,750,55); 52 Date.food.paintIcon(this,g,foodx,foody); 53 if(fx.equals("R")){ 54 Date.right.paintIcon(this,g,snakeX[0],snakeY[0]);//头 55 }else if(fx.equals("U")){ 56 Date.up.paintIcon(this,g,snakeX[0],snakeY[0]);//头 57 }else if(fx.equals("D")){ 58 Date.down.paintIcon(this,g,snakeX[0],snakeY[0]);//头 59 }else if (fx.equals("L")){ 60 Date.left.paintIcon(this,g,snakeX[0],snakeY[0]);//头 61 } 62 63 for (int i = 1; i < length; i++) { 64 Date.body.paintIcon(this,g,snakeX[i],snakeY[i]);//身体1 65 } 66 67 if (isStart == false) { 68 g.setColor(Color.cyan); 69 g.setFont(new Font("微软雅黑",Font.BOLD,40)); 70 g.drawString("按下空格开始游戏",300,300); 71 } 72 if (isFail) { 73 g.setColor(Color.RED); 74 g.setFont(new Font("微软雅黑",Font.BOLD,40)); 75 g.drawString("失败了,按下空格重新开始游戏",300,300); 76 } 77 } 78 //键盘事件监听 79 @Override 80 public void keyPressed(KeyEvent e) { 81 int keyCode = e.getKeyCode();//获得键盘按键 82 if(keyCode==KeyEvent.VK_SPACE){ 83 if (isFail){ 84 isFail = false; 85 init(); 86 }else { 87 isStart = !isStart; 88 } 89 repaint(); //重新绘制 90 } 91 if (keyCode==KeyEvent.VK_UP){ 92 fx = "U"; 93 }else if (keyCode==KeyEvent.VK_DOWN){ 94 fx = "D"; 95 }else if (keyCode==KeyEvent.VK_LEFT){ 96 fx = "L"; 97 }else if (keyCode==KeyEvent.VK_RIGHT){ 98 fx = "R"; 99 } 100 } 101 //事件监听(定时器) 102 @Override 103 public void actionPerformed(ActionEvent e) { 104 if(isStart && isFail == false){ 105 if (snakeX[0]==foodx&&snakeY[0]==foody){ 106 length++; 107 socer+=10; 108 foodx = 25+25*random.nextInt(34); 109 foody = 75+25*random.nextInt(34); 110 } 111 //身体增长 112 for (int i = length - 1; i > 0 ; i--) { 113 snakeX[i]=snakeX[i-1]; 114 snakeY[i]=snakeY[i-1]; 115 } 116 if (fx.equals("R")){ 117 snakeX[0]=snakeX[0]+25; 118 if (snakeX[0]>850){ snakeX[0]=25;} 119 }else if (fx.equals("L")){ 120 snakeX[0]=snakeX[0]-25; 121 if (snakeX[0]<25){ snakeX[0]=850;} 122 }else if (fx.equals("U")){ 123 snakeY[0]=snakeY[0]-25; 124 if (snakeY[0]<75){ snakeY[0]=650;} 125 }else if (fx.equals("D")){ 126 snakeY[0]=snakeY[0]+25; 127 if (snakeY[0]>650){ snakeY[0]=75;} 128 } 129 //失败判定 130 for (int i = 1; i < length; i++) { 131 if (snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){ 132 isFail = true; 133 } 134 } 135 136 repaint(); 137 } 138 timer.start();//定时器开启 139 } 140 @Override 141 public void keyTyped(KeyEvent e) { 142 143 } 144 @Override 145 public void keyReleased(KeyEvent e) { 146 147 } 148 }
图片资源
package com.dong.sanke; import javax.swing.*; import java.net.URL; public class Date { public static URL headerURL= Date.class.getResource("statics/header.png"); public static ImageIcon header= new ImageIcon(headerURL); public static URL upURL= Date.class.getResource("statics/up.png"); public static ImageIcon up= new ImageIcon(upURL); public static URL downURL= Date.class.getResource("Statics/down.png"); public static ImageIcon down= new ImageIcon(downURL); public static URL leftURL= Date.class.getResource("statics/left.png"); public static ImageIcon left= new ImageIcon(leftURL); public static URL rightURL= Date.class.getResource("statics/right.png"); public static ImageIcon right= new ImageIcon(rightURL); public static URL bodyURL= Date.class.getResource("statics/body.png"); public static ImageIcon body= new ImageIcon(bodyURL); public static URL foodURL= Date.class.getResource("statics/food.png"); public static ImageIcon food= new ImageIcon(foodURL); }

浙公网安备 33010602011771号