GUI编程
1、简介
-
GUI的核心技术:Swing AWT
1.因为界面不美观
2.需要jre环境! -
为什么我们要学习?
1.可以写出自己心中想要的一些工具;
2.工作时候,也可能需要维护到swing界面;
3.了解MVC架构,了解监听!
2、AWT
2.1 AWT介绍
1.包含了很多类和接口! GUI!
2.元素:窗口,按钮,文本框
3.java.awt
2.2 组件和容器
1、Frame
public class TestFrame {
public static void main(String[] args) {
//Frame ,JDK, 看源码!
Frame frame = new Frame("我的第一个GUI窗口");
//需要设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(500,400);
//设置背景色
frame.setBackground(new Color(44, 141, 153));
//设置弹出的初始位置
frame.setLocation(200,200);
//设置窗口大小固定
frame.setResizable(false);
}
}
问题:发现窗口关闭不了,停止java程序!
封装一个自己的Frame组件
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.gray);
MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.magenta);
}
}
class MyFrame extends Frame{
static int id = 0; //可能存在多个窗口,需要一个id用来记数
public MyFrame(int x, int y,int w,int h,Color color){
super("MyFrame" + (++id));
setBounds(x,y,w,h);
setBackground(color);
setVisible(true);
}
}
2、面板Panel
// panel 可以看作一个空间,但是不能单独存在
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("测试panel");
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//设置坐标
frame.setBounds(300,300,500,500);
frame.setBackground(Color.green);
//设置panel坐标
panel.setBounds(50,50,400,400);
panel.setBackground(Color.red);
frame.add(panel);
frame.setVisible(true);
//解决窗口无法关闭的问题
//监听事件,监听窗口关闭事件 system.exit(0);
//适配器模式
frame.addWindowListener(new WindowAdapter() {
@Override
//点击窗口关闭按钮要做的事情
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
2.3、布局管理器
- 流式布局
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.RIGHT));
//把按钮添加到frame
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setSize(200,200);
frame.setVisible(true);
}
}
- 东西南北中
public class TestBorderLayout {
public static void main(String[] args) {
Frame frame = new Frame("测试 BorderLayout");
//东西南北中
Button east = new Button("East");
Button west = new Button("West");
Button north = new Button("North");
Button south = new Button("South");
Button center = new Button("Center");
frame.add(east, BorderLayout.EAST);
frame.add(west, BorderLayout.WEST);
frame.add(north, BorderLayout.NORTH);
frame.add(south, BorderLayout.SOUTH);
frame.add(center, BorderLayout.CENTER);
frame.setBounds(200,200,300,300);
frame.setVisible(true);
}
}
- 表格
public class TestGridLayout {
public static void main(String[] args) {
Frame frame = new Frame("TestGridLayout");
//设置表格布局
frame.setLayout(new GridLayout(3,2));
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
Button button4 = new Button("button4");
Button button5 = new Button("button5");
Button button6 = new Button("button6");
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.add(button5);
frame.add(button6);
frame.pack(); //自动布局
frame.setVisible(true);
}
}
练习:实现下面的布局
分析:
代码实现:
public class ExDemo {
public static void main(String[] args) {
//总的窗口
Frame frame = new Frame("布局练习Demo");
frame.setSize(400,300);
frame.setLocation(300,300);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
//4个面板
Panel p1 = new Panel(new BorderLayout());
p1.setBackground(Color.green);
Panel p2 = new Panel(new GridLayout(2, 1));
Panel p3 = new Panel(new BorderLayout());
Panel p4 = new Panel(new GridLayout(2, 2));
//上面
p1.add(new Button("East-1"), BorderLayout.EAST);
p1.add(new Button("West-1"), BorderLayout.WEST);
p2.add(new Button("p2-btn-1"));
p2.add(new Button("p2-btn-2"));
p1.add(p2,BorderLayout.CENTER);
//下面
p3.add(new Button("East-2"), BorderLayout.EAST);
p3.add(new Button("Weat-2"), BorderLayout.WEST);
for (int i = 0; i < 4; i++) {
p4.add(new Button("for-"+i));
}
p3.add(p4,BorderLayout.CENTER);
//添加到窗口
frame.add(p1);
frame.add(p3);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
总结:
-
Frame是一个顶级窗口
-
Panel无法单独显示,必须添加到某个容器中。
-
布局管理器
-
流式 FlowLayout
-
表格 GrideLayout
-
东西南北中 BorderLayout
-
大小、背景、定位、监听
2.4、事件监听
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮触发一些事件
Frame frame = new Frame("TestActionEvent");
Button button = new Button();
//因为addActionListener()需要一个actionListener,所以我们构造一个actionListener
button.addActionListener(new MyActionListener());
frame.add(button, BorderLayout.CENTER);
frame.pack();
closeWindow(frame); //关闭窗口
frame.setVisible(true);
}
//关闭窗口的方法
private static void closeWindow(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("aaa");
}
}
两个按钮实现同一个监听:
public class TestActionTwo {
//两个按钮实现同一个监听
// 开始 停止
public static void main(String[] args) {
Frame frame = new Frame("TestActionTwo");
Button button1 = new Button("start");
Button button2 = new Button("top");
MyMonitor myMonitor = new MyMonitor();
button1.addActionListener(myMonitor);
button2.addActionListener(myMonitor);
button1.setActionCommand("btn-start");
button2.setActionCommand("btn-stop");
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.setVisible(true);
frame.pack();
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了:msg=>"+e.getActionCommand());
}
}
2.5、输入框 TextField 监听
public class TestText01 {
public static void main(String[] args) {
//启动
new MyFrame();
}
}
class MyFrame extends Frame {
public MyFrame(){
TextField textField = new TextField();
add(textField);
//监听这个文本框的输入的文字
MyActionListener2 myActionListener2 = new MyActionListener2();
//按下enter就会触发这个输入框的事件
textField.addActionListener(myActionListener2);
//设置一些替换编码
textField.setEchoChar('*');
pack();
setVisible(true);
}
}
class MyActionListener2 implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
TextField textField = (TextField) e.getSource(); //获得一些资源,返回一个对象
System.out.println(textField.getText()); //获得输入框的内容
textField.setText("");
}
}
2.6 简易计算器,组合+内部类回顾复习
oop原则:组合,大于继承!
class A extend B{ //继承
}
class A{ //组合
public B b;
}
简易计算器:
//简易计算器
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);
setVisible(true);
pack();
}
}
//监听器类
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("");
}
}
在监听器类中组合计算类:
//简易计算器
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);
Label label = new Label("+");
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(this));
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
setVisible(true);
pack();
}
}
//监听器类
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(num1.getText());
int n2 = Integer.parseInt(num2.getText());
num3.setText("" +(n1 + n2));
num1.setText("");
num2.setText("");
}
}
使用内部类:
- 更好的包装
//简易计算器
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);
Label label = new Label("+");
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener());
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
setVisible(true);
pack();
}
//监听器类
//内部类的最大好处就是可以畅通无阻的访问外部类的属性和方法
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("");
}
}
}
2.7、画笔
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFrame();
}
}
class MyPaint extends Frame{
public void loadFrame(){
setBounds(200,200, 600, 500);
setVisible(true);
}
@Override
//画笔
public void paint(Graphics g) {
//画笔需要有颜色,画笔可以画画
g.setColor(Color.red);
//g.drawOval(100,100,100,100);
g.fillOval(100,100,100,100);
g.setColor(Color.green);
g.fillRect(150,200,200,200);
//养成习惯,画笔用完,将它还原到最初的颜色
}
}
2.8、鼠标监听
目标:实现鼠标画画
//监听鼠标事件
public class TestMouseListener {
public static void main(String[] args) {
new MyFrame("画图");
}
}
//自己的类:画板类
class MyFrame extends Frame {
//画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
//保存点的集合
ArrayList points;
public MyFrame(String title){
super(title);
setBounds(200,200,400,300);
setVisible(true);
//存鼠标点击的点
points = new ArrayList<>();
//鼠标监听器,针对这个窗口
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.green);
g.fillOval(point.x, point.y,10,10);
}
}
//添加一个点到集合
public void addPoint(Point point){
points.add(point);
}
//定义自己的鼠标监听类,适配器模式
private class MyMouseListener extends MouseAdapter{
//鼠标 按下 ,弹起,按住不放
@Override
public void mousePressed(MouseEvent e) {
MyFrame myFrame = (MyFrame) e.getSource();
//这个我们点击的时候,就会在界面上产生一个点!
//这个点是鼠标的点,添加到集合
myFrame.addPoint(new Point(e.getX(),e.getY()));
//每次点击鼠标,重画一遍
myFrame.repaint(); //刷新
}
}
}
实现思路:
2.9、窗口监听
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame(){
setBounds(200,200,200,200);
setVisible(true);
addWindowListener(
new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("你点了X");
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("窗口激活了");
}
}
);
}
}
2.10 键盘监听
//键盘事件监听
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
setBounds(1,2,300,200);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
@Override
//键盘按下
public void keyPressed(KeyEvent e) {
//获取键盘按下的是哪一个键
int keyCode = e.getKeyCode(); //不需要记录这个数值,直接使用静态属性 VK_XXX
if(keyCode == KeyEvent.VK_UP) {
System.out.println("你按下了上箭头");
}else{
System.out.println(keyCode);
}
}
});
}
}
3、swing
3.1、窗口、面板
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);
//获取一个容器
Container container = jf.getContentPane();
container.setBackground(Color.yellow);
//给窗口添加一段文字
JLabel label = new JLabel("这是给窗口添加的一段文字");
//文字居中,设置水平对齐
label.setHorizontalAlignment(SwingConstants.CENTER);
jf.add(label);
//窗口关闭事件
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JFrameDemo().init();
}
}
3.2、弹窗
public class DialogDemo extends JFrame {
public DialogDemo() {
this.setVisible(true);
this.setSize(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,40);
//点击这个按钮的时候,弹出一个弹窗
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, 200, 200);
this.setTitle("这是一个弹出之窗口");
//this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(null);
JLabel jLabel = new JLabel("跟着狂神学Java");
jLabel.setBounds(20,20,100,100);
container.add(jLabel);
}
}
3.3、 标签
lable
new JLable();
//图标,需要实现类,Frame继承
public class IconDemo extends JFrame implements Icon {
private int width;
private int height;
public IconDemo(){}; //无参构造器
public void init(){
IconDemo iconDemo = new IconDemo(15,15);
//图标放在标签上,也可以放在按钮上!
JLabel label = new JLabel("icontest", iconDemo, JLabel.CENTER);
Container container = this.getContentPane();
container.add(label);
this.setVisible(true);
}
public IconDemo(int width,int height){
this.width = width;
this.height = height;
}
@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;
}
public static void main(String[] args) {
new IconDemo().init();
}
}
图标ICON
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
JLabel label = new JLabel("ImageIconDemo");
//获取图片的地址
URL url = ImageIconDemo.class.getResource("tx.jpg");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
Container container = this.getContentPane();
container.add(label);
setBounds(200,200,600,500);
setVisible(true);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}
3.4、 面板
JPanel
``java
public class JPanelDemo extends JFrame {
public static void main(String[] args) {
new JPanelDemo();
}
public JPanelDemo(){
this.setVisible(true);
this.setBounds(200,200,600,500);
Container container = this.getContentPane();
this.setLayout(new GridLayout(2,3,10,20));
JPanel panel1 = new JPanel(new GridLayout(1, 2));
JPanel panel2 = new JPanel(new GridLayout(2, 1));
JPanel panel3 = new JPanel(new GridLayout(1, 3));
JPanel panel4 = new JPanel(new GridLayout(2, 2));
panel1.add(new JButton("1"));
panel1.add(new JButton("1"));
panel2.add(new JButton("2"));
panel2.add(new JButton("2"));
panel3.add(new JButton("3"));
panel3.add(new JButton("3"));
panel3.add(new JButton("3"));
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);
}
}
![](https://img2022.cnblogs.com/blog/2519465/202203/2519465-20220308173113944-202815078.png)
JScrollPanel
```java
//带滚动条的面板 JScrollPane
public class JScrollDemo extends JFrame {
public JScrollDemo() {
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(10, 20);
textArea.setText("欢迎学习Java!");
//面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setBounds(200,200,300,200);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
3.5、 按钮
图片按钮
public class JButtonDemo1 extends JFrame {
public JButtonDemo1() {
Container container = this.getContentPane();
//将一个图片变为图标
URL url = JButtonDemo1.class.getResource("tx.gif");
ImageIcon icon = new ImageIcon(url);
//把这个图标放在按钮上
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
//添加按钮到容器
container.add(button);
this.setVisible(true);
this.setSize(500,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo1();
}
}
单选按钮
//单选按钮
public class JButtonDemo2 extends JFrame {
public JButtonDemo2() {
Container container = this.getContentPane();
//单选框
JRadioButton radioButton1 = new JRadioButton("radioButton1");
JRadioButton radioButton2 = new JRadioButton("radioButton2");
JRadioButton radioButton3 = new JRadioButton("radioButton3");
//由于单选框只能选择一个,分组,一个组中只能选择一个
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);
//add
container.add(radioButton1,BorderLayout.NORTH);
container.add(radioButton2,BorderLayout.CENTER);
container.add(radioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setSize(500,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo2();
}
}
复选按钮
//单选按钮
public class JButtonDemo3 extends JFrame {
public JButtonDemo3() {
Container container = this.getContentPane();
//多选按钮
JCheckBox checkBox1 = new JCheckBox("checkBox1");
JCheckBox checkBox2 = new JCheckBox("checkBox2");
//add
container.add(checkBox1,BorderLayout.NORTH);
container.add(checkBox2,BorderLayout.SOUTH);
this.setVisible(true);
this.setSize(500,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo3();
}
}
3.6、列表
- 下拉框
public class TestComBox extends JFrame {
public TestComBox() {
Container container = this.getContentPane();
//下拉列表框
JComboBox stuatus = new JComboBox();
stuatus.addItem(null);
stuatus.addItem("正在热映");
stuatus.addItem("已下线");
stuatus.addItem("即将上映");
container.add(stuatus);
this.setVisible(true);
this.setBounds(200,200,300,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComBox();
}
}
- 列表框
//列表框
public class TestListBox extends JFrame {
public TestListBox() {
Container container = this.getContentPane();
//生成列表内容
//String[] contents = {"one","two","three","four"};
//动态添加列表项
Vector contents = new Vector();
contents.add("张三");
contents.add("李四");
contents.add("王五");
//列表框
JList list = new JList(contents);
container.add(list);
this.setVisible(true);
this.setBounds(200,200,300,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestListBox();
}
}
- 应用场景:
- 下拉列表框:选择地区或一些单个选项
- 列表框:展示信息,一般是动态扩容的!
3.7、文本框
- 文本框
//文本框练习
public class TestTextDemo1 extends JFrame {
public TestTextDemo1() {
Container container = this.getContentPane();
//两个文本框
JTextField textField1 = new JTextField("hello");
JTextField textField2 = new JTextField("world",20);
//add
container.add(textField1,BorderLayout.NORTH);
container.add(textField2,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(200,200,300,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo1();
}
}
- 密码框
//密码框
public class TestTextDemo2 extends JFrame {
public TestTextDemo2() {
Container container = this.getContentPane();
container.setLayout(new FlowLayout());
JLabel label = new JLabel("密码:");
//密码框
JPasswordField passwordField = new JPasswordField(20);
//add
container.add(label);
container.add(passwordField);
this.setVisible(true);
this.setBounds(200,200,300,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo2();
}
}
- 文本域
//文本域
public class TestTextAreaDemo extends JFrame {
public TestTextAreaDemo() {
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea("这是一个文本域!", 10, 20);
//滚动面板
JScrollPane scrollPane = new JScrollPane(textArea);
//add
container.add(scrollPane);
this.setVisible(true);
this.setBounds(200,200,300,200);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextAreaDemo();
}
}
贪吃蛇
帧,如果时间片足够小,就是动画,一秒30帧 60帧。连起来是动画,拆开是静态的图片。
键盘监听、事件监听
定时器Timer
主启动类:
//游戏的主启动类
public class StartGame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new GamePanel());
frame.setBounds(10,10,900,720);
frame.setResizable(false); //窗口大小不可变
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
用来保存数据的类
//数据中心
public class Data {
//相对路径 tx.jpg
//绝对路径 / 相当于当前的项目
//public static URL headerURL = Data.class.getResource("statics/header.png");
public static URL headerURL = Data.class.getResource("statics/header.png");
public static ImageIcon headr = 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);
}
游戏面板类
//游戏的面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
//定义蛇的数据结构
int length; //蛇的长度
int[] snakeX = new int[600]; //蛇的 x 坐标 25*25
int[] snakeY = new int[500]; //蛇的 Y 坐标 25*25
String fx; //方向
//定义食物
int foodX;
int foodY;
Random random = new Random();
//定时器,以ms为单位,1000ms = 1s
Timer timer = new Timer(100, this); //100ms 执行一次
//游戏的状态:开始 停止
boolean isStart = false; //默认为未开始
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; //第二个身体的坐标
fx = "right"; //初始方向向右
//初始化食物
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.headr.paintIcon(this,g,25,11); //头部广告栏画上去
g.fillRect(25,75,850,600); //默认的游戏界面
//画食物
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);
//把小蛇画上去,根据方向判断蛇脑袋
if(fx.equals("right")){
Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
}else if(fx.equals("left")){
Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
}else if(fx.equals("up")){
Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
}else if(fx.equals("down")){
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("按下空格开始游戏!", 300, 300);
}
if(isFail){
g.setColor(Color.RED);
g.setFont(new Font("微软雅黑", Font.BOLD, 40));
g.drawString("游戏失败!按下空格重新开始。", 300, 300);
}
repaint();
}
//键盘监听事件
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode(); //获取键盘按的是哪一个键
if(keyCode == KeyEvent.VK_SPACE){ //如果按的是空格
if(isFail){ //游戏失败时
isFail = false;
init();
}else{
isStart = !isStart; //取反
repaint(); //重绘
}
}
//判断键盘上下左右按键,改变文方向
if(keyCode == KeyEvent.VK_UP){
fx = "up";
}else if(keyCode == KeyEvent.VK_DOWN){
fx = "down";
}else if(keyCode == KeyEvent.VK_LEFT){
fx = "left";
}else if(keyCode == KeyEvent.VK_RIGHT){
fx = "right";
}
}
//事件监听---需要通过固定事件来刷新, 1s = 10次
@Override
public void actionPerformed(ActionEvent e) {
if(isStart && isFail==false){ //如果为开始状态,就让小蛇动起来
//吃食物
if(snakeX[0]==foodX && snakeY[0]==foodY){
//长度 + 1
length ++;
//积分
score = score + 10;
//重新生成食物
foodX = 25 + 25 * random.nextInt(34);
foodY = 75 + 25 * random.nextInt(24);
}
//移动身体部分
for (int i = length - 1 ; i > 0; i--) { //遍历每一个身体部分
snakeX[i] = snakeX[i-1];
snakeY[i] = snakeY[i-1];
}
//边界判断,脑袋到达边界时,重新开始
if(fx.equals("right")){
snakeX[0] = snakeX[0] + 25;
if(snakeX[0] > 850){snakeX[0] = 25;}//向右到边界时
}else if (fx.equals("left")){
snakeX[0] = snakeX[0] -25;
if(snakeX[0] < 25){snakeX[0] = 850;}//向右到边界时
}else if (fx.equals("up")){
snakeY[0] = snakeY[0] -25;
if(snakeY[0] < 75){snakeY[0] = 650;}//向右到边界时
}else if (fx.equals("down")){
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();
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
游戏面板添加组件的流程:
- 定义数据
- 初始化数据
- 画上去
- 监听事件
- 键盘
- 事件