GUI编程
定义
图形用户界面编程
组件
- 窗口
- 弹窗
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件
- 鼠标
- 键盘事件
- 外挂:java
- 破解工具
开发
核心技术:Swing、AWT (本质是两个类,但是界面不美观,需要jre环境,所以不流行)
学习的必要性:开发一些小工具、维护swing界面、了解MVC架构了解监听
AWT
- swing的前身,awt是底层,swing是封装了的
- 抽象的窗口工具,包含了很多类和接口
- 元素:窗口、按钮、文本框
- java.awt
窗口Frame
package com.okami.lesson01;
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(400,400);
//设置背景颜色
frame.setBackground(new Color(178, 37, 37));
//弹出的初始位置
frame.setLocation(100,100);
//设置大小固定
frame.setResizable(false);
}
}
package com.okami.lesson01;
import java.awt.*;
public class TestFrame2 {
public static void main(String[] args) {
//展示多个窗口new
MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.blue);
MyFrame myFrame2 = new MyFrame(300, 300, 200, 200, Color.yellow);
MyFrame myFrame3 = new MyFrame(500, 500, 200, 200, Color.red);
MyFrame myFrame4 = new MyFrame(700, 700, 200, 200, Color.magenta);
}
}
//构造器封装
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);
setBounds(x,y,w,h);
setVisible(true);
}
}
面板Panel
解决了关闭事件
package com.okami.lesson01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
//Panel 可以看成是一个空间,但是不能单独存在
public class TestPanel {
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(new Color(29, 149, 156));
//Panel的设置,要相对与Frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(184, 195, 29));
//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);
}
});
}
}
布局管理器
- 流式布局
package com.okami.lesson01;
import java.awt.*;
public class TestFlowLayout {
public static void main(String[] args) {
Frame frame = new Frame();
//组件-按钮
Button button1 = new Button("这是一个按钮");
Button button2 = new Button("这是一个按钮");
Button button3 = new Button("这是一个按钮");
Button button4 = new Button("这是一个按钮");
//设置为流式布局
//frame.setLayout(new FlowLayout());
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.setSize(200,200);
//把按钮添加上去
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.setVisible(true);
}
}
- 东西南北中
package com.okami.lesson01;
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(500,500);
frame.setVisible(true);
}
}
- 表格布局Grid
package com.okami.lesson01;
import java.awt.*;
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");
frame.setSize(500,500);
frame.setLayout(new GridLayout(2,2));
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
//frame.pack(); //java函数
frame.setVisible(true);
}
}
- 习题
package com.okami.lesson01;
import java.awt.*;
public class Demo01 {
public static void main(String[] args) {
//总窗
Frame frame = new Frame();
frame.setSize(500,500);
frame.setLocation(300,300);
frame.setBackground(Color.green);
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-1"));
p2.add(new Button("p2-2"));
p1.add(p2,BorderLayout.CENTER);
//下面
p3.add(new Button("East-3"),BorderLayout.EAST);
p3.add(new Button("West-3"),BorderLayout.WEST);
for(int i=0;i<4;i++){
p4.add(new Button("p4-"+i));
}
p3.add(p4,BorderLayout.CENTER);
frame.add(p1);
frame.add(p3);
}
}
小结
- Frame是一个顶级窗口
- Panel无法单独显示,必须添加到某个容器中
- 布局管理期:流式布局、边界布局、网格布局
事件监听
package com.okami.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();//自适应
windowClose(frame);
frame.setVisible(true);
}
//关闭窗口事件
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("abc");
}
}
多个按钮共享一个事件
package com.okami.lesson02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestActiveEvent02 {
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());
}
}
输入框
package com.okami.lesson02;
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);
//监听文本框输入的文字
MyActiveListener2 myActiveListener2 = new MyActiveListener2();
//按下enter键就会触发这个输入框的事件
textField.addActionListener(myActiveListener2);
//设置替换编码,输入密码显示为*
textField.setEchoChar('*');
setVisible(true);
pack();
}
}
class MyActiveListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField) e.getSource();//获得一些资源,返回一个对象
System.out.println(field.getText());//获得输入框中的文本
field.setText(""); //回车之后,输入框为空,null是个对象,""是字符串
}
}
用输入框实现计算器
oop原则:优先使用组合,继承大于组合
class A extends B{
//这是继承,A使用B的全部特性
}
class A{
//这是组合,将B的功能组合到A
public B b;
}
package com.okami.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(){
//3个文本框
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(20);
//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);
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("");
}
}
此时的代码是面向过程的
改造成组合,面向对象
package com.okami.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(){
num1 = new TextField(10);
num2 = new TextField(10);
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{
//获取计算器这个对象,在一个类中组合另外一个类
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.okami.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(){
num1 = new TextField(10);
num2 = new TextField(10);
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.okami.lesson03;
import java.awt.*;
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFrame();
}
}
class MyPaint extends Frame{
public void loadFrame(){
setBounds(200,200,600,800);
setVisible(true);
}
//画笔 alt+insert,Override
@Override
public void paint(Graphics g) {
//设定画笔颜色,然后画画
g.setColor(Color.blue);
g.drawLine(100,100,20,40);
g.fillOval(100,200,100,200);//实心园
g.drawOval(200,300,100,50);//空心园
g.setColor(Color.red);
g.fillRect(300,400,100,100);//矩形
//画笔用完,将他还原到最初的颜色
g.setColor(Color.BLACK);
}
}
鼠标监听
实现鼠标画画
package com.okami.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,600,800);
//存鼠标点击的位置
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.red);
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.okami.lesson03;
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(){
setBackground(Color.red);
setBounds(200,200,400,600);
setVisible(true);
//addWindowFocusListener(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.okami.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,1,300,400);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//获取当前键值的码
int keyCode=e.getKeyCode(); //直接使用静态属性VK_XXX
System.out.println(keyCode);
if(keyCode == KeyEvent.VK_UP){
System.out.println("你按了up键");
}
}
});
}
}
Swing
窗口
JFrame
package com.okami.lesson04;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo {
//init(); 初始化
public void init(){
//顶级窗口
JFrame jf = new JFrame("这是一个JFrame窗口");
jf.setVisible(true);
jf.setBounds(100,100,400,300);
jf.setBackground(Color.blue);
//设置文字Jlable
JLabel label = new JLabel("啊哈");
jf.add(label);
//容器实例化
//关闭事件
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//建立一个窗口
new JFrameDemo().init();
}
}
文字居中
package com.okami.lesson04;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo02 {
public static void main(String[] args) {
new MyJframe2().init();
}
}
class MyJframe2 extends JFrame {
public void init(){
this.setBounds(200,200,400,300);
this.setVisible(true);
//设置文字Jlable
JLabel label = new JLabel("啊哈");
//JLabel label = new JLabel("啊哈",SwingConstants.CENTER);
this.add(label);
//文本居中
//label.setHorizontalAlignment(JTextField.CENTER);
label.setHorizontalAlignment(SwingConstants.CENTER);
//获得一个容器
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.magenta);
}
}
弹出
Dialog
package com.okami.lesson04;
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.setSize(400,300);
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 MyDialog();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo();
}
}
//弹窗的窗口
class MyDialog extends JDialog{
public MyDialog(){
this.setVisible(true);
this.setBounds(100,100,400,300);
//this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 重复了
Container container = this.getContentPane();
//container.setLayout(null); //绝对定义布局
container.add(new JLabel("这是一个句子"));
}
}
标签
lable
new JLable("xxx");
Icon
package com.okami.lesson04;
import javax.swing.*;
import java.awt.*;
//图标,需要实现类,Frame继承
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(15, 15);
//图标放在标签,也可以放在按钮上!
JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.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 this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
}
加图片
package com.okami.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("bqb.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,200,200);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}
面板
JPanel
package com.okami.lesson05;
import javax.swing.*;
import java.awt.*;
public class JPanelDemo extends JFrame {
public JPanelDemo() {
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(2, 1));
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"));
container.add(panel1);
container.add(panel2);
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JPanelDemo();
}
}
JScrollPane(带滚动条的面板)
package com.okami.lesson05;
import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
public JScrollDemo() {
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(20, 50);
textArea.setText("阿巴阿巴阿巴");
//Scrall面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setVisible(true);
this.setBounds(100,100,300,300);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
按钮
- 单选按钮
package com.okami.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo02 extends JFrame {
public JButtonDemo02() {
Container container = this.getContentPane();
//单选框
JRadioButton radioButton01 = new JRadioButton("JRadioButton01");
JRadioButton radioButton02 = new JRadioButton("JRadioButton02");
JRadioButton radioButton03 = new JRadioButton("JRadioButton03");
//由于单选框只能选择其中一个,我们将多个按钮放在一个分组,一个分组中只能选择一个
ButtonGroup group = new ButtonGroup();
group.add(radioButton01);
group.add(radioButton02);
group.add(radioButton03);
container.add(radioButton01,BorderLayout.CENTER);
container.add(radioButton02,BorderLayout.NORTH);
container.add(radioButton03,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,300,400);
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
- 复选按钮
package com.okami.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo03 extends JFrame {
public JButtonDemo03() {
Container container = this.getContentPane();
//多选项
JCheckBox checkbox01 = new JCheckBox("checkbox01");
JCheckBox checkbox02 = new JCheckBox("checkbox02");
container.add(checkbox01,BorderLayout.NORTH);
container.add(checkbox02,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,300,400);
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
列表
- 下拉框
package com.okami.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("已下架");
status.addItem("即将上映");
status.addItem("正在热映");
container.add(status);
this.setVisible(true);
this.setBounds(100,100,300,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo01();
}
}
- 列表框
package com.okami.lesson06;
import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo02 extends JFrame{
public TestComboboxDemo02() {
Container container = this.getContentPane();
//生成列表的内容
String[] contents = {"1","2","3"};
//列表中需要放入内容
JList jList = new JList(contents);
container.add(jList);
this.setVisible(true);
this.setBounds(100,100,300,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo02();
}
}
package com.okami.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("a");
contents.add("b");
contents.add("c");
container.add(jList);
this.setVisible(true);
this.setBounds(100,100,300,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo02();
}
}
- 应用场景
- 多级联动
- 列表,动态扩容
文本框
- 文本框
package com.okami.lesson06;
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class TestTextDemo01 extends JFrame{
public TestTextDemo01() {
Container container = this.getContentPane();
JTextField textField1 = new JTextField("hello");
JTextField textField2 = new JTextField("world");
container.add(textField1,BorderLayout.NORTH);
container.add(textField2,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(100,100,300,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo01();
}
}
- 密码框
package com.okami.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(100,100,300,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo02();
}
}
- 文本域
JTexArea
贪吃蛇
帧,24帧,1秒的动画由24张图片连续播放形成
监听
定时器
定义、画、监听
主程序
package com.okami.snake;
import javax.swing.*;
//游戏主启动类
public class StartGame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(10,10,900,720);
frame.setResizable(false); //窗口大小不可变
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//正常的游戏界面都应该在面板上
frame.add(new GamePanel());
frame.setVisible(true);
}
}
数据中心
package com.okami.snake;
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
//相对路径
//绝对路径::在相对路径前加/,相当于当前项目
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);
}
游戏面板
package com.okami.snake;
import javafx.scene.input.KeyCode;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
//游戏的面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
//定义蛇的数据结构
int length;//蛇的长度
int[] snakeX = new int[600];
int[] snakeY = new int[500];
String direction; //蛇头方向
//食物的坐标
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;//第二个身体坐标
direction = "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,35);
g.drawString("分数"+score,750,50);
//画食物
Data.food.paintIcon(this,g,foodx,foody); //先画食物,不然会出现食物长在小蛇头上的情况
//把小蛇画上去
if(direction.equals("R")){
Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); //蛇头初始化向右
}else if(direction.equals("L")){
Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
}else if(direction.equals("U")){
Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
}else if(direction.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("按下空格开始游戏",280,330);
}
if(isFail==true){
g.setColor(Color.RED);
g.setFont(new Font("微软雅黑",Font.BOLD,40)); //设置字体
g.drawString("失败,按下空格重新开始",280,330);
}
}
//键盘监听事件
@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){
direction = "U";
}else if(keyCode==KeyEvent.VK_DOWN){
direction = "D";
}else if(keyCode==KeyEvent.VK_LEFT){
direction = "L";
}else if(keyCode==KeyEvent.VK_RIGHT){
direction = "R";
}
}
//事件监听--通过固定的时间刷新
@Override
public void actionPerformed(ActionEvent e) {
if(isStart && isFail == false){ //如果游戏是开始状态,就让小蛇动起来
//吃食物
if(snakeX[0] == foodx && snakeY[0] == foody){
length++; //长度 + 1
score=score+10; //分数加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(direction.equals("R")){
snakeX[0]=snakeX[0]+25;
if(snakeX[0]>850){snakeX[0]=25;} //边界判断
}else if(direction.equals("L")) {
snakeX[0] = snakeX[0] - 25;
if (snakeX[0] < 25) {snakeX[0] = 850; } //边界判断
}else if(direction.equals("U")) {
snakeY[0] = snakeY[0] - 25;
if (snakeY[0] < 75) {snakeY[0] = 650; } //边界判断
}else if(direction.equals("D")) {
snakeY[0] = snakeY[0] + 25;
if (snakeY[0] > 650) {snakeY[0] = 75; } //边界判断
}
//失败判断,撞到自己就算失败
for(int i=1;i<length;i++){
if (snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
isFail=true;
}
}
repaint(); //重画页面
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}