一、AWT
1. 组件和容器
1.1 frame窗口
基本设置
package com.javase.GUI;
import java.awt.*;
public class TestFrame {
public static void main(String[] args) {
Frame frame = new Frame("我的第一个Java图形界面窗口");
//需要设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置背景颜色
frame.setBackground(new Color(85,150,68));
//弹出的初始化位置
frame.setLocation(200,200);
//设置大小固定,不能拉伸
frame.setResizable(false);
}
}
1.2 panel面板
package com.javase.GUI;
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(175, 229, 123));
//panel设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(84, 150, 217));
frame.add(panel); //panel面板放进frame窗口
frame.setVisible(true); //设置可见性
//监听窗口关闭事件
//适配器模式 只重写closing
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭后需要做的事情
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); //结束程序 1为异常退出
}
});
}
}
效果图:
1.3 布局管理器
- 流式布局
package com.javase.GUI;
import java.awt.*;
/**
* 流式布局
*/
public class TestFlowLayout {
public static void main(String[] args) {
Frame frame = new Frame();
//按钮组件
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
//设置为流式布局
//frame.setLayout(new FlowLayout());
//frame.setLayout(new FlowLayout(FlowLayout.LEFT)); //布局靠左
frame.setLayout(new FlowLayout(FlowLayout.RIGHT)); //布局靠右
frame.setSize(200,200);
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setVisible(true);
}
}
- 东西南北中
package com.javase.GUI;
import java.awt.*;
/**
* 东西南北中布局
*/
public class TestBorderLayout {
public static void main(String[] args) {
Frame frame = new Frame("TestBorderLayout");
Button east = new Button("east");
Button west = new Button("west");
Button South = new Button("South");
Button North = new Button("North");
Button Center= new Button("Center");
frame.add(east,BorderLayout.EAST);
frame.add(west,BorderLayout.WEST);
frame.add(South,BorderLayout.SOUTH);
frame.add(North,BorderLayout.NORTH);
frame.add(Center,BorderLayout.CENTER);
frame.setSize(200,200);
frame.setVisible(true);
}
}
- 表格布局
package com.javase.GUI;
import java.awt.*;
/**
* 表格布局
*/
public class TestGridLayout {
public static void main(String[] args) {
Frame frame = new Frame("TestGridLayout");
Button btn1 = new Button("btn1");
Button btn2 = new Button("btn2");
Button btn3 = new Button("btn3");
Button btn4 = new Button("btn4");
Button btn5 = new Button("btn5");
Button btn6 = new Button("btn6");
frame.setLayout(new GridLayout(2,3));
frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.add(btn5);
frame.add(btn6);
frame.pack();//Java函数!自动选择最优布局
frame.setVisible(true);
}
}
综合练习
package com.javase.GUI;
import com.javase.oop.B;
import java.awt.*;
public class ExLayout {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setSize(500,400);
frame.setLocation(400,400);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
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("button1"),BorderLayout.EAST);
panel1.add(new Button("button2"),BorderLayout.WEST);
panel2.add(new Button("btn1"));
panel2.add(new Button("btn2"));
panel1.add(panel2,BorderLayout.CENTER);
panel3.add(new Button("button3"),BorderLayout.EAST);
panel3.add(new Button("button4"),BorderLayout.WEST);
for (int i = 0; i < 4; i++) {
panel4.add(new Button("btn"+i));
}
panel3.add(panel4,BorderLayout.CENTER);
frame.add(panel1);
frame.add(panel3);
frame.setVisible(true);
}
}
2 事件监听
2.1 按钮事件监听
package com.javase.GUI;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* 事件监听
*/
public class TestActionEvent {
public static void main(String[] args) {
Frame frame = new Frame();
Button button = new Button("点击");
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button);
frame.setVisible(true);
}
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了");
}
}
2.2 输入框事件监听
textField和textArea区别:
textField是单行文本编辑器;textArea是多行文本编辑器。
package com.javase.GUI;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* 输入框事件监听
*/
public class TestText {
public static void main(String[] args) {
new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame(){
TextField textField = new TextField();
add(textField);
setVisible(true);
//监听文本框输入的文字
MyActionListener1 myActionListener1 = new MyActionListener1();
//enter回车键触发事件
textField.addActionListener(myActionListener1);
//设置替换编码,如输入密码不可见
textField.setEchoChar('*');
}
}
class MyActionListener1 implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField) e.getSource(); //获得一些资源,返回给对象
System.out.println(field.getText()); //获得输入框文本
field.setText("");//此行代码表示自动清空上次输入
}
}
2.3 paint画笔
package com.javase.GUI;
import java.awt.*;
/**
* paint画笔
*/
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.fillOval(100,100,100,100);
g.setColor(Color.cyan);
//画一个矩形
g.fillRect(150,200,200,200);
}
}
2.4 鼠标监听
2.4.1 Iterator迭代器
迭代器 it 的两个基本操作是 next 、hasNext 和 remove。
调用 it.next() 会返回迭代器的下一个元素,并且更新迭代器的状态。
调用 it.hasNext() 用于检测集合中是否还有元素。
调用 it.remove() 将迭代器返回的元素删除。
package com.javase.GUI;
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) {
new MyMouseFrame("画图");
}
}
class MyMouseFrame extends Frame{
ArrayList points = new ArrayList<>();
public MyMouseFrame(String title){
super(title);
setBounds(200,200,400,300);
this.addMouseListener(new MyMouseListener());
setVisible(true);
}
@Override
public void paint(Graphics g) {
Iterator iterator = points.iterator();
while (iterator.hasNext()){ //用迭代器循环判断集合中是否还有元素
Point point = (Point) iterator.next(); //next指向集合中的下一个元素
g.setColor(Color.BLUE);
g.fillOval(point.x,point.y,10,10 );
}
}
public void addPaint(Point point){
points.add(point); //把点加进集合
}
private class MyMouseListener extends MouseAdapter {
//鼠标按下事件
@Override
public void mousePressed(MouseEvent e) {
//监听到的东西返回给窗口
MyMouseFrame myMouseFrame= (MyMouseFrame) e.getSource();
myMouseFrame.addPaint(new Point(e.getX(),e.getY())); //获取鼠标点击的位置返回产生一个点
//每次点击鼠标重新画一次
myMouseFrame.repaint();
}
}
}
2.5 窗口监听
package com.javase.GUI;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* 窗口监听事件
*/
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame(){
setBounds(200,200,400,400);
setBackground(Color.blue);
setVisible(true);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("closing");
System.exit(0);
}
@Override
public void windowActivated(WindowEvent e) {
WindowFrame windowFrame = (WindowFrame) e.getSource();
windowFrame.setTitle("别走");
System.out.println("被激活了");
}
});
}
}
2.6 键盘监听
package com.javase.GUI;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
/**
* 键盘监听
*/
public class TestKey {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
setVisible(true);
setBackground(Color.cyan);
setBounds(100,100,200,200);
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyCode());
if (e.getKeyCode() == KeyEvent.VK_Y) {
System.out.println("你按下了Y键");
}
}
});
}
}
二、Swing
1. 窗口
1.1 JFrame窗口
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class TestJFrame {
public static void main(String[] args) {
new MyJFrame().init();
}
}
class MyJFrame extends JFrame{
public void init(){
MyJFrame jFrame = new MyJFrame();
jFrame.setVisible(true);
jFrame.setBounds(100,100,200,200);
jFrame.setBackground(Color.GRAY);
JLabel jLabel = new JLabel("欢迎!");
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
jFrame.add(jLabel);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Container container = this.getContentPane();
// container.setBackground(Color.cyan);
}
}
1.2 弹窗
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* 弹窗
*/
public class TestDialog {
public static void main(String[] args) {
new DialogFrame();
}
}
class DialogFrame extends JFrame{
public DialogFrame(){
setVisible(true);
setBounds(100,100,500,500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button = new JButton("点击弹窗");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
});
button.setBounds(10,10,120,50);
Container container = this.getContentPane();
container.setLayout(null);
container.add(button);
}
}
class MyDialog extends JDialog{
public MyDialog(){
setVisible(true);
setBounds(150,150,150,150);
Container container = this.getContentPane();
container.setLayout(null);
container.add(new Label("第一个弹窗"));
}
}
1.3 图标
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
/**
* 图片图标
*/
public class TestImageIcon extends JFrame {
public TestImageIcon(){
//获取图片地址
JLabel label = new JLabel();
URL url = TestImageIcon.class.getResource("lan.jpg");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = this.getContentPane();
container.add(label);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(500,500,500,500);
}
public static void main(String[] args) {
new TestImageIcon();
}
}
1.4 JScrollDemo面板
可下滑面板
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
/**
* 下滑面板
*/
public class TestJScroll extends JFrame {
public TestJScroll(){
setVisible(true);
setBounds(100,100,200,100);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea(20,50);
textArea.setText("我们的征途是星辰大海!");
Container container = this.getContentPane();
JScrollPane jScrollPane = new JScrollPane(textArea);
container.add(jScrollPane);
}
public static void main(String[] args) {
new TestJScroll();
}
}
2. 按钮
2.1 图片按钮
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
/**
* 图片按钮
*/
public class TestButton1 extends JFrame {
public TestButton1(){
URL url = TestButton1.class.getResource("lan.jpg");
Icon icon = new ImageIcon(url);
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
Container container = this.getContentPane();
container.add(button);
setVisible(true);
setSize(700,700);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestButton1();
}
}
2.2 单选按钮
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
/**
* 单选框
*/
public class TestButton2 extends JFrame{
public TestButton2(){
//单选框
JRadioButton jRadioButton1 = new JRadioButton("A");
JRadioButton jRadioButton2 = new JRadioButton("B");
JRadioButton jRadioButton3 = new JRadioButton("C");
//由于单选框只能选择一个,放入分组中,一个分组中只能选择一个
ButtonGroup group = new ButtonGroup();
group.add(jRadioButton1);
group.add(jRadioButton2);
group.add(jRadioButton3);
Container container = this.getContentPane();
container.add(jRadioButton1,BorderLayout.NORTH);
container.add(jRadioButton2,BorderLayout.CENTER);
container.add(jRadioButton3,BorderLayout.SOUTH);
setVisible(true);
setSize(700,700);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestButton2();
}
}
2.3 复选按钮
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
/**
* 多选框
*/
public class TestButton3 extends JFrame {
public TestButton3(){
//多选框
JCheckBox checkBox1 = new JCheckBox("自动登录");
JCheckBox checkBox2 = new JCheckBox("手动登录");
JCheckBox checkBox3 = new JCheckBox("记住密码");
Container container = this.getContentPane();
container.add(checkBox1,BorderLayout.WEST);
container.add(checkBox2,BorderLayout.CENTER);
container.add(checkBox3,BorderLayout.EAST);
setVisible(true);
setSize(700,700);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestButton3();
}
}
3. 列表
3.1 下拉框
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
/**
* 下拉框
*/
public class TestSelect extends JFrame {
TestSelect(){
Container container = this.getContentPane();
//下拉框
JComboBox jComboBox = new JComboBox();
jComboBox.addItem(null);
jComboBox.addItem("芋泥奶茶");
jComboBox.addItem("布蕾奶茶");
jComboBox.addItem("绿豆冰沙");
container.add(jComboBox);
setVisible(true);
setSize(500,350);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestSelect();
}
}
3.2 列表框
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
/**
* 列表框
*/
public class TestSelect2 extends JFrame {
TestSelect2(){
Container container = this.getContentPane();
//生成列表内容
String[] content ={"芋泥奶茶","布蕾奶茶","绿豆冰沙"};
//列表中放入内容
JList jList = new JList(content);
container.add(jList);
setVisible(true);
setSize(500,350);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestSelect2();
}
}
4.文本框
4.1 文本框
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
/**
* 文本框
*/
public class TestText01 extends JFrame{
public TestText01(){
Container container = this.getContentPane();
JTextField textField1 = new JTextField("蓝天");
JTextField textField2 = new JTextField("白云");
container.add(textField1,BorderLayout.NORTH);
container.add(textField2,BorderLayout.SOUTH);
setVisible(true);
setSize(500,350);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestText01();
}
}
4.2 密码框
package com.GUI.Swing;
import javax.swing.*;
import java.awt.*;
/**
* 密码框
*/
public class TestText02 extends JFrame {
public TestText02(){
Container container = this.getContentPane();
//密码框
JPasswordField jPasswordField = new JPasswordField();
jPasswordField.setEchoChar('*');
container.add(jPasswordField);
setVisible(true);
setSize(500,350);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestText02();
}
}
4.3 文本域
JTextArea;
三、贪吃蛇
帧,如果时间片足够小,就是动画,一秒30帧
1. 主程序代码
package com.GUI.Game;
import javax.swing.*;
/**
* 主程序
*/
public class EatSnake {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("贪吃蛇小游戏");
frame.setBounds(10,10,900,720);
frame.setResizable(false); //窗口大小不可变
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//放游戏面板
frame.add(new GamePanel());
}
}
2. 游戏面板代码
package com.GUI.Game;
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坐标
int [] snakeY = new int[500];//蛇的Y坐标
String fx;
int score;
//食物坐标
int foodx;
int foody;
Random radom = new Random();
//游戏状态:开始,停止
boolean isStart = false;
boolean isFail = false;
//定时器 1000ms执行一次
Timer timer = new Timer(100,this);
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 = "R";//初始方向向右
//随机产生食物
foodx = 25 + 25*radom.nextInt(34);
foody = 75 + 25*radom.nextInt(24);
score = 0;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);//清屏
//绘制静态的面板
g.fillRect(25,75,850,600);//游戏区
this.setBackground(Color.WHITE);
//画积分
g.setColor(Color.BLUE);
g.setFont(new Font("微软雅黑",Font.BOLD,30));
g.drawString("分数"+score,750,50);
//把小蛇画上去
if(fx.equals("R")){
Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); //蛇头向右
}else if(fx.equals("L")){
Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
}else if(fx.equals("U")){
Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
}else if(fx.equals("D")){
Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
}
for (int i = 1; i < length; i++) {
Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
}
Data.food.paintIcon(this,g,foodx,foody);
//游戏状态
if(isStart == false){
g.setColor(Color.white);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("按下空格开始游戏",300,300);
}
if (isFail ) {
g.setColor(Color.RED);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("游戏失败,按下空格开始游戏",200,300);
}
}
//键盘监听事件
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode(); //获取键盘按键
if (keyCode == KeyEvent.VK_SPACE) {
if (isFail) {
isFail = false;
init();
}else {
isStart = !isStart;
}
repaint(); //换行重新绘制
}
if (keyCode == KeyEvent.VK_UP){
fx = "U";
}else if (keyCode == KeyEvent.VK_DOWN){
fx = "D";
}else if (keyCode == KeyEvent.VK_LEFT){
fx = "L";
}else if (keyCode == KeyEvent.VK_RIGHT){
fx = "R";
}
}
//重写定时器事件监听方法
@Override
public void actionPerformed(ActionEvent e) {
if (isStart && !isFail) {
//吃食物
if (snakeX[0] == foodx && snakeY[0] == foody ) {
length++;
score += 5;
//再次随机产生食物
foodx = 25 + 25*radom.nextInt(34);
foody = 75 + 25*radom.nextInt(24);
}
//后一节移到前一节
for (int i = length-1; i >0 ; i--) {
snakeX[i] = snakeX[i-1];
snakeY[i] = snakeY[i-1];
}
//改变方向
if (fx.equals("R")) {
snakeX[0] = snakeX[0] + 25;
//边界判断
if (snakeX[0] > 850) {
snakeX[0] = 25;
}
}else if (fx.equals("L")) {
snakeX[0] = snakeX[0] - 25;
//边界判断
if (snakeX[0] < 25) {
snakeX[0] = 850;
}
}else if (fx.equals("U")) {
snakeY[0] = snakeY[0] - 25;
//边界判断
if (snakeY[0] < 75) {
snakeY[0] = 650;
}
}else if (fx.equals("D")) {
snakeY[0] = snakeY[0] + 25;
//边界判断
if (snakeY[0] > 650) {
snakeY[0] = 75;
}
}
//撞到自己就算失败
for (int i = 1; i < length; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
isFail = true;
}
}
repaint();
}
timer.start();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
3. 数据中心代码
package com.GUI.Game;
import javax.swing.*;
import java.net.URL;
import javax.swing.ImageIcon;
/**
* 数据中心
*/
public class Data {
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 URL bodyurl = Data.class.getResource("statics/body.png");
public static URL foodurl = Data.class.getResource("statics/food.png");
public static ImageIcon right = new ImageIcon(righturl);
public static ImageIcon body = new ImageIcon(bodyurl);
public static ImageIcon food = new ImageIcon(foodurl);
public static ImageIcon up = new ImageIcon(upurl);
public static ImageIcon down = new ImageIcon(downurl);
public static ImageIcon left = new ImageIcon(lefturl);
}
由于自己的素材一直获取不到,且获取到的大小不合适,最后还是采用了狂神的素材。
本文含有隐藏内容,请 开通VIP 后查看