组件:窗口、弹窗、面板、文本框、列表框、按钮、图片、监听事件、鼠标、键盘事件
一、简介
GUI的核心开发技术:Swing AWT。
弊端:
- 页面不美观
- 需要jre环境
学习的必要性
- 可以写出自己心中想要的一些小工具
- 可以维护swing界面
- 了解MVC架构,了解监听!
二、AWT
1、AWT介绍
- 包含了很多类和接口,GUI:图形用户界面编写
- 元素:窗口,按钮,文本框
- java.awt
2、组件和容器
1、Frame
package com.jjl.GUI.lessDmo01;
import java.awt.*;
//gui的第一个界面
public class TestFrame {
public static void main(String[] args) {
//Frame
Frame frame=new Frame("我的第一个Java图形界面窗口");
//需要设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(1000,800);
//设置窗口大小固定
frame.setResizable(false);
//设置背景颜色
frame.setBackground(new Color(60, 63, 65));
//弹出的初始位置
frame.setLocation(400,200);
}
}
注意:窗口正常关闭不了,只能停止Java运行
回顾封装,创建多个窗口
package com.jjl.GUI.lessDmo01;
import java.awt.*;
public class TestFrame2 {
public static void main(String[] args) {
//展示多个窗口
MyFrame myFrame1=new MyFrame(200,200,200,200,Color.darkGray);
MyFrame myFrame2=new MyFrame(400,200,200,200,Color.gray);
MyFrame myFrame3=new MyFrame(200,400,200,200,Color.black);
MyFrame myFrame4=new MyFrame(400,400,200,200,Color.pink);
}
}
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、面板(panel)
解决了点击关闭窗口时结束程序的监听事件
package com.jjl.GUI.lessDmo01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//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(60, 63, 65));
//panel设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(60,60,60));
//frame.add(panel)
frame.add(panel);
//可见性
frame.setVisible(true);
//监听事件,监听窗口关闭事件 System.exit(0);
frame.addWindowListener(new WindowAdapter() {
/**
* @param e
* 适配器模式
* 窗口关闭点击关闭的时候需要做的事情
*/
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
3、布局管理器
- 流式布局
package com.jjl.GUI.lessDmo01;
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");
//设置流式布局
//FlowLayout.LEFT:表示靠左,默认居中
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.setBounds(200,200,400,400);
//添加按钮
frame.add(button1);
frame.add(button2);
frame.add(button3);
//窗口可见性
frame.setVisible(true);
//监听关闭窗口事件
frame.addWindowListener(new WindowAdapter() {
/**
* @param e
*/
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
- 东西南北中
package com.jjl.GUI.lessDmo01;
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.setBounds(200,200,400,400);
//窗口可见性
frame.setVisible(true);
//监听关闭窗口事件
frame.addWindowListener(new WindowAdapter() {
/**
* @param e
*/
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
- 表格式布局 Grid
package com.jjl.GUI.lessDmo01;
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("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(3,2));
frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.add(btn5);
frame.add(btn6);
frame.pack();//Java函数,自动布局
frame.setVisible(true);
//监听关闭窗口事件
frame.addWindowListener(new WindowAdapter() {
/**
* @param e
*/
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
- 总结练习
package com.jjl.GUI.lessDmo01;
import java.awt.*;
public class TestOVER {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setLayout(new GridLayout(2,1));
frame.setBounds(300,300,600,400);
frame.setBackground(new Color(60,63,65));
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(panel2,BorderLayout.CENTER);
panel3.add(panel4,BorderLayout.CENTER);
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"));
panel3.add(new Button("East-3"),BorderLayout.EAST);
panel3.add(new Button("West-3"),BorderLayout.WEST);
for (int i = 0; i < 4; i++) {
panel4.add(new Button("p4-btn-"+i));
}
frame.setVisible(true);
//监听关闭窗口事件
frame.addWindowListener(new WindowAdapter() {
/**
* @param e
*/
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
3、事件监听
点击按钮触发动作
package com.jjl.GUI.lesson2;
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 TestAction {
public static void main(String[] args) {
//按下按钮时触发事情
Frame frame = new Frame();
Button button = new Button();
//因为addActionListener()需要一个addActionListener,所以需要构造一个addActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
windownClose(frame);//关闭窗口
}
//关闭窗体的事件
private static void windownClose(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("qqqqqqq");
}
}
多个按钮共享一个事件
package com.jjl.GUI.lesson2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestActionTwo {
public static void main(String[] args) {
//两个按钮,实现同一个监听
//启动,停止
Frame frame = new Frame("开始停止");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值
button2.setActionCommand("button2-stop");
MyMoitor myMoitor = new MyMoitor();
button1.addActionListener(myMoitor);
button2.addActionListener(myMoitor);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
class MyMoitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了:"+e.getActionCommand());
}
}
4、简易计算器
4.1、输入框TextField监听
package com.jjl.GUI.lesson2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestField extends TestAction{
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("");//回车之后自动清空
}
}
4.2、简易计算器,组合+内部类回顾
package com.jjl.GUI.lesson2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestCalc {
public static void main(String[] args) {
new Calculator();
}
}
//计算器类
class Calculator extends Frame{
public Calculator(){
//3个文本框
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(20);
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(num1,num2,num3));
//1个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
class MyCalculatorListener implements ActionListener{
//获取三个变量
private TextField num1,num2,num3;
public MyCalculatorListener(TextField num1,TextField num2,TextField num3){
this.num1=num1;
this.num2=num2;
this.num3=num3;
}
@Override
public void actionPerformed(ActionEvent e) {
//1获取加数,和被加数
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
//2.相加后,放到第三个数
num3.setText(String.valueOf(n1+n2));
//3.清空
num1.setText("");
num2.setText("");
}
}
使用组合,代码优化
package com.jjl.GUI.lesson2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestCalc {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
//计算器类
class Calculator extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadFrame(){
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(20);
//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);
}
}
class MyCalculatorListener implements ActionListener{
//使用组合的方式(在一个类中组合另一个类),获取计算器这个对象
Calculator calculator=null;
public MyCalculatorListener(Calculator calculator){
this.calculator=calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
//1获取加数,和被加数
int n1=Integer.parseInt(calculator.num1.getText());
int n2=Integer.parseInt(calculator.num2.getText());
//2.相加后,放到第三个数
calculator.num3.setText(String.valueOf(n1+n2));
//3.清空
calculator.num1.setText("0");
calculator.num2.setText("0");
}
}
完全改造为面向对象——内部类
package com.jjl.GUI.lesson2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestCalc {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
//计算器类
class Calculator extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadFrame(){
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(20);
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener());
//1个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
//内部类可以访问外部类的方法
private class MyCalculatorListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//1获取加数,和被加数
int n1=Integer.parseInt(num1.getText());
int n2=Integer.parseInt(num2.getText());
//2.相加后,放到第三个数
num3.setText(String.valueOf(n1+n2));
//3.清空
num1.setText("0");
num2.setText("0");
}
}
}
5、画笔
package com.jjl.GUI.lesson3;
import java.awt.*;
import com.jjl.GUI.lesson2.*;
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFrame();
}
}
class MyPaint extends Frame{
public void loadFrame(){
setBounds(200,200,600,400);
setVisible(true);
}
/**
* @param g the specified Graphics window
* 画笔
*/
@Override
public void paint(Graphics g) {
//画笔,需要颜色
g.setColor(Color.red);
g.drawOval(100,100,100,100);//空心圆
g.fillOval(200,100,100,100);//实心圆
g.setColor(Color.GREEN);
g.fillRect(150,200,200,200);//实心矩形
}
}
6、鼠标监听
实现鼠标画画
package com.jjl.GUI.lesson3;
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 MyFrame("画画");
}
}
class MyFrame extends Frame{
ArrayList points;
//画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
public MyFrame(String title){
super(title);
setBounds(200,200,400,300);
//存鼠标点击的点
points=new ArrayList<>();
setVisible(true);
//鼠标监听器,正对这个窗口
this.addMouseListener(new MyMouseListener());
}
/**
* @param g the specified Graphics window
* 画画,监听鼠标的事件
*/
@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{
/**
* @param e
*/
@Override
public void mousePressed(MouseEvent e) {
MyFrame frame = (MyFrame) e.getSource();
//这个我们点击的时候,就会在界面上产生一个点
//这个点就是鼠标的点
frame.addPaint(new Point(e.getX(),e.getY()));
//每次点击鼠标都需要重新画一遍
frame.repaint();//刷新
}
}
}
7、窗口监听事件
1、使用内部类,和匿名内部类编写窗口关闭事件
package com.jjl.GUI.lesson3;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame {
public WindowFrame(){
setBackground(Color.blue);
setBounds(100,100,600,400);
setVisible(true);
//addWindowListener(new MyWindowListener());
//匿名内部类,建议这样写
this.addWindowListener(
new WindowAdapter() {
/**
* @param e
*/
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
//
// //内部类
// class MyWindowListener extends WindowAdapter{
// /**
// * @param e
// */
// @Override
// public void windowClosing(WindowEvent e) {
// //setVisible(false);//隐藏窗口
// System.exit(0);//正常退出,1:非正常退出
// }
// }
//
}
2、监听窗口是否为当前活动窗口
package com.jjl.GUI.lesson3;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame {
public WindowFrame(){
setBackground(Color.blue);
setBounds(100,100,600,400);
setVisible(true);
//addWindowListener(new MyWindowListener());
//匿名内部类,建议这样写
this.addWindowListener(
new WindowAdapter() {
/**
* @param e
* 窗口打开时(用不上)
*/
@Override
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened:窗口已打开");
}
/**
* @param e
*/
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing:窗口关闭中");
System.exit(0);
}
/**
* @param e(用不上)
*/
@Override
public void windowClosed(WindowEvent e) {
System.out.println("windowClosed:窗口已经关闭");
}
/**
* @param e
*/
@Override
public void windowActivated(WindowEvent e) {
System.out.println("windowActivated:为当前活动窗口");
}
}
);
}
}
8、键盘监听
package com.jjl.GUI.lesson3;
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(300,300,600,400);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
/**
* @param e
* 键盘按下
*/
@Override
public void keyPressed(KeyEvent e) {
//获取键盘按下的键
int keyCode = e.getKeyCode();//获取被按下的键的键盘码
if (keyCode==KeyEvent.VK_UP){
System.out.println("你按下了上键");
}
}
});
}
}
1、窗口、面板
窗口的关闭事件,文本标签的X,Y对齐,文本颜色,通过创建容器设置窗口背景颜色
package com.jjl.GUI.lesson4;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo {
public void init(){
JFrame frame = new JFrame("这是一个JFrame窗口");
frame.setVisible(true);
frame.setBounds(600,400,600,400);
//frame.setBackground(Color.CYAN);
//设置文字
JLabel label = new JLabel("欢迎Java");
frame.add(label);
//让文本标签居中
label.setHorizontalAlignment(SwingConstants.CENTER);//设置标签内容沿X轴的对齐方式
label.setVerticalAlignment(SwingConstants.TOP);//设置标签内容沿着Y轴的对齐方式
label.setForeground(Color.white);
//获取一个容器,所有的东西只能放在容器里
Container contentPane = frame.getContentPane();
contentPane.setBackground(new Color(60,60,60));
//关闭事件
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new JFrameDemo().init();
}
}
2、弹窗
JDialog,用来被弹出,默认就有关闭事件
package com.jjl.GUI.lesson5;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
//主窗口
public class DialogDemo extends JFrame {
public DialogDemo(){
this.setVisible(true);
this.setSize(700,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//创建一个容器
Container container=this.getContentPane();
//绝对布局
container.setLayout(null);
//按钮
JButton button=new JButton("点击弹出一个对话框");//创建
button.setBounds(30,30,200,50);
//点击按钮是弹窗
button.addActionListener(new AbstractAction() {
@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 contentPane = this.getContentPane();
contentPane.setLayout(null);
contentPane.add(new Label("学习Java"));
}
}
3、标签
文字标签:new Label(“学习Java”)
图标:Icon
1、创建图形作为图标
package com.jjl.GUI.lesson5;
import javax.swing.*;
import java.awt.*;
//图标,需要实现类,Frame继承
public class IconDemo extends JFrame implements Icon {
private int width;
private int height;
public IconDemo(int width,int height){
this.width=width;
this.height=height;
}
public IconDemo() {
}
public void init(){
this.setBounds(200,200,600,400);
IconDemo iconDemo = new IconDemo(15, 15);
//图标放在标签,也可以放在按钮上
JLabel icontest = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(icontest);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new IconDemo().init();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fillOval(x,y,width,height);
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
}
2、将图片设置为图标
package com.jjl.GUI.lesson5;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
this.setBounds(200,200,600,400);
//获取图片的地址
JLabel label = new JLabel("imageIcon");
URL url = ImageIconDemo.class.getResource("java.png");//获取当前这个类所在的同级目录下的资源
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(label);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}
4、面板
1、JPanel
package com.jjl.GUI.lesson6;
import javax.swing.*;
import java.awt.*;
public class JPanelDeo extends JFrame {
public JPanelDeo(){
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,3));
container.add(panel1);
container.add(panel2);
panel1.add(new JButton("1"));
panel1.add(new JButton("2"));
panel1.add(new JButton("3"));
panel2.add(new JButton("3"));
panel2.add(new JButton("3"));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,400);
}
public static void main(String[] args) {
new JPanelDeo();
}
}
2、页面滚动JScrollPanel
package com.jjl.GUI.lesson6;
import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
public JScrollDemo(){
Container contentPane = this.getContentPane();
//文本域,限制输入的行数和列数
JTextArea jTextArea = new JTextArea(20, 50);
jTextArea.setText("欢迎学习Java");
//添加Scroll面板 获取滚动条
JScrollPane scrollPane=new JScrollPane(jTextArea);
contentPane.add(scrollPane);
this.setVisible(true);
this.setBounds(300,300,600,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
5、按钮
1、将图片放在按钮上
package com.jjl.GUI.lesson6;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo01 extends JFrame {
public JButtonDemo01(){
//构造一个容器
Container container=this.getContentPane();
//绝对布局,这样才能设置控件的大小
container.setLayout(null);
//获取当前目录下的资源
URL url =JButtonDemo01.class.getResource("java.png");
//将图片变成图标
Icon icon =new ImageIcon(url);
//把图标放在按钮上
JButton button = new JButton();
button.setIcon(icon);
button.setBounds(20,20,100,100);
//当鼠标经过时提示的文本
button.setToolTipText("图片按钮");
container.add(button);
this.setVisible(true);
this.setBounds(300,300,600,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo01();
}
}
2、单选框
package com.jjl.GUI.lesson6;
import javax.swing.*;
import java.awt.*;
public class JButtonDemo02 extends JFrame{
public JButtonDemo02(){
//构造一个容器
Container container=this.getContentPane();
//绝对布局,这样才能设置控件的大小
container.setLayout(null);
//单选框
JRadioButton readioButton1 = new JRadioButton("单选1");
JRadioButton readioButton2 = new JRadioButton("单选2");
JRadioButton readioButton3 = new JRadioButton("单选3");
readioButton1.setBounds(20,20,100,20);
readioButton2.setBounds(120,20,100,20);
readioButton3.setBounds(240,20,100,20);
//由于单选框只能选择一个,会分组,new一个button组,将三个按钮放在一个组里,这样三个就只能选一个了
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(readioButton1);
buttonGroup.add(readioButton2);
buttonGroup.add(readioButton3);
container.add(readioButton1);
container.add(readioButton2);
container.add(readioButton3);
this.setVisible(true);
this.setBounds(300,300,600,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
3、多选框
package com.jjl.GUI.lesson6;
import javax.swing.*;
import java.awt.*;
public class JButtonDemo03 extends JFrame {
public JButtonDemo03(){
//构造一个容器
Container container=this.getContentPane();
//绝对布局,这样才能设置控件的大小
container.setLayout(null);
//多选框
JCheckBox jCheckBox1 = new JCheckBox("复选1");
JCheckBox jCheckBox2 = new JCheckBox("复选2");
JCheckBox jCheckBox3 = new JCheckBox("复选3");
jCheckBox1.setBounds(20,20,100,20);
jCheckBox2.setBounds(120,20,100,20);
jCheckBox3.setBounds(240,20,100,20);
container.add(jCheckBox1);
container.add(jCheckBox2);
container.add(jCheckBox3);
this.setVisible(true);
this.setBounds(300,300,600,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
6、列表
1、下拉框
package com.jjl.GUI.lesson7;
import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo01 extends JFrame {
public TestComboboxDemo01(){
Container contentPane = this.getContentPane();
contentPane.setLayout(null);
JComboBox<Object> status = new JComboBox<>();
status.setBounds(20,20,200,50);
status.addItem(null);
status.addItem("选项1");
status.addItem("选项2");
status.addItem("选项3");
contentPane.add(status);
this.setVisible(true);
this.setBounds(400,400,600,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo01();
}
}
2、列表框
用于展示信息,一般动态扩容
package com.jjl.GUI.lesson7;
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class TestComboboxDemo02 extends JFrame {
public TestComboboxDemo02(){
Container contentPane = this.getContentPane();
//contentPane.setLayout(null);
//生成列表的内容(静态)
//String[] contents ={"1","2","3"};
//生成列表的内容(动态)
Vector contents = new Vector();
//添加动态内容
contents.add("zhangsan");
contents.add("lisi");
contents.add("wangwu");
JList jList = new JList(contents);
contentPane.add(jList);
this.setVisible(true);
this.setBounds(400,400,600,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestComboboxDemo02();
}
}
7、文本框
文本框、密码框、文本域
package com.jjl.GUI.lesson8;
import javax.swing.*;
import java.awt.*;
public class TestTextDemo01 extends JFrame {
public TestTextDemo01(){
Container container = this.getContentPane();
container.setLayout(null);
//文本框
JTextField jTextField = new JTextField("hello");
jTextField.setBounds(0,0,100,50);
JTextField jTextField2 = new JTextField("hello",20);
jTextField2.setBounds(0,70,100,50);
container.add(jTextField);
container.add(jTextField2);
//密码框
JPasswordField passwordField = new JPasswordField();
passwordField.setEchoChar('*');
passwordField.setBounds(0,160,100,50);
container.add(passwordField);
//文本域,限制输入的行数和列数
JTextArea jTextArea = new JTextArea(20, 50);
jTextArea.setText("欢迎学习Java");
//添加Scroll面板 获取滚动条,将文本域放在面板里面
JScrollPane scrollPane=new JScrollPane(jTextArea);
scrollPane.setBounds(0,230,300,300);
container.add(scrollPane);
this.setBounds(400,400,600,400);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestTextDemo01();
}
}
启动main
package com.jjl.GUI.snake;
import javax.swing.*;
public class startGame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new GamePanel());
frame.setTitle("Java学习小成果——贪吃蛇");
frame.setBounds(600,200,900,760);
frame.setResizable(false);//固定窗口大小
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
数据存放类
package com.jjl.GUI.snake;
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
public static URL upURL=Data.class.getResource("static/up.png");
public static URL headerURL=Data.class.getResource("static/header.png");
public static URL downURL=Data.class.getResource("static/down.png");
public static URL leftURL=Data.class.getResource("static/left.png");
public static URL rigthURL=Data.class.getResource("static/rigth.png");
public static URL bodyURL=Data.class.getResource("static/blue.png");
public static URL eatURL=Data.class.getResource("static/eat.png");
public static ImageIcon up=new ImageIcon(upURL);
public static ImageIcon header=new ImageIcon(headerURL);
public static ImageIcon down=new ImageIcon(downURL);
public static ImageIcon left=new ImageIcon(leftURL);
public static ImageIcon right=new ImageIcon(rigthURL);
public static ImageIcon body=new ImageIcon(bodyURL);
public static ImageIcon foob=new ImageIcon(eatURL);
}
游戏实现类
package com.jjl.GUI.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 {
//1、定义蛇的数据结构
int length;//蛇的长度
int[] snakex = new int[600];//蛇的X坐标
int[] snakey = new int[500];//蛇的y坐标
String fx;
//食物的坐标
int foodx;
int foody;
Random random=new Random();//随机数
int score;//成绩
//游戏当前的状态
boolean isStart = false;//默认不开始
boolean isFall=false;//游戏失败状态
//定时器
Timer timer = new Timer(100,this);//100毫秒执行一次
public GamePanel() {
init();
//获得焦点和键盘事件
this.setFocusable(true);//获得焦点事件,当前窗口是否为活动窗口
this.addKeyListener(this);//获得键盘监听事件
timer.start();//游戏一开始,定时器就启动
}
//2、初始化方法
public void init(){
length=3;
snakex[0]=80;snakey[0]=140;//脑袋的坐标
snakex[1]=60;snakey[1]=140;//身体1的坐标
snakex[2]=40;snakey[2]=140;//身体2的坐标
fx="R";
//把食物随机放在页面上
foodx=20+20*random.nextInt(42);
foody=120+20*random.nextInt(29);
score=0;
}
/**
* @param g the <code>Graphics</code> object to protect
* 绘制面板,我们在游戏中的所有东西,都是用这个画笔来
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);//清屏
this.setBackground(Color.WHITE);
Data.header.paintIcon(this,g,20,11);//放头部header图片
g.fillRect(20,120,850,600);
//画积分
g.setColor(Color.white);
g.setFont(new Font("微软雅黑",Font.BOLD,20));
g.drawString("成绩:"+score,700,80);
g.drawString("吃了:"+length,700,40);
//把小蛇放上去
//初始的头部坐标
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.foob.paintIcon(this,g,foodx,foody);
//游戏状态
if(isStart==false){
g.setColor(Color.white);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("按下空格开始游戏",300,400);
}
if(isFall){
g.setColor(Color.RED);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("失败了!按下空格重新开始游戏",300,400);
}
}
/**
* @param e
* 3、键盘监听事件
*/
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();//获得当前按下了哪一个键
if(keyCode==KeyEvent.VK_SPACE){
if(isFall){
//重新开始
isFall=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";
}
}
/**
* @param e
* 事件监听---需要通过固定的事件刷新
*/
@Override
public void actionPerformed(ActionEvent e) {
if(isStart && isFall==false){//如果游戏是开启状态,就让小蛇动起来
if (snakex[0]==foodx && snakey[0]==foody){
length++;//长度加一
//分数
score=score+10;
//再次随机食物
foodx=40+20*random.nextInt(40);
foody=120+20*random.nextInt(28);
}
//右移
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]+20;
//边界判断
if(snakex[0]>850){
snakex[0]=20;
}
}else if(fx.equals("L")){
snakex[0]=snakex[0]-20;
//边界判断
if(snakex[0]<20){
snakex[0]=850;
}
}else if(fx.equals("U")){
snakey[0]=snakey[0]-20;
//边界判断
if(snakey[0]<120){
snakey[0]=700;
}
}else if(fx.equals("D")){
snakey[0]=snakey[0]+20;
//边界判断
if(snakey[0]>700){
snakey[0]=120;
}
}
//撞到自己就失败
for (int i = 1; i <length ; i++) {
if (snakey[0]==snakey[i]&&snakex[0]==snakex[i]){
isFall=true;
}
}
repaint();//刷新页面
}
timer.start();
}
/**
* @param e
*/
@Override
public void keyReleased(KeyEvent e) {
}
/**
* @param e
*/
@Override
public void keyTyped(KeyEvent e) {
}
}