GUI编程
概念
- GUI(Graphics User Interface),图形用户界面,是指采用图形方式显示的计算机操作用户界面,是计算机与其使用者之间的对话接口,是计算机系统的重要组成部分。它能够使应用程序看上去更加友好。
1、学习GUI的一些简介
- GUI的核心技术:Swing 、 AWT
- 因为界面不美观,需要JRE环境。
- GUI可以写出自己心中想要的一些小工具
- 工作时,也可能需要维护到Swing界面,概率不大。
- 了解MVC架构,了解监听事件。
2、AWT
2.1、AWT介绍
- AWT(Abstract Window Toolkit 抽象窗口工具集)没错,它就是提供Java的GUI设计的工具箱.该包提供了一套与本地图形界面进行交互的接口,也就是说AWT中的图形函数与操作系统所提供的图形函数之间有着一一对应的关系(当利用AWT编写图形用户界面时,实际上是在利用本地操作系统所提供的图形库,由于不同操作系统的图形库不同,可能不同平台运行出来的形状与功能就不一样)AWT所提供的图形功能是各种操作系统所提供图形功能的交集,这样才能实现Java语言的平台无关性。
- 包含了很多类和接口
- 元素:窗口,文本框,按钮
- 用于GUI编程图像用户界面
- 通过java.awt包来实现各种组件
2.2、组件和容器
- 组件
- 窗口
- 弹窗
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件
- 鼠标事件
- 键盘事件
- Frame
-
单个窗口,代码实例,演示如下:
package com.gui.lesson1; import java.awt.*; /* GUI的第一个界面 */ public class TestFrame { public static void main(String[] args) { //Frame,JDK,看源码 Frame frame = new Frame("我的第一个Java图像界面窗口"); //需要设置可见性 frame.setVisible(true); //设置窗口大小 frame.setSize(500,500); //设置背景颜色 frame.setBackground(new Color(128, 127, 255)); //弹出的初始位置 frame.setLocation(250,250); //设置大小固定 frame.setResizable(false); } }
如果发现窗口关不掉,则终止程序运行即可。
-
多个窗口,代码实例,演示如下:
package com.gui.lesson1; import java.awt.*; /* 多窗口创建 */ public class TestFrame02 { public static void main(String[] args) { //展示多个窗口 new MyFrame myFrame = new MyFrame(100, 100, 200, 200, Color.red); MyFrame myFrame2 = new MyFrame(200, 100, 200, 200, Color.blue); MyFrame myFrame3 = new MyFrame(100, 200, 200, 200, Color.yellow); } } class MyFrame extends Frame{ static int id = 0;//可能存在多个窗口,我们需要一个计数器 public MyFrame(int x,int y,int w,int h,Color color) throws HeadlessException { super("MyFrame+"+(++id)); setBackground(color); setBounds(x,y,w,h); setVisible(true); } }
-
面板Panel
-
代码实例
package com.gui.lesson1; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /* Panel 可以看成是一个空间,但是不能单独存在 */ public class TestPanel { public static void main(String[] args) { Frame frame = new Frame(); //布局 Panel panel = new Panel(); //设置布局 frame.setLayout(null); //坐标 frame.setBounds(100,300,400,500); frame.setBackground(new Color(20,60,90)); //panel设置坐标,相对于frame panel.setBounds(50,90,400,500); panel.setBackground(new Color(90,20,199)); //frame.add(panel) frame.add(panel); frame.setVisible(true); //监听事件,监听窗口关闭事件 System.exit(0) //适配器模式: frame.addWindowListener(new WindowAdapter() { //窗口点击关闭的时候需要做的事情 @Override public void windowClosing(WindowEvent e) { //结束程序 System.exit(0); super.windowClosing(e); } }); } }
-
-
布局管理器
-
流式布局
package com.gui.lesson1; 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); } }
-
东西南北中
package com.gui.lesson1; import java.awt.*; public class TestBorderLayout { public static void main(String[] args) { Frame frame = new Frame("TestBorderLayout"); Button east = new Button("East"); Button north = new Button("North"); Button west = new Button("West"); Button south = new Button("South"); Button center = new Button("Center"); frame.add(east,BorderLayout.EAST); frame.add(north,BorderLayout.NORTH); frame.add(west,BorderLayout.WEST); frame.add(south,BorderLayout.SOUTH); frame.add(center,BorderLayout.CENTER); frame.setSize(200,200); frame.setVisible(true); } }
-
表格布局
package com.gui.lesson1; import java.awt.*; public class TestGridLayout { public static void main(String[] args) { Frame frame = new Frame("TestGridLayout"); Button bnt1 = new Button("bnt1"); Button bnt2 = new Button("bnt2"); Button bnt3 = new Button("bnt3"); Button bnt4 = new Button("bnt4"); Button bnt5 = new Button("bnt5"); Button bnt6 = new Button("bnt6"); frame.setLayout(new GridLayout(3,2)); frame.add(bnt1); frame.add(bnt2); frame.add(bnt3); frame.add(bnt4); frame.add(bnt5); frame.add(bnt6); frame.pack();//Java函数 frame.setVisible(true); } }
-
练习三种布局案例,代码演示如下:
package com.gui.lesson1; import java.awt.*; public class ExDemo { public static void main(String[] args) { Frame frame = new Frame(); frame.setSize(400,300); frame.setLocation(300,400); frame.setBackground(Color.BLACK); frame.setVisible(true); 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); } }); } }
-
总结:
- Frame是一个顶级窗口
- Panel无法单独显示,必须添加到某个容器中。
- 布局管理器(流式、东南西北、表格)
- 大小、定位,背景颜色,可见性,监听
-
-
事件监听
-
事件监听器是某个类的对象,我们将这个类称为监听器类,监听器必须要由监听和处理XXXEvent事件的能力,他所在的类必须要实现XXXListener接口
-
代码演示如下:
package com.gui.lesson02; 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 button = new Button(); //因为addActionListener需要一个ActionListener,所有我们构造一个ActionListener MyActionListener myActionListener = new MyActionListener(); button.addActionListener(myActionListener); frame.add(button,BorderLayout.CENTER); frame.pack(); windowsClose(frame); frame.setVisible(true); } //关闭窗体事件 private static void windowsClose(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("mmm"); } }
-
代码实例2(多个按钮共享一个事件):
package com.gui.lesson02; 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 TestActionEvent02 { 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); windowsClose(frame); frame.pack(); frame.setVisible(true); } //关闭窗体事件 private static void windowsClose(Frame frame){ frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class MyMonitor implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //e.getActionCommand()获得按钮信息 System.out.println("按钮被点击了:msg"+e.getActionCommand()); } }
-
-
输入框TextFiled监听
package com.gui.lesson02; import java.awt.*; import java.awt.event.*; public class TestText01 { public static void main(String[] args) { //启动! new MyFrame(); } } class MyFrame extends Frame{ public MyFrame(){ TextField textField = new TextField(); add(textField); //监听这个文本框输入的文字 MyActionListener2 myActionListener2 = new MyActionListener2(); //按下enter,就会触发这个输入框的事件 textField.addActionListener(myActionListener2); //设置替换编码 textField.setEchoChar('*'); pack(); setVisible(true); } } class MyActionListener2 implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { TextField filed= (TextField)e.getSource();//获得一些资源,返回了一个对象 System.out.println(filed.getText());//获得输入框的文本 filed.setText("");//null } }
-
简易计算器,组合+内部类
-
oop原则:组合,大于继承
-
代码实例1:
package com.gui.lesson02; 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() { //三个文本框 TextField num1 = new TextField(10);//字符数 TextField num2 = new TextField(10);//字符数 TextField num3 = new TextField(20);//字符数 //一个按钮 Button button = new Button("="); button.addActionListener(new MyCalculatorListener(num1,num2,num3)); //一个标签 Label label = new Label("+"); //布局 setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); } } //监听器类 class MyCalculatorListener implements ActionListener{ //获取三个变量 private TextField num1,num2,num3; public MyCalculatorListener(TextField num1,TextField num2, TextField num3){ this.num1 = num1; this.num2 = num2; this.num3 = num3; } @Override public void actionPerformed(ActionEvent e) { //1.获得加数和被加数 int n1 = Integer.parseInt(num1.getText()); int n2 = Integer.parseInt(num2.getText()); //2.将这个值+运算后,放到第三个框 num3.setText(""+(n1+n2)); //3.清除前两个框 num1.setText(""); num2.setText(""); } }
-
优化oop写法:
package com.gui.lesson02; 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(){ //三个文本框 TextField num1 = new TextField(10);//字符数 TextField num2 = new TextField(10);//字符数 TextField num3 = new TextField(20);//字符数 Button button = new Button("="); Label label = new Label("+"); button.addActionListener(new MyCalculatorListener(this)); setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); } //监听器类 class MyCalculatorListener implements ActionListener{ //获取三个变量 // private TextField num1,num2,num3; //获取计算器这个对象,在一个类中组合另外一个类 Calculator calculator = null; public MyCalculatorListener(Calculator calculator){ this.calculator = calculator; } @Override public void actionPerformed(ActionEvent e) { //1.获得加数和被加数 //2.将这个值+运算后,放到第三个框 //3.清除前两个框 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(""); } }
-
代码示例(内部类):
package com.gui.lesson02; 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() { //三个文本框 TextField num1 = new TextField(10);//字符数 TextField num2 = new TextField(10);//字符数 TextField num3 = new TextField(20);//字符数 Button button = new Button("="); Label label = new Label("+"); button.addActionListener(new MyCalculatorListener()); setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); } //监听器类 //内部类最大的好处,就是可以畅通无阻的访问外部的属性和方法! private class MyCalculatorListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //1.获得加数和被加数 //2.将这个值+运算后,放到第三个框 //3.清除前两个框 int n1 = Integer.parseInt(num1.getText()); int n2 = Integer.parseInt(num2.getText()); num3.setText(""+(n1+n2)); num1.setText(""); num2.setText(""); } } }
-
-
画笔
-
代码实例:
package com.gui.lesson03; import java.awt.*; public class TreePaintDemo01 { public static void main(String[] args) { new MyPaint().loadFrame(); } } class MyPaint extends Frame{ public void loadFrame(){ setBounds(200,200,600,500); setVisible(true); } //画笔 @Override public void paint(Graphics g) { //画笔,需要有颜色,可以画画 g.setColor(Color.red); g.drawOval(200,200,200,200);//空心圆 g.fillOval(200,200,200,200);//实心圆 g.setColor(Color.green); g.fillRect(100,300,400,200); //养成习惯,画笔用完,将他还原到最初的颜色 } }
-
-
鼠标监听
-
目的:想要实现鼠标画画
-
代码实例:
package com.gui.lesson03; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Iterator; //鼠标监听事件 public class TestMouseListener { public static void main(String[] args) { new MyFrame("画图"); } } //自己的类 class MyFrame extends Frame{ //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点 ArrayList points; public MyFrame(String title){ super(title); setBounds(200,200,400,300); //存鼠标点击的点 points = new ArrayList<>(); setVisible(true); //鼠标监听器,正对着窗口 this.addMouseListener(new MyMouseListener()); } @Override public void paint(Graphics g) { //画画,监听鼠标的事件 Iterator iterator = points.iterator(); while (iterator.hasNext()){ Point point = (Point) iterator.next(); g.setColor(Color.blue); g.fillOval(point.x,point.y,10,10); } } //添加一个点到界面上 public void addPaint(Point point){ points.add(point); } //适配器模式 private class MyMouseListener extends MouseAdapter { //鼠标,按下,弹起,按住不放 @Override public void mousePressed(MouseEvent e) { MyFrame frame = (MyFrame) e.getSource(); //这个我们点击的时候,就会在界面上产生一个点。 //这个点就是鼠标的点 frame.addPaint(new Point(e.getX(),e.getY())); //每次点击鼠标都需要重新画一遍 frame.repaint(); } } }
-
-
窗口监听
-
代码实例:
package com.gui.lesson03; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class TestWindows { public static void main(String[] args) { new WindowFrame(); } } class WindowFrame extends Frame{ public WindowFrame() { setBackground(Color.blue); setBounds(200,200,200,200); setVisible(true); //addWindowListener(new MyWindowListener()); this.addWindowListener( new WindowAdapter() { //关闭窗口 @Override public void windowClosing(WindowEvent e) { System.out.println("windowClosing"); System.exit(0); } //激活窗口 @Override public void windowActivated(WindowEvent e) { WindowFrame source =(WindowFrame) e.getSource(); source.setTitle("被激活了"); System.out.println("windowActivated"); } } ); } // class MyWindowListener extends WindowAdapter{ // @Override // public void windowClosing(WindowEvent e) { // setVisible(false);//隐藏窗口 // System.exit(0);//正常退出 // } // } }
-
-
键盘监听
-
代码实例:
package com.gui.lesson03;
-
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(){
setBounds(1,2,300,400);
setVisible(true);
this.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("你按下了上键");
}
//根据按下的不同的操作,产生不同的结果
}
});
}
}
```
3、Swing
-
窗口
窗口代码示例:
package com.gui.lesson04;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo {
//int();初始化
public void init(){
JFrame jf = new JFrame("这是一个JFrame窗口");
jf.setBounds(1,2,100,200);
jf.setVisible(true);
jf.setBackground(Color.cyan);
//设置文字 Jlabel
JLabel label = new JLabel("哈啰");
jf.add(label);
//关闭事件
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//建立一个窗口
new JFrameDemo().init();
}
}
package com.gui.lesson04;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo02 {
public static void main(String[] args) {
new MyJrame02().init();
}
}
class MyJrame02 extends JFrame{
public void init(){
this.setVisible(true);
this.setBounds(10,10,200,400);
JLabel label = new JLabel("你好");
this.add(label);
//让文本标签居中 设置水平对齐
label.setHorizontalAlignment(SwingConstants.CENTER);
//获得一个容器
Container container = this.getContentPane();
container.setBackground(Color.blue);
}
}
-
JDialog弹窗
JDialog,用来被弹出,默认就有关闭窗口事件,代码演示如下:
package com.gui.lesson04;
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//主窗口
public class DialogDemo01 extends JFrame {
public DialogDemo01() {
this.setVisible(true);
this.setSize(600,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame 放东西,容器
Container container = this.getContentPane();
//绝对布局
container.setLayout(null);
//按钮
JButton button = new JButton("点击弹出一个对话框");//创建
button.setBounds(30,30,200,50);
//点击这个按钮的时候,弹出一个弹窗
button.addActionListener(new ActionListener() {//监听器
@Override
public void actionPerformed(ActionEvent e) {
//弹窗
new MyDialogDemo01();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo01();
}
}
//弹窗的窗口
class MyDialogDemo01 extends JDialog{
public MyDialogDemo01() {
this.setVisible(true);
this.setBounds(100,100,500,500);
Container container = this.getContentPane();
container.setLayout(null);
container.add(new Label("哟嚯"));
}
}
3. **标签**
- label 图标ICON
- 代码示例,演示如下:
```java
package com.gui.lesson04;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//主窗口
public class DialogDemo01 extends JFrame {
public DialogDemo01() {
this.setVisible(true);
this.setSize(600,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame 放东西,容器
Container container = this.getContentPane();
//绝对布局
container.setLayout(null);
//按钮
JButton button = new JButton("点击弹出一个对话框");//创建
button.setBounds(30,30,200,50);
//点击这个按钮的时候,弹出一个弹窗
button.addActionListener(new ActionListener() {//监听器
@Override
public void actionPerformed(ActionEvent e) {
//弹窗
new MyDialogDemo01();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo01();
}
}
//弹窗的窗口
class MyDialogDemo01 extends JDialog{
public MyDialogDemo01() {
this.setVisible(true);
this.setBounds(100,100,500,500);
Container container = this.getContentPane();
container.setLayout(null);
container.add(new Label("哟嚯"));
}
}
-
代码示例2,Imageicon
package com.gui.lesson04; import javax.swing.*; import java.awt.*; import java.net.URL; public class ImageIconDemo extends JFrame { public ImageIconDemo() { //获取图片的地址 JLabel label = new JLabel("ImageIcon"); URL url = ImageIconDemo.class.getResource("Default.jpg"); ImageIcon imageIcon = new ImageIcon(url); label.setIcon(imageIcon); label.setHorizontalAlignment(SwingConstants.CENTER); Container container = getContentPane(); container.add(label); setVisible(true); setBounds(100,100,200,300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new ImageIconDemo(); } }
-
面板
-
JPanel
package com.gui.lesson05; import javax.swing.*; import java.awt.*; public class JPanelDemo01 extends JFrame { public JPanelDemo01() { Container container = this.getContentPane(); container.setLayout(new GridLayout(2,1,10,10));//后面的参数间距 JPanel panel1 = new JPanel(new GridLayout(1,3)); JPanel panel2 = new JPanel(new GridLayout(1,2)); JPanel panel3 = new JPanel(new GridLayout(3,2)); panel1.add(new JButton("1")); panel1.add(new JButton("1")); panel1.add(new JButton("1")); panel2.add(new JButton("2")); panel2.add(new JButton("2")); panel3.add(new JButton("3")); panel3.add(new JButton("3")); panel3.add(new JButton("3")); panel3.add(new JButton("3")); panel3.add(new JButton("3")); panel3.add(new JButton("3")); container.add(panel1); container.add(panel2); container.add(panel3); this.setVisible(true); this.setSize(500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JPanelDemo01(); } }
-
JScrollPanel
package com.gui.lesson05; import javax.swing.*; import java.awt.*; public class JScrollDemo01 extends JFrame { public JScrollDemo01(){ Container container = this.getContentPane(); //文本域 JTextArea textArea = new JTextArea(20, 50); textArea.setText("欢迎gui"); //Scroll面板 JScrollPane pane = new JScrollPane(textArea); container.add(pane); this.setVisible(true); this.setBounds(100,100,300,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JScrollDemo01(); } }
-
-
按钮
-
图片按钮
package com.gui.lesson05; import javax.swing.*; import java.awt.*; import java.net.URL; public class JButtonDemo01 extends JFrame { public JButtonDemo01(){ Container container = this.getContentPane(); //将一个图片变为图标 URL resource = JButtonDemo01.class.getResource("Default.jpg"); Icon icon = new ImageIcon(resource); //把这个图标放在按钮上 JButton button = new JButton(); button.setIcon(icon); button.setToolTipText("图片按钮"); //把按钮加到容器 container.add(button); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JButtonDemo01(); } }
-
单选按钮
package com.gui.lesson05; import javax.swing.*; import java.awt.*; import java.net.URL; public class JButtonDemo02 extends JFrame { public JButtonDemo02(){ Container container = this.getContentPane(); //将一个图片变为图标 URL resource = JButtonDemo02.class.getResource("Default.jpg"); Icon icon = new ImageIcon(resource); //单选框 JRadioButton rdioButton01 = new JRadioButton("JRdioButton01"); JRadioButton rdioButton02 = new JRadioButton("JRdioButton02"); JRadioButton rdioButton03 = new JRadioButton("JRdioButton03"); //由于单选框只能选择一个,所以实现分组,一个组中只能选一个 ButtonGroup group = new ButtonGroup(); group.add(rdioButton01); group.add(rdioButton02); group.add(rdioButton03); container.add(rdioButton01,BorderLayout.CENTER); container.add(rdioButton02,BorderLayout.SOUTH); container.add(rdioButton03,BorderLayout.NORTH); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JButtonDemo02(); } }
-
多选按钮
package com.gui.lesson05; import javax.swing.*; import java.awt.*; import java.net.URL; public class JButtonDemo03 extends JFrame { public JButtonDemo03(){ Container container = this.getContentPane(); //将一个图片变为图标 URL resource = JButtonDemo03.class.getResource("Default.jpg"); Icon icon = new ImageIcon(resource); //多选框 JCheckBox checkBox1 = new JCheckBox("checkBox1"); JCheckBox checkBox2 = new JCheckBox("checkBox2"); container.add(checkBox1,BorderLayout.SOUTH); container.add(checkBox2,BorderLayout.NORTH); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JButtonDemo03(); } }
-
-
列表
-
下拉框
package com.gui.lesson06; import javax.swing.*; import java.awt.*; public class TestComboboxDemo01 extends JFrame { public TestComboboxDemo01() { Container container = this.getContentPane(); JComboBox status = new JComboBox(); status.addItem(null); status.addItem("222"); status.addItem("333"); status.addItem("555"); container.add(status); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new TestComboboxDemo01(); } }
-
列表框
package com.gui.lesson06; 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); contents.add("张三"); contents.add("小六"); contents.add("王五"); container.add(jList); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new TestComboboxDemo02(); } }
-
应用场景
- 选择地区,或者一些单个选项
- 列表,展示信息,一般是动态扩容
-
-
文本框
-
文本框
package com.gui.lesson06; import javax.swing.*; import java.awt.*; import java.util.Vector; public class TestTextDemo01 extends JFrame { public TestTextDemo01() { Container container = this.getContentPane(); container.setLayout(null); JTextField textField = new JTextField("hello"); JTextField textField2 = new JTextField("world",20); container.add(textField,BorderLayout.NORTH); container.add(textField2,BorderLayout.SOUTH); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new TestTextDemo01(); } }
-
密码框
package com.gui.lesson06; import javax.swing.*; import java.awt.*; public class TestTextDemo02 extends JFrame { public TestTextDemo02() { Container container = this.getContentPane(); JPasswordField passwordField = new JPasswordField(); passwordField.setEchoChar('*'); container.add(passwordField); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new TestTextDemo02(); } }
-
文本域
package com.gui.lesson06; import javax.swing.*; import java.awt.*; public class TestTextDemo02 extends JFrame { public TestTextDemo02() { Container container = this.getContentPane(); JTextArea textArea = new JTextArea(20,50); textArea.setText("你好"); JScrollPane scrollPane = new JScrollPane(textArea); container.add(scrollPane); this.setVisible(true); this.setBounds(200,200,500,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new TestTextDemo02(); } }
-
4、贪食蛇小游戏案例
-
帧:如果时间片足够小,就是动画,一秒30帧 60帧。连起来是动画,拆开就是静态的图片
-
需要键盘监听,定时器 Timer
-
代码1(StartGame)
package com.gui.snake; import javax.swing.*; //游戏的主启动类 public class StartGame { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setBounds(10,10,900,700); frame.setResizable(false);//窗口大小不变 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //正常游戏界面都应该在面板上 frame.add(new GamePanel()); frame.setVisible(true); } }
-
代码2(Date)
package com.gui.snake; import javax.swing.*; import java.net.URL; //数据中心 public class Data { //相对路径 tx.jpg //绝对路径 / 相当于当前的项目 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 ImageIcon up = new ImageIcon(upURL); public static URL downURL = Data.class.getResource("statics/down.png"); public static ImageIcon down = new ImageIcon(downURL); public static URL leftURL = Data.class.getResource("statics/left.png"); public static ImageIcon left = new ImageIcon(leftURL); public static URL rightURL = Data.class.getResource("statics/right.png"); 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); }
-
代码3(GamePanel)
package com.gui.snake; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Random; //游戏的面板 public class GamePanel extends JPanel implements KeyListener, ActionListener { //定义蛇的数据结构 int length; //蛇的长度 int[] snakeX = new int[600];//蛇的X坐标 25*25 int[] snakeY =new int[500];//蛇的Y坐标 25*25 String fx; //食物的坐标 int foodx; int foody; Random random = new Random(); //积分 int score;//成绩 //游戏当前的状态:开始,停止 boolean isStart = false;//默认是不开始 //判断失败 boolean isFail = false; //定时器 Timer timer = new Timer(800,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] = 50;snakeY[1] = 100;//第一个身体的坐标 snakeX[2] = 30;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);//默认的游戏界面 //把小蛇画上去 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 = 0; i < length; i++) { Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//第一个身体坐标 } //花积分 g.setColor(Color.white); g.setFont(new Font("微软雅黑",Font.BOLD,18)); g.drawString("长度"+length,750,35); g.drawString("分数"+score,750,50); //画食物 Data.food.paintIcon(this,g,foodx,foody); //游戏状态 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); } } @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"; } } @Override public void keyReleased(KeyEvent e) { } //事件监听--需要固定的频率刷新 @Override public void actionPerformed(ActionEvent e) { if(isStart && isFail == false){//如果游戏是开始状态,就让小蛇动起来 //吃食物 if (snakeX[0] == foodx && snakeY[0] == foody){ length++;//长度加一 //分数加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; } } } } snakeX[0] = snakeX[0]+25; //边界判断 if (snakeX[0]>850){ snakeX[0] = 25; } //失败判定,撞到自己就算失败 for (int i = 1; i < length; i++) { if (snakeX[0]==snakeX[i] && snakeY[0]==snakeY[i]){ isFail = true; } } repaint();//重画 } timer.start(); } }