跟着秦疆老师学习时的课堂笔记
一级目录
二级目录
三级目录
1.简介
GUI(图形用户界面graphical user interface)的核心技术:Swing AWT
主要的学习目的:了解MVC架构, 以及监听的概念
2.AWT
2.1AWT介绍:
- 抽象的窗口工具
- 包含了很多的类和接口
- 包含元素:窗口、按钮、文本框
- java.awt
- awt中有两个核心类
1. Component(组件)
butten(按钮)
TextArea(文本域)
Label(标签)
........
2. Container(容器)
2.2 、组件和容器
2.2.1.Frame
import java.awt.*;
//GUI的第一个界面
//TestFrame(测试框架)
public class TestFrame {
public static void main(String[] args) {
//Frame
Frame frame = new Frame("My first java Image interface window");//标题:我的第一个java图像界面窗口
//需要设置可见性
frame.setVisible(true);//Visible:adj看得见的;可见的;明显的;能注意到的n.现实世界;看得见的事物;直观教具
//设置窗口大小
frame.setSize(400,400);//Size:大小 width:宽 height:高;高度;
//设置背景颜色 color bg color(bg color:背景色)
// frame.setBackground(Color.red);//Color.颜色(colour)
frame.setBackground(new Color(71, 22, 222));//更智能的设置颜色方式。。左边色块可以自由调整
//弹出的初始位置
frame.setLocation(960,200);// Location n.地方;地点;位置;(电影的)外景拍摄地;定位
//设置大小固定
frame.setResizable(false);//Resizable(翻译:可调整大小)
}
}
运行结果:弹出以下的窗口:
窗口目前无法直接关闭,暂时先停止程序运行即可关闭
接下来回顾面向对象的知识:
-
思考:
1. 想同时出现多个窗口怎么做? 2. 代码如何高效开发?
-
思路:
1.创建一个子类 MyFrame 使其继承 Frame类 ,从而可以直接调用Frame类的方法
2.子类 MyFrame中设定好要使用的方法
3.在主程序 class TestFrame02 中创建多个 MyFrame类型的对象并设置其参数
4.运行
import java.awt.*;
public class TestFrame02 {
public static void main(String[] args) {
//展现多个窗口
new MyFrame(100,100,200,200, Color.green);
new MyFrame(300,100,200,200, Color.BLACK);
new MyFrame(100,300,200,200, Color.CYAN);
new MyFrame(300,300,200,200, Color.orange);
}
}
class MyFrame extends Frame{
static int id = 0;//可能存在多个窗口,so 我们需要一个计数器
public MyFrame(int x,int y , int w, int h, Color color){
super("My frame+"+(++id));
setBackground(color);
setBounds(x, y, w, h);
setVisible(true);
}
}
运行结果:
2.2.2 Panel面板
- Panel可以看做是一个空间
- Panel不可以单独存在
- 需要放在Frame上
import java.awt.*;
/*
Panel
n.
面板;(门、墙等上面的)嵌板,镶板,方格板块;(车身的)金属板,板金;(衣服上的)镶条,嵌条,饰片;专家咨询组;控制板,仪表盘*/
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame();
//布局的概念
Panel panel = new Panel();
// frame.setVisible(true);
frame.setLayout(null); //设置布局
frame.setBounds(300,300,500,500);//坐标
frame.setBackground(new Color(98, 248, 221));//背景色
//接下来设置panel
// panel.setVisible(true);//panel不是靠这种方法显示
panel.setBounds(50,50,400,400);//panel设置的坐标(相对于frame而言)
panel.setBackground(new Color(200, 255, 163));//面板的背景色彩
//在框架中添加面板 frame.add(panel)
frame.add(panel);
frame.setVisible(true);//这个分严格放置位置吗
}
}
运行结果:
另如何关闭窗口(需要监听器)
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
/*
Panel
n.
面板;(门、墙等上面的)嵌板,镶板,方格板块;(车身的)金属板,板金;(衣服上的)镶条,嵌条,饰片;专家咨询组;控制板,仪表盘*/
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame();
//布局的概念
Panel panel = new Panel();
// frame.setVisible(true);
frame.setLayout(null); //设置布局
frame.setBounds(300,300,500,500);//坐标
frame.setBackground(new Color(98, 248, 221));//背景色
//接下来设置panel
// panel.setVisible(true);//panel不是靠这种方法显示
panel.setBounds(50,50,400,400);//panel设置的坐标(相对于frame而言)
panel.setBackground(new Color(200, 255, 163));//面板的背景色彩
//在框架中添加面板 frame.add(panel)
frame.add(panel);
frame.setVisible(true);//这个分严格放置位置吗
//最后解决窗口该如何正常关闭的问题。。。。。。。(监听事件) System.exit(0)
/* frame.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return super.toString();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
});//WindowListener:窗口事件 Listener:侦听;监听器;监听;监听程序;听者*/
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭时需要做的事情
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
//结束程序
System.exit(0);
}
});
}
}
2.2.3 布局管理器
- 流式布局
import java.awt.*;
//Layout布局;布置;设计;安排 Flow vi.流;流动;涌流;流畅;有的是;被强烈感到 FlowLayout流式布局
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.setLayout(new FlowLayout(FlowLayout.CENTER));
// frame.setLayout(new FlowLayout(FlowLayout.LEADING));
// frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
// frame.setLayout(new FlowLayout(FlowLayout.TRAILING));
frame.setSize(400,400);
//添加按钮
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setVisible(true);
}
}
- 东南西北中
import java.awt.*;
//Border vt.和…毗邻;与…接壤;沿…的边;环绕…;给…镶边 BorderLayout边界布局
public class TestBorderLayout {
public static void main(String[] args) {
Frame frame = new Frame("边界布局(东西南北中)");
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(1000,800);
frame.setVisible(true);
}
}
- 表格布局 Grid
import java.awt.*;
//GridLayout表格布局 Grid n.网格;方格;(金属或木制的)格子,格栅,栅栏;(地图上的)坐标方格;系统网络;赛车起跑线;(利用互联网的)联网,联机
public class TestGridLayout {
public static void main(String[] args) {
Frame frame = new Frame("TestGridlayout 表格布局");
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(2,3));
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.add(button5);
frame.add(button6);
frame.pack();//java函数 (可以自动排版)(可以不用)
frame.setVisible(true);
}
}
2.2.4 综和测试
写出如下界面:
import java.awt.*;
//练习演示
public class ExerciseDemo {
public static void main(String[] args) {
//总框架
Frame frame = new Frame("结合测试");
frame.setLayout(new GridLayout(2,1));//网格布局 frame分割成2行
frame.setBackground(new Color(1,1,1));
frame.setVisible(true);//显示
frame.setSize(900,500);//框架大小
//4个面板Panel
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));
panel1.add(new Button("East-1"),BorderLayout.EAST);
panel1.add(new Button("WEST-1"),BorderLayout.WEST);
panel2.add(new Button("p2-btn-1"));
panel2.add(new Button("p2-btn-2"));
panel1.add(panel2,BorderLayout.CENTER);
panel3.add(new Button("EAST-2"),BorderLayout.EAST);
panel3.add(new Button("WEST-2"),BorderLayout.WEST);
/ panel4.add(new Button("p4-btn-1"));
// panel4.add(new Button("p4-btn-2"));
// panel4.add(new Button("p4-btn-3"));
// panel4.add(new Button("p4-btn-4"));
//panel4可以不用一个个手动加
for (int i = 1 ; i <= 4; i++){
panel4.add(new Button("p4-btn-" + i));
}
panel3.add(panel4,BorderLayout.CENTER);
//框架中添加面板frame.add(panel);
frame.add(panel1);
frame.add(panel3);
//添加监听
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
2.2.5 总结
-
Frame 是一个总窗口
-
Panel无法单独显示,必须添加到某个容器中
-
布局管理器有3种
-
流式
frame.setLayout(new FlowLayout());
-
东西南北中
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.setLayout(new GridLayout(2,3));
-
-
组织架构
- 大小 frame.setSize(number,number);
- 定位 frame.setLocation(960,200);
- 背景色 frame.setBackground(100,100);
- 可见性 frame.setVisible(true);
- 监听
//添加监听 frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } });
2.3、事件监听
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//Event 事件 Action行为行动;行为过程;所做之事;行为;诉讼;起诉;战斗;情节;激动人心的事;作用;(身体部位的)动作,功能;机械装置,活动部件vt.务必做,确保处理(某事)
//Action Event 动作事件
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮以触发一些事件
Frame frame = new Frame();
Button button = new Button();
// button.addActionListener(new AbstractAction() {//new了一个接口,要将实现类写出(匿名内部类)
// @Override
// public void actionPerformed(ActionEvent e) {
//
// }
// });
//因为addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
ActionListener MyActionListener = new MyActionListener() ;
button.addActionListener(MyActionListener);//ActionListener监听器My
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);
/* exit //n. 出口;退出;通道;太平门;离去;(尤指演员)退场;(车辆可以从一道路驶出进入另一道路的)出路
v.
退场;出去;离去;退出(计算机程序);(剧本里的指示)退场
记忆
ex 出 + it 行走 → 走出 → 出口*/
// status 状态 / ˈsteɪtəs/
}
});
}
}
class MyActionListener implements ActionListener{//alt+insert 选 实现方法
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("QAQ");
}
}
按一下小窗体就会输出一个"QAQ"点击关闭可以正常关闭
思考:两个按钮可以共用一个事件吗?
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 TestAction02 {
public static void main(String[] args) {
//两个按钮实现同一个监听 开始-停止
Frame frame = new Frame("start - stop");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//显示定义 并被 触发 后 会返回的命令,如果不显示定义,则会走默认值
//可以多个按钮只写一个监听器
button1.setActionCommand("button1-start");//将其注释后 试一试
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);
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭时需要做的事情
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
//写一个监听事件类 Monitor 班长;监视器;监控器;显示屏
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//
System.out.println("msg:" + e.getActionCommand());//msg 消息;提示信息
// e.getActionCommand();
}
}
2.4、输入框Text Field监听
Text Field(文本框;文本域;文本字段;文本输入框;输入框)
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);
//监听这个文本框的输入
MyActionListener2 myActionListener2 = new MyActionListener2();
textField.addActionListener(myActionListener2);
textField.setEchoChar('*');//设置替换编码、、、用户设密码时用到
setVisible(true);
pack();
}
}
class MyActionListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField)e.getSource();//强转(我没听懂)
System.out.println(field.getText());//获得输入框的文本
field.setText("");//回车后会清空所有内容
// e.getSource();//获得一些资源 get source
/* Source
n.
来源;出处;信息来源;原始资料;起源;根源;原因;源头
vt.
(从…)获得*/
}
}
2.5、 简易的计算器,组合+内部类(复习)
oop(面向对象的程序设计)7大原则之一:组合 (组合 大于 继承)
实现这个“小计算器”
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//Calculation重新计算;计算;轮廓度计算;运算;計算
public class TestCalculation {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
/*//计算器类 Calculator计算器
class Calculator extends Frame{
public Calculator() {
//思路:
// 需要 3个文本框 1个按钮 1个标签(一会出现的加号没任何实际作用只是给用户看)
//文本框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);
setLocation(800,400);
setBackground(new Color(91, 227, 150));
setTitle("许诺溪的小小加法计算器");
addWindowListener(new WindowAdapter() {
//窗口点击关闭时需要做的事情
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
//结束程序
System.exit(0);
}
});
}
}*/
//优化后的计算器类 Calculator计算器
class Calculator extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadFrame(){
num1 = new TextField(10);//字符数
num2 = new TextField(10);//字符数
num3 = new TextField(20);//字符数
//文本框3个
//按钮1个
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(this));
//标签1个
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
//添加组件
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
setLocation(800,400);
setBackground(new Color(91, 227, 150));
setTitle("许诺溪的小小加法计算器");
addWindowListener(new WindowAdapter() {
//窗口点击关闭时需要做的事情
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
//结束程序
System.exit(0);
}
});
}
public Calculator() {
}
}
/*//监听器类
class MyCalculatorListener implements ActionListener{
//监听器需要获取3个变量
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.获得两个要相加的数
// num1.getText();//获得的是String型
int n1 = Integer.parseInt(num1.getText());//获得并转换成int型
int n2 = Integer.parseInt(num2.getText());//获得并转换成int型
//2.将值运算后放入第3个文本框
num3.setText(""+(n1+n2));//老师的独特暴力方法
//3.清除前两个框
num1.setText("");
num2.setText("");
}
}*/
//优化后的监听器类
class MyCalculatorListener implements ActionListener{
//获取计算器这个对象,在一个类中组合另外一个类
Calculator calculator = null;
public MyCalculatorListener(Calculator calculator) {
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(calculator.num1.getText());
int n2 = Integer.parseInt(calculator.num2.getText());
calculator.num3.setText("" + (n1+n2));
calculator.num1.setText("");
calculator.num2.setText("");
//1.获得两个要相加的数
//2.将值运算后放入第3个文本框
//3.清除前两个框
}
}
2.6、画笔
import java.awt.*;
//Paint
// n.
//油漆;油漆涂层;绘画颜料
//v.
//在…上刷油漆;用颜料画;把…描绘成;往施化妆品
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFrame();
}
}
class MyPaint extends Frame {
public void loadFrame(){
setBounds(200,200,800,800);
setVisible(true);
setBackground(Color.BLACK);
}
@Override
public void paint(Graphics g) {
//画笔需要 1.颜色;2. 画笔可以画
g.setColor(Color.red);
g.drawOval(100,100,100,100);
g.fillOval(300,300,100,100);
g.setColor(Color.GREEN);
g.fillRect(150,150,200,200);
//养成习惯,画笔用完,将其还原最初的颜色
}
}
2.7、鼠标监听
目的:想要实现鼠标画画
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,400);
//存鼠标点击的点
points = new ArrayList<>();
//鼠标监听器
this.addMouseListener(new MyMouseListener());
setVisible(true);
}
@Override
public void paint(Graphics g) {
//画画,监听鼠标的事件
Iterator iterator = points.iterator();
while (iterator.hasNext()){
Point point = (Point) iterator.next();
g.setColor(Color.orange);
g.fillOval(point.x,point.y,10,10);
}
}
//添加一个点到界面上
public void addPaint(Point point){
points.add(point);
}
private class MyMouseListener extends MouseAdapter {//Adapter适配器;适配器模式; MouseAdapter鼠标适配器
//鼠标的3个基本动作:按下,弹起,按住不放
@Override
public void mouseClicked(MouseEvent e) {
MyFrame frame = (MyFrame) e.getSource();//作用:拿到窗口 (点击时会在界面上产生一个点)
//这个点就是鼠标的点
frame.addPaint(new Point(e.getX(),e.getY()));
//每次点击鼠标都需要重画一遍
frame.repaint();//刷新
}
}
}
2.8、窗口监听
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] ags){
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame(){
setBackground(Color.BLACK);
setBounds(100,100,200,200);
setVisible(true);
// addWindowListener(new MyWindowListener());
this.addWindowListener(new WindowAdapter() {
//老师建议这样写 匿名内部类
@Override
public void windowClosing(WindowEvent e) {
System.out.println("You clicked close");
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("windowClosed");
}
@Override
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened");
}
/* @Override
public void windowIconified(WindowEvent e) {
super.windowIconified(e);
}
@Override
public void windowDeiconified(WindowEvent e) {
super.windowDeiconified(e);
}*/
@Override
public void windowActivated(WindowEvent e) {
System.out.println("windowActivated");
}
/* @Override
public void windowDeactivated(WindowEvent e) {
super.windowDeactivated(e);
}
@Override
public void windowStateChanged(WindowEvent e) {
super.windowStateChanged(e);
}
@Override
public void windowGainedFocus(WindowEvent e) {
super.windowGainedFocus(e);
}
@Override
public void windowLostFocus(WindowEvent e) {
super.windowLostFocus(e);
}*/
});
}
//创建的内部类
class MyWindowListener extends WindowAdapter{
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);//隐藏窗口,通过按钮,隐藏当前窗口
System.exit(0);//正常退出
}
}
}
2.9、键盘监听
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,400,500);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
//键盘按下
@Override//Pressed 按下;
public void keyPressed(KeyEvent e) {
//获得键盘按下的键是哪一个,当前的码
int keyCode = e.getKeyCode();//不需要记录这个数值,直接使用其静态属性 VK_XXX
System.out.println(keyCode);
if (keyCode == KeyEvent.VK_UP) {
System.out.println("Press the up key");
}
//根据按下的不同键,产生不同结果:
}
});
}
}
3.Swing
3.1、窗口、面板
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(100,100,400,400);
this.setVisible(true);
JLabel label = new JLabel("喵喵QAQ");
this.add(label);
//让我们的文本居中
label.setHorizontalAlignment(SwingConstants.CENTER);
//获得一个容器
Container contentPane = this.getContentPane();
contentPane.setBackground(new Color(78, 215, 182));
}
}
3.2、弹窗
//Dialog 英 / ˈdaɪəlɒɡ美 / ˈdaɪəlɔːɡ 对话框;对话
//Dialog弹窗
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(400,400,600,600);
// 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);
// this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(null);
container.add(new Label("喵喵喵喵喵喵"));
}
}
点一下就会弹出一个小窗口
3.3、标签
图标ICON
import javax.swing.*;
import java.awt.*;
// Icon图标
//图标需要实现类 要继承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("小东东", iconDemo, SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setBounds(100,100,100,100);
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;
}
}
图片
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("金克斯.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,600,600);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}
3.4、面板
import com.nuoxi.lesson04.JFrameDemo;
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(1,2));
JPanel panel3 = new JPanel(new GridLayout(2,1));
JPanel panel4 = new JPanel(new GridLayout(3,3));
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"));
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.setSize(600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JPanelDemo();
}
}
JSrollPanel
import javax.swing.*;
import java.awt.*;
import static java.awt.SystemColor.text;
public class JScrollDemo extends JFrame {
public JScrollDemo() {
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(20, 50);
textArea.setText("QAQ阿嚏喵喵喵喵");
//Scroll面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setVisible(true);
this.setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
3.5、按钮
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("tx.jpg");
ImageIcon icon = new ImageIcon(resource);
//把图标放在按钮上、
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
//add
container.add(button);
this.setVisible(true);
this.setBounds(100,100,100,100);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo01();
}
}
- 单选按钮
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo02 extends JFrame {
public JButtonDemo02() {
Container container = this.getContentPane();
//将一个图片变为图标
URL resource = JButtonDemo01.class.getResource("tx.jpg");
ImageIcon icon = new ImageIcon(resource);
//单选框
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.setBounds(100,100,600,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo02 extends JFrame {
public JButtonDemo02() {
Container container = this.getContentPane();
//将一个图片变为图标
URL resource = JButtonDemo01.class.getResource("tx.jpg");
ImageIcon icon = new ImageIcon(resource);
//单选框
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.setBounds(100,100,600,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
两者区别(是否分组)
// ButtonGroup group = new ButtonGroup();
// group.add(radioButton01);
// group.add(radioButton02);
// group.add(radioButton03);
- 复选按钮
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo03 extends JFrame {
public JButtonDemo03() {
Container container = this.getContentPane();
//将一个图片变为图标
URL resource = JButtonDemo01.class.getResource("tx.jpg");
ImageIcon icon = new ImageIcon(resource);
//多选框
JCheckBox checkBox01 = new JCheckBox("checkBox01");
JCheckBox checkBox02 = new JCheckBox("checkBox02");
container.add(checkBox01,BorderLayout.NORTH);
container.add(checkBox02,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(100,100,600,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
3.6、列表
- 下拉框
import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo01 extends JFrame {
public TestComboboxDemo01() throws HeadlessException{
Container container = this.getContentPane();
JComboBox status = new JComboBox();//Status 状态 英 / ˈsteɪtəs美 / ˈsteɪtəs
status.addItem(null);
status.addItem("正在上映");
status.addItem("已下架");
status.addItem("即将上映");
container.add(status);
this.setVisible(true);
this.setBounds(300,300,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo01();
}
}
- 列表框
import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo02 extends JFrame {
public TestComboboxDemo02() throws HeadlessException {
Container container = this.getContentPane();
//生成列表的内容 稀疏数组 压缩数据
String[] contents = {"1","2","3"};
//列表中需要放入内容
JList jList = new JList(contents);
container.add(jList);
this.setVisible(true);
this.setBounds(300,300,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo02();
}
}
3.7、文本框
- 文本框
import javax.swing.*;
import java.awt.*;
public class TestTextDemo01 extends JFrame {
public TestTextDemo01() throws HeadlessException {
Container container = this.getContentPane();
JTextField textField = new JTextField("全世界");
JTextField textField1 = new JTextField("无产者",20);
container.add(textField,BorderLayout.NORTH);
container.add(textField1,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(300,300,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new com.nuoxi.lesson06.TestTextDemo01();
}
}
- 密码框
import javax.swing.*;
import java.awt.*;
public class TestTextDemo02 extends JFrame {
public TestTextDemo02() throws HeadlessException {
Container container = this.getContentPane();
//尽量使用面板做此仅为简单演示
JPasswordField passwordField = new JPasswordField();
passwordField.setEchoChar('喵');
container.add(passwordField);
this.setVisible(true);
this.setBounds(300,300,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo02();
}
}
- 文本域
前面有这个代码
4.贪吃蛇
-
键盘监听
-
定时器Timer
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);
}
}
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 direction = "R";//蛇的方向 : R:右 L:左 U:上 D:下
boolean isStart = false;//游戏是否开始,默认是不开始;
//定时器 以毫秒为单位 1000 ms = 1s
Timer timer = new Timer(100, this);//100毫秒执行一次
//食物的坐标
int foodX;
int foodY;
Random random = new Random();//random随机的,随意的
boolean isFail = false; //游戏是否结束
int score; //游戏分数!
//游戏当前的状态:开始,停止
//构造器构造方法
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";//初始方向向右 direction方向
//把食物随机分布在在界面上!
foodX = 25 + 25* random.nextInt(34);
foodY = 75 + 25* random.nextInt(24);
score = 0;//初始化游戏分数
}
//绘制面板,我们游戏中的所有东西,都用此画笔来画
protected void paintComponent(Graphics g) {
super.paintComponent(g);//清屏
//绘制静态的面板
this.setBackground(new Color(75, 7, 7));
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);
//把小蛇画上去
switch (direction) {
case "R" -> Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头初始化向右,需要通过方向来判断
case "L" -> Data.Left.paintIcon(this, g, snakeX[0], snakeY[0]);//需要通过方向来判断
case "U" -> Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);//需要通过方向来判断
case "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]);//第一个身体的坐标
// Data.body.paintIcon(this, g, snakeX[2], snakeY[2]);//第二个身体的坐标
}
Data.food.paintIcon(this,g,foodX,foodY);//画食物
g.setColor(Color.white);
g.setFont(new Font("微软雅黑",Font.BOLD,18));
g.drawString("长度 " + length,750,35);
g.drawString("分数 " + score,750,50);
// Data.body.paintIcon(this,g,snakeX[2],snakeY[2]);//第二个身体的坐标
//游戏状态
if (!isStart) {
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("失败,空格重新开始", 200, 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) {
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 keyReleased(KeyEvent e) {
}
//事件监听器----需要固定事件来刷新,1秒10次
@Override
public void actionPerformed(ActionEvent e) {
if (isStart && !isFail) {//如果游戏是开始状态,就让小蛇动起来
//移动
for (int i = length - 1; i > 0; i--) {//后一节移动到前一节的位置snakeX[i] = snakeX[i-1];
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
//走向
switch (direction) {
case "R" -> {
snakeX[0] = snakeX[0] + 25;
if (snakeX[0] > 850) snakeX[0] = 25;
}
case "L" -> {
snakeX[0] = snakeX[0] - 25;
if (snakeX[0] < 25) snakeX[0] = 850;
}
case "U" -> {
snakeY[0] = snakeY[0] - 25;
if (snakeY[0] < 75) snakeY[0] = 650;
}
case "D" -> {
snakeY[0] = snakeY[0] + 25;
if (snakeY[0] > 650) snakeY[0] = 75;
}
}
//吃食物
if (snakeX[0]==foodX && snakeY[0]==foodY ){
length++ ; //长度+1
score = score + 10;
foodX = 25 + 25*random.nextInt(34);
foodY = 75 + 25*random.nextInt(24);
}
//失败判断,撞到自己就算
for (int i = 1; i < length; i++) {
if (snakeX[i] == snakeX[0] && snakeY[i] == snakeY[0]) {
isFail = true;
break;
}
}
repaint();//重画页面
}
timer.start();//定时器开启
}
}
//Data 数据;资料;材料;(储存在计算机中的)数据资料
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);
}
肝完了----感谢秦疆老师