GUI编程
组件:
- 窗口
- 弹窗
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件
- 鼠标
- 键盘事件
- 破解工具
1. 简介
GUI的核心技术:Swing AWT,因为界面不美观。
1.需要GRE环境
2.需要界面不美观
为什么要学习?
1.可以写出自己心中想要的一些小工具
2.工作时候,也可能需要维护到Swing界面,但是概率极小
3、了解MVC框架,了解监听!
2. AWT
2.1 Awt介绍
-
包含了很多的类和接口! GUI:图形用户界面变成
-
元素:窗口、按钮、文本框
-
java.awt
2.2 组件和容器
1. Frame
package com.xx.lesson01;
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);
//设置背景颜色 Color
//new Color()
frame.setBackground(new Color(1, 1, 1));
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
问题:发现窗口关闭不掉,停止java程序!
尝试回顾封装:
package com.xx.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, 100, 200, 200, Color.yellow);
MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.red);
MyFrame myFrame4 = new MyFrame(300, 300, 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);
}
}
2. 面板
解决了关闭事件
package com.xx.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(1,1,1));
//panel设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(255, 255, 255));
//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);
}
});
}
}
2.3 布局管理器
-
流式布局FlowLayout
package com.xx.lesson01; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class TestFlowLayout { public static void main(String[] args) { Frame frame = new Frame(); //组件-按钮 Button button1 = new Button("button1"); Button button2 = new Button("button2"); Button button3 = new Button("button3"); Button button4 = new Button("button4"); //设置为流式布局 //frame.setLayout(new FlowLayout()); frame.setLayout(new FlowLayout(FlowLayout.LEFT)); //frame.setLayout(new FlowLayout(FlowLayout.RIGHT)); frame.setBounds(200,200,200,200); //把按钮添加上去 frame.add(button1); frame.add(button2); frame.add(button3); frame.add(button4); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
-
东西南北中BorderLayout
package com.xx.lesson01; 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(500,500); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0 ); } }); } }
-
表格布局 Grid
package com.xx.lesson01; 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(); 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();//java函数,调整窗口的大小,使其适应组件的大小和布局,窗口自动适应大小,使窗口能正好显示里面所有的控件. frame.setSize(500,500); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
课堂练习::
分析过程:
代码实现:
package com.xx.lesson01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ExDemo01 {
public static void main(String[] args) {
//总,Frame
Frame frame = new Frame();
frame.setLayout(new GridLayout(2,1));
frame.setSize(400,300);
frame.setLocation(300,400);
//frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Button 按钮
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("butto10");
//4个面板
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));
frame.add(panel1);
frame.add(panel3);
panel1.add(button1,BorderLayout.WEST);
panel1.add(button4,BorderLayout.EAST);
panel1.add(panel2,BorderLayout.CENTER);
panel2.add(button2);
panel2.add(button3);
panel3.add(button5,BorderLayout.WEST);
panel3.add(button10,BorderLayout.EAST);
panel3.add(panel4,BorderLayout.CENTER);
panel4.add(button6);
panel4.add(button7);
panel4.add(button8);
panel4.add(button9);
}
}
总结:
-
Frame是一个顶级窗口
-
Panel无法单独显示,必须添加到某个容器中
-
布局管理器
- 流式
- 东西南北中
- 表格
-
大小,定位,背景颜色,可见性,监听!
2.4 事件监听
事件监听:当某个事情发生的时候,干......
package com.xx.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("输出aaaa");
//因为addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
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("aaaa");
}
}
多个按钮,共享一个事件
package com.xx.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 TestActionEvent2 {
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.setLayout(new GridLayout(2,1));
frame.add(button1);
frame.add(button2);
frame.setVisible(true);
frame.pack();
windowClose(frame);
}
private static void windowClose(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) {
//ee.getActionCommand() 获取按钮的信息
System.out.println("按钮被点击了:msg==>"+e.getActionCommand());
if (e.getActionCommand().equals("star")){
}
}
}
2.5 输入框TextField监听
package com.xx.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 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('*');
setVisible(true);
pack();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyActionListener2 implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField)e.getSource(); //获得一些资源,返回的一个对象
System.out.println(field.getText()); //获得输入框中的文本
field.setText("");//null ""
}
}
2.6 简易计算器,组合+内部类回顾学习
oop原则:组合,大于继承!
package com.xx.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 TestCalc {
public static void main(String[] args) {
Calculator calculator = 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("=");
MyCalculatorActionListener myCalculatorActionListener = new MyCalculatorActionListener(num1,num2,num3);
button.addActionListener(myCalculatorActionListener);
//一个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//监听器类
class MyCalculatorActionListener implements ActionListener {
private TextField num1,num2,num3;
public MyCalculatorActionListener(TextField num1, TextField num2, TextField num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
@Override
public void actionPerformed(ActionEvent e) {
//1.获取加数和被加数
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
//2.将这个值 + 运算后放到第三个框
num3.setText(""+(n1+n2));
//3.清除前两个框内的数据
num1.setText("");
num2.setText("");
}
}
完全改为面相对象写法:
package com.xx.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 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 MyCalculatorActionListener(this));
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//监听器类
class MyCalculatorActionListener implements ActionListener {
//获取对象,在一个类中组合另外一个类
Calculator calculator = null;
public MyCalculatorActionListener(Calculator calculator) {
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
//1.获取加数和被加数
int n1 = Integer.parseInt(this.calculator.num1.getText());
int n2 = Integer.parseInt(this.calculator.num2.getText());
//2.将这个值 + 运算后放到第三个框
this.calculator.num3.setText(""+(n1+n2));
//3.清除前两个框内的数据
calculator.num1.setText("");
calculator.num2.setText("");
}
}
内部类:
-
更好的包装
package com.xx.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 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 MyCalculatorActionListener()); //布局 setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } //监听器类 //内部类最大的好处,就是可以畅通无阻的访问外部类的属性和方法! private class MyCalculatorActionListener 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(""); } } }
2.7 画笔
package com.xx.lesson03;
import java.awt.*;
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFram();
}
}
class MyPaint extends Frame {
public void loadFram(){
setVisible(true);
setBounds(200,200,600,500);
}
@Override
public void paint(Graphics g) {
//画笔,需要有颜色,画笔可以画画
g.setColor(Color.red);
//g.drawOval(100,100,100,100);
g.fillOval(100,100,100,100);//实心的圆
g.setColor(Color.green);
g.fillRect(150,200,200,200);
//养成习惯,画笔用完,将它还原到最初的颜色
}
}
2.8 鼠标监听
目的:想要实现鼠标画画!
package com.xx.lesson03;
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) {
MyFrame myFrame = new MyFrame("画图");
}
}
//自己的类
class MyFrame extends Frame{
ArrayList points;
public MyFrame(String title) {
super(title);
setBounds(200,200,400,300);
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.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 mouseClicked(MouseEvent e) {
MyFrame frame = (MyFrame) e.getSource();
//这个我们点击的时候,就会在界面上产生一个点!
//这个点就是鼠标的点
frame.addPaint(new Point(e.getX(),e.getY()));
//每次点击鼠标都需要重新画一遍
frame.repaint();//刷新
}
}
}
2.9 窗口监听
package com.xx.lesson03;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindowListener {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame(){
setBackground(Color.green);
setVisible(true);
setBounds(100,100,200,200);
addWindowListener(
//匿名内部类
new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened");
}
//关闭窗口
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing");
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("windowClosed");
}
//激活窗口
@Override
public void windowActivated(WindowEvent e) {
WindowFrame title = (WindowFrame) e.getSource();
title.setTitle("被激活了");
System.out.println("windowActivated");
}
});
}
// class MyWindowListener extends WindowAdapter {
// @Override
// public void windowClosing(WindowEvent e) {
// setVisible(false); //隐藏窗口:通过按钮,隐藏当前窗口
// System.exit(0);// exit(0)正常退出
// }
// }
}
2.10 键盘监听
package com.xx.lesson03;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
//键盘监听
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
setVisible(true);
setBounds(100,100,400,300);
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("你按下了上键");
}
//根据按下的不同操作,产生不同的结果
}
});
}
}
3. Swing
3.1 窗口、面板
package com.xx.lesson04;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo01 {
//init()初始化
public void init(){
//顶级窗口
JFrame jf = new JFrame("这是一个JFrame窗口");
jf.setVisible(true);
jf.setBounds(100,100,400,300);
jf.setBackground(Color.green);
//设置文字 Jlabel
JLabel label = new JLabel("这是一串文字");
jf.add(label);
//关闭事件
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JFrameDemo01().init();
}
}
标签居中:
package com.xx.lesson04;
import javax.swing.*;
import java.awt.*;
public class JFrameDomo02 {
public static void main(String[] args) {
new MyJFrame2().init();
}
}
class MyJFrame2 extends JFrame{
public void init(){
this.setVisible(true);
this.setBounds(100,100,400,300);
JLabel label = new JLabel("这是一串字符");
add(label);
//让文本标签居中,设置水平对齐
label.setHorizontalAlignment(SwingConstants.CENTER);
//获得一个容器
Container container = this.getContentPane();
container.setBackground(Color.YELLOW);
}
}
3.2 弹窗
JDialog,用来被弹出,默认就有关闭事件!
package com.xx.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.setBounds(100,100,700,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 MyDialogDemo();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo();
}
}
//弹窗的窗口
class MyDialogDemo extends JDialog{
public MyDialogDemo() {
this.setVisible(true);
this.setBounds(100,100,500,500);
Container container = this.getContentPane();
container.setLayout(null);
JLabel label = new JLabel("aaa");
//label.setVisible(true);
label.setBounds(100,100,100,100);//label设置了大小之后才会显示
container.add(label);
}
}
3.3 标签
label
new JLabel("xxx")
图标 ICON
package com.xx.lesson04;
import javax.swing.*;
import java.awt.*;
//图标,需要实现类,Frame继承
public class IconDemo extends JFrame implements Icon {
private int height;
private int weight;
public IconDemo(){
}
public IconDemo(int height, int weight){
this.height=height;
this.weight=weight;
}
public void init(){
IconDemo iconDemo = new IconDemo(15,15);
//图标放在标签,也可以放在按钮上
JLabel label = new JLabel("IconDemo",iconDemo,SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,400);
}
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,weight,height);
}
@Override
public int getIconWidth() {
return this.weight;
}
@Override
public int getIconHeight() {
return this.height;
}
}
图片ICON
package com.xx.lesson04;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
//获取图片地址
JLabel label = new JLabel();
URL url = ImageIconDemo.class.getResource("报名照片2.jpg");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
setVisible(true);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}
3.4 面板
JPanel
package com.xx.lesson05;
import javax.swing.*;
import java.awt.*;
public class TestJPanel extends JFrame {
public TestJPanel(){
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(2,1));
JPanel panel4 = 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"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
container.add(panel1);
container.add(panel2);
container.add(panel3);
container.add(panel4);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
new TestJPanel();
}
}
JScrollPanel
package com.xx.lesson05;
import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
public JScrollDemo() {
Container container = getContentPane();
//文本域
JTextArea textArea = new JTextArea(20,50);
textArea.setText("欢迎到来狂神说java");
//Scroll面板
JScrollPane jScrollPane = new JScrollPane(textArea);
container.add(jScrollPane);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,300,350);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
3.5 按钮
图片按钮
package com.xx.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo01 extends JFrame {
public JButtonDemo01(){
Container container = this.getContentPane();
//将一个图片变成图标
URL url = JButtonDemo01.class.getResource("报名照片2.jpg");
Icon icon = new ImageIcon(url);
//把图片放到按钮上
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
//add
container.add(button);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(500,300);
}
public static void main(String[] args) {
new JButtonDemo01();
}
}
-
单选按钮 JRadioButto、ButtonGroup
package com.xx.lesson05; import javax.swing.*; import java.awt.*; import java.net.URL; public class JButtonDemo01 extends JFrame { public JButtonDemo01(){ Container container = this.getContentPane(); //将一个图片变成图标 URL url = JButtonDemo01.class.getResource("报名照片2.jpg"); Icon icon = new ImageIcon(url); //单选框 JRadioButton radioButton1 = new JRadioButton("radioButton1"); JRadioButton radioButton2 = new JRadioButton("radioButton2"); JRadioButton radioButton3 = new JRadioButton("radioButton3"); //由于单选框只能选择一个,分组,一个组中只能选择一个 ButtonGroup group = new ButtonGroup(); group.add(radioButton1); group.add(radioButton2); group.add(radioButton3); container.add(radioButton1,BorderLayout.NORTH); container.add(radioButton2,BorderLayout.CENTER); container.add(radioButton3,BorderLayout.SOUTH); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(500,300); } public static void main(String[] args) { new JButtonDemo01(); } }
-
复选按钮 JCheckBox
package com.xx.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo03 extends JFrame {
public JButtonDemo03(){
Container container = this.getContentPane();
//将一个图片变成图标
URL url = JButtonDemo01.class.getResource("报名照片2.jpg");
Icon icon = new ImageIcon(url);
//多选框
JCheckBox checkBox1 = new JCheckBox("JCheckBox1");
JCheckBox checkBox2 = new JCheckBox("JCheckBox2");
container.add(checkBox1,BorderLayout.NORTH);
container.add(checkBox2,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(500,300);
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
3.6 列表
-
下拉框
package com.xx.lesson06; import javafx.scene.control.ComboBox; import javax.swing.*; import java.awt.*; public class TestComboboxDemo01 extends JFrame { public TestComboboxDemo01(){ Container container = getContentPane(); JComboBox status = new JComboBox(); status.addItem(null); status.addItem("正在热映"); status.addItem("即将上映"); status.addItem("已下架"); container.add(status); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(500,350); } public static void main(String[] args) { new TestComboboxDemo01(); } }
-
列表框
package com.xx.lesson06; import javax.swing.*; import java.awt.*; import java.util.Vector; public class TestComboboxDemo02 extends JFrame { public TestComboboxDemo02(){ Container container = getContentPane(); //生成列表的内容 //1.静态数据 //String[] contents = {"1","2","3"}; //2.动态数据 Vector contents = new Vector(); //列表中需要放入内容 JList list = new JList(contents); contents.add("张三"); contents.add("李四"); contents.add("王五"); container.add(list); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(500,350); } public static void main(String[] args) { new TestComboboxDemo02(); } }
-
应用场景
- 选择地区,或者一些单个选项,
- 列表,展示信息,一般是动态扩容!
3.7 文本框
-
文本框 new JTextField
package com.xx.lesson06; import javax.swing.*; import java.awt.*; public class TestTextDemo01 extends JFrame { public TestTextDemo01(){ Container container = this.getContentPane(); JTextField textField1 = new JTextField("hello"); JTextField textField2 = new JTextField("world",20); container.add(textField1,BorderLayout.NORTH); container.add(textField2,BorderLayout.SOUTH); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(500,350); } public static void main(String[] args) { new TestTextDemo01(); } }
-
密码框 new JPasswordField()
package com.xx.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.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(500,350); } public static void main(String[] args) { new TestTextDemo02(); } }
-
文本域 new JTextArea(20,50)
package com.xx.lesson06; import javax.swing.*; import java.awt.*; public class TestTextDemo03 extends JFrame { public TestTextDemo03(){ Container container = this.getContentPane(); //文本域,可以回车换行 JTextArea textArea = new JTextArea(20,50); textArea.setText("欢迎学习JAVA"); //Scroll面板 JScrollPane scrollPane = new JScrollPane(textArea); container.add(scrollPane); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(500,350); } public static void main(String[] args) { new TestTextDemo03(); } }
贪吃蛇
帧,如果时间片足够小,就是动画,一秒30帧, 60帧。 连起来是动画,拆开就是静态的图片!
键盘监听
定时器 Timer
-
启动类 StartGame
package com.xx.snake; import javax.swing.*; //游戏的主启动类 public class StartGame { public static void main(String[] args) { JFrame frame = new JFrame(); //正常的游戏界面都应该放在面板上 frame.add(new GamePanel()); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); frame.setBounds(50,50,900,720); frame.setResizable(false);//窗口大小不可变 } }
-
面板类 GamePanel
package com.xx.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 { //定义蛇的数据结构 private int length;//蛇的长度 private int[] snakeX = new int[600];//蛇的X坐标 25*25 private int[] snakeY = new int[500];//蛇的Y坐标 25*25 String fx = "R";//初始方向向右 //食物的坐标 private int foodX; private int foodY; Random random = new Random(); int score;//积分 //游戏当前的状态: 开始 停止 boolean isStart = false;//默认是停止 boolean isFail = false;//游戏失败状态 //定时器,单位是毫秒 1000=1s 1秒10次 Timer timer = new Timer(100,this); //构造器 public GamePanel() { init(); //获得焦点和键盘事件 this.setFocusable(true); //获得焦点事件 this.addKeyListener(this);//获得键盘监听事件 timer.start();//游戏一开始定时器就启动 } //初始化方法 public void init(){ this.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 public void paint(Graphics g) { super.paint(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,55); //画食物 Data.food.paintIcon(this,g,foodX,foodY); //把小蛇画上去 //绘制蛇头,蛇头初始方向向右,需要通过方向来判断 switch (fx){ case "R": Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); break; case "L": Data.left.paintIcon(this,g,snakeX[0],snakeY[0]); break; case "U": Data.up.paintIcon(this,g,snakeX[0],snakeY[0]); break; case "D": Data.down.paintIcon(this,g,snakeX[0],snakeY[0]); break; } //绘制蛇身体 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==true){ g.setColor(Color.red); g.setFont(new Font("微软雅黑",Font.BOLD,40)); g.drawString("失败,按下空格重新开始",300,300); } } //键盘监听事件 @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode();//获得键盘按压的是哪一个 if (keyCode==KeyEvent.VK_SPACE){//如果按下的是空格键 //判断游戏是否结束 if (isFail){ //重新开始 isFail =false; init(); } 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 keyTyped(KeyEvent e) { } //事件监听---需要通过固定时间来刷新,1s 10次 @Override public void actionPerformed(ActionEvent e) { if (isStart &&isFail==false){//如果游戏是开始状态,就让小蛇动起来! //吃食物 if (snakeX[0]==foodX &&snakeY[0]==foodY){ //长度+1 length++; score+=10;//每吃一个食物,分数+1 //再次随机食物 foodX = 25 + 25*random.nextInt(34); foodY = 75 + 25*random.nextInt(24); } //移动 for (int i = length-1; i >0 ; i--) {//后一节移到前一节的位置 snakeX[1]=snakeX[0] 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();//定时器开启 } }
-
数据类 Data
package com.xx.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 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); }