GUI编程
- 1、这是什么?
- 2、它怎么玩?
- 3、该如何在我们平时运用。
- class–>可阅读的 反编译
组件
- 窗口
- 弹窗
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件
- 鼠标事件
- 键盘事件
- 外挂
- 破解工具
1、简介
Gui的核心技术:Swing AWT,
1、因为界面不美观
2、需要jre环境
为什么要学习?
1、MVC的架构
2、工作需要
3、可以写出自己想要的工具
2、AWT介绍
2.1、AWT简介
1、包含了很多的类和接口!GUI:图形用户界面编程。Esclipe:java写的
2、元素:按钮,窗口,文本框
3、java.awt
2.2、组件和容器
1、窗口
package com.xuchong.lesson1;
import java.awt.*;
//GUI的第一个界面
public class TestFrame {
public static void main(String[] args) {
//窗口对象
Frame frame=new Frame("我的第一个java图形界面窗口");//在内存中
//需要设置可见性
frame.setVisible(true);//设置可见性
frame.setSize(400,400);//设置窗口口大小
Color color =new Color(1,1,1) ;//设置背景颜色
frame.setBackground(color);
frame.setLocation(200,200);//窗口的初始位置
frame.setResizable(false);//设置窗口大小不可调整
}
}
发现的问题:窗口关不掉,停止java程序 (解决方案:监听事件)
多个窗口
package com.xuchong.lesson1;
import java.awt.*;
public class ManyFrames {
public static void main(String[] args) {
//展示多个窗口
MyFrame myFrame1 = new MyFrame(100,100,200,200,Color.blue);
MyFrame myFrame2 = new MyFrame(400,100,200,200,Color.black);
MyFrame myFrame3 = new MyFrame(100,400,200,200,Color.yellow);
MyFrame myFrame4 = new MyFrame(400,400,200,200,Color.red);
}
}
class MyFrame extends Frame{
static int id = 0;//可能存在多个窗口,我们需要一个计数器
public MyFrame(int x,int y,int h,int w,Color color){
super("MyFrame"+(++id));
setBackground(color);
setBounds(x,y,w,h);
setVisible(true);
}
}
2、Panel(面板)
package com.xuchong.lesson1;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
//Panel 可以看成一个空间 ,但是不能单独存在
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("面板");
//存在布局的概念
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//坐标
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(1,10,9));
//panel设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(Color.yellow);
//frame.add(panel)
frame.add(panel);
frame.setVisible(true);
//监听事件,监听窗口关闭事件,System.exit
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});//适配器模式
}
}
3、布局管理器
-
流式布局
package com.xuchong.lesson1; 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"); Button button4 = new Button("button4"); //设置方式为流布局 frame.setLayout(new FlowLayout(FlowLayout.LEFT)); frame.setSize(200,200); //把按钮添加上去 frame.add(button1); frame.add(button2); frame.add(button3); frame.add(button4); frame.setVisible(true); }
-
东西南北中
package com.xuchong.lesson1; import java.awt.*; public class TestESNWLayout { public static void main(String[] args) { Frame frame = new Frame("东西南北中"); //按钮 Button west = new Button("west"); Button east = new Button("east"); Button north = new Button("north"); Button south = new Button("south"); Button center = new Button("center"); frame.add(west,BorderLayout.WEST); frame.add(east,BorderLayout.EAST); frame.add(north,BorderLayout.NORTH); frame.add(south,BorderLayout.SOUTH); frame.add(center,BorderLayout.CENTER); frame.setSize(200,200); frame.setVisible(true); } }
-
表格布局
package com.xuchong.lesson1; import java.awt.*; public class TestChartLayout { public static void main(String[] args) { Frame frame = new Frame("表格定位"); Button b1= new Button("1"); Button b2= new Button("2"); frame.setLayout(new GridLayout(1,2)); frame.add(b1); frame.add(b2); frame.pack();//java函数 frame.setVisible(true); } }
4、练习:
package com.xuchong.lesson1;
import java.awt.*;
public class Test {
public static void main(String[] args) {
Frame frame =new Frame("练习");
frame.setBounds(500,500,1000,500);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
//4个面板
Panel p1 = new Panel(new BorderLayout());
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("b1"),BorderLayout.EAST);
p1.add(new Button("b2"),BorderLayout.WEST);
p2.add(new Button("b3"));
p2.add(new Button("b4"));
p3.add(new Button("b5"),BorderLayout.EAST);
p3.add(new Button("b6"),BorderLayout.WEST);
int j= 7;
for (int i = 0; i < 4; i++) {
p4.add(new Button("b"+(++j)));
}
p3.add(p4,BorderLayout.CENTER);
p1.add(p2,BorderLayout.CENTER);
frame.add(p1);
frame.add(p3);
//监听器
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
总结:
1、Frame是一个顶级窗口
2、Pannel无法单独显示,必须加到一个容器中
3、布局管理器
4、事件监听
事件监听:当某个事情发生的时候,干什么?
按钮监听:
package com.xuchong.lesson2;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮触发一些事件
Frame frame = new Frame();
Button button = new Button("aaa");
//因为需要addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
windowClose(frame);
}
//关闭窗体的方法
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//事件监听
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
多个按钮监听:
package com.xuchong.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 TestActionEvent2 {
public static void main(String[] args) {
//两个按钮实现同一个监听
Frame frame = new Frame("开始-停止");
Button button = new Button("start");
Button button1 = new Button("stop");
button.setActionCommand("button-start");
MyMonitor myMonitor = new MyMonitor();
button.addActionListener(myMonitor);
button1.addActionListener(myMonitor);
frame.add(button,BorderLayout.SOUTH);
frame.add(button1,BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
windowClose(frame);
}
//关闭窗体的方法
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//事件监听
class MyMonitor implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//获得按钮信息
System.out.println("按钮被点击了:msg:"+ e.getActionCommand());
}
}
5、计算器
5.1、输入框TextFiled监听
package com.xuchong.lesson2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestText1 {
public static void main(String[] args) {
//只管启动
new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame(){
TextField textField = new TextField();
add(textField);
//监听文本框输入的文字
MyTextListener myTextListener = new MyTextListener();
//按下这个回车就会触发这个监听
textField.addActionListener(myTextListener);
pack();
//设置替换编码
textField.setEchoChar('*');
setVisible(true);
}
}
class MyTextListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField source = (TextField)e.getSource();//获得一些资源,返回的一个对象
//获得输入框中的文本
System.out.println( source.getText());
source.setText("");//null
}
}
5.2、组合内部类回顾复习
oop原则:组合大于继承
class A extends B{//继承
}
class A {//组合
private B b;
}
package com.xuchong.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(){
//三个文本框 一个按钮 一个标签
TextField textField1 = new TextField(10);//字符数
TextField textField2 = new TextField(10);//字符数
TextField textField3 = new TextField(20);//字符数
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(textField1,textField2,textField3));
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(textField1);
add(label);
add(textField2);
add(button);
add(textField3);
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 num1Text = Integer.parseInt(num1.getText());
int num2Text = Integer.parseInt(num2.getText());
//2、将这两个数相加,放到第三个框
num3.setText(""+(num1Text+num2Text));
//3、将第一二个框清除
num1.setText("");
num2.setText("");
}
}
程序优化(面向对象):
package com.xuchong.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().loading();
}
}
//计算器类
class Calculator extends Frame {
//属性
TextField textField1,textField2,textField3;
//方法
public void loading(){
//三个文本框 一个按钮 一个标签
textField1 = new TextField(10);//字符数
textField2 = new TextField(10);//字符数
textField3 = new TextField(20);//字符数
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(this));
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(textField1);
add(label);
add(textField2);
add(button);
add(textField3);
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(calculator.textField1.getText());
int n2 = Integer.parseInt(calculator.textField2.getText());
calculator.textField3.setText(""+(n1+n2));
calculator.textField1.setText("");
calculator.textField2.setText("");
}
}
内部类:
-
更好的包装
-
内部类最大的好处就是可以畅通无阻的访问外部的属性和方法
package com.xuchong.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().loading(); } } //计算器类 class Calculator extends Frame { //属性 TextField textField1,textField2,textField3; //方法 public void loading(){ //三个文本框 一个按钮 一个标签 textField1 = new TextField(10);//字符数 textField2 = new TextField(10);//字符数 textField3 = new TextField(20);//字符数 Button button = new Button("="); button.addActionListener(new MyCalculatorListener()); Label label = new Label("+"); //布局 setLayout(new FlowLayout()); add(textField1); add(label); add(textField2); add(button); add(textField3); setVisible(true); pack(); } //监听器类 private class MyCalculatorListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //1、获得加数和被加数 // 2、将这两个数相加,放到第三个框 //3、将第一二个框清除 int n1 = Integer.parseInt(textField1.getText()); int n2 = Integer.parseInt(textField2.getText()); textField3.setText(""+(n1+n2)); textField1.setText(""); textField2.setText(""); } } }
6、画笔
package com.xuchong.lesson3; import java.awt.*; public class Paint { public static void main(String[] args) { new MyPaint().loading(); } } class MyPaint extends Frame { public void loading() { setBounds(200,200,600,500); setVisible(true); }//画笔 @Override public void paint (Graphics g){ //画笔有颜色,可以画画 //g.setColor(Color.red); //g.drawString("victory",100,100); g.fillOval(100,100,100,100); //g.setColor(Color.blue); g.fillRect(150,200,200,200); //养成习惯,画笔用完,还原到最初的颜色 } }
6、鼠标监听
目的:想用鼠标画画
package com.xuchong.lesson3;
import javax.swing.plaf.multi.MultiInternalFrameUI;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
//测试鼠标监听事件
public class MouseListener {
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 MouseListener());
setVisible(true);
}
@Override
public void paint(Graphics g) {
//画图,监听鼠标事件
Iterator iterator = points.iterator();
while (iterator.hasNext()){
Point point = (Point) iterator.next();
g.setColor(Color.blue);
g.fillOval(point.x,point.y,10,10);
}
}
//添加一个点到界面上
public void addPoint(Point point){
points.add(point);
}
//适配器模式
private class MouseListener extends MouseAdapter {
//鼠标按下,弹起,按住不放
@Override
public void mousePressed(MouseEvent e) {
MyFrame myFrame = (MyFrame) e.getSource();
//点击的时候就会产生一个点,鼠标点击的点用鼠标存点
//这个点就是鼠标的点
myFrame.addPoint(new Point(e.getX(),e.getY()));
//每次点击鼠标需要重新画一遍
myFrame.repaint();
}
}
}
7、窗口监听
package com.xuchong.lesson3;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class WindowListener {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame{
public WindowFrame (){
setTitle("未激活");
setBackground(Color.CYAN);
setBounds(100,100,300,300);
setVisible(true);
//addWindowListener(new MyWindowListener());
this.addWindowListener( new WindowAdapter() {//匿名内部类
//关闭窗口
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);//正常退出 非正常退出1
}
//激活窗口
@Override
public void windowActivated(WindowEvent e) {
WindowFrame windowFrame=(WindowFrame) e.getSource();
windowFrame.setTitle("激活");
System.out.println("窗口已激活");
}
});
}
8、键盘监听
package com.xuchong.lesson3;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
setBounds(100,100,300,400);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//获得键盘按的哪个键
int keyCode = e.getKeyCode();
if(keyCode==KeyEvent.VK_UP){
System.out.println("上");
}
}
});
}
}
9、Swing介绍
1、窗口
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends JFrame{
public void init(){
JFrame jFrame = new JFrame("JFrame窗口");
jFrame.setVisible(true);
jFrame.setBounds(100,100,200,200);
//设置文字
JLabel label = new JLabel("hello");
jFrame.add(label);
//容器实例化 获得容器
Container contentPane = jFrame.getContentPane();
contentPane.setBackground(Color.blue);
//让文本居中
label.setHorizontalAlignment(0);
//关闭窗口
//EXIT_ON_CLOSE(= 3)
//DISPOSE_ON_CLOSE( = 2)
//DO_NOTHING_ON_CLOSE( = 0)
//HIDE_ON_CLOSE(= 1)
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//建立一个窗口
new JFrameDemo().init();
}
}
label居中可以这样label1.setAlignment(java.awt.Label.CENTER);
jlabel的居中就jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
2、弹窗(layer)
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
//主窗口
public class DialogDemo extends JFrame {
public static void main(String[] args) {
new DialogDemo();
}
public DialogDemo(){
this.setVisible(true);
this.setSize(700,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame放东西需要容器
Container contentPane = this.getContentPane();
//绝对布局
contentPane.setLayout(null);
//按钮
JButton jButton = new JButton("点击弹出对话框");
jButton.setBounds(30,30,70,50);
contentPane.add(jButton);
//点击这个按钮弹出弹窗 监听器
jButton.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
//弹窗
new MyDialogDemo();
}
});
}
}
//弹窗的窗口
class MyDialogDemo extends JDialog{
public MyDialogDemo(){
this.setVisible(true);
this.setBounds(100,100,500,500);
Container contentPane = this.getContentPane();
contentPane.setLayout(null);
JLabel hello = new JLabel("Hello");
hello.setBounds(100,100,100,100);
contentPane.add(hello);
}
}
3、标签(label)
new Label("xxx");
图标ICON
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
//图标是个接口,需要实现类,JFrame继承
public class ICONDemo extends JFrame implements Icon {
private int width;
private int height;
public ICONDemo(){
}
public ICONDemo(int width, int height) throws HeadlessException {
this.width = width;
this.height = height;
}
public void init(){
ICONDemo iconDemo = new ICONDemo(15, 12);
//图标可放在按钮上也可放在标签上
JLabel jLabel = new JLabel("icon",iconDemo,SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(jLabel);
this.setVisible(true);
this.setBounds(100,100,300,300);
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.drawOval(x,y,width,height);
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
}
图片Image
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame implements Icon {
public ImageIconDemo() {
JLabel jLabel = new JLabel("ImageIconDemo");
//获取图片的地址
URL resource = ImageIconDemo.class.getResource("item.jpg");
ImageIcon imageIcon = new ImageIcon(resource);
jLabel.setIcon(imageIcon);
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
Container contentPane = this.getContentPane();
contentPane.add(jLabel);
setBounds(20,20,1000,1000);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ImageIconDemo();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
}
@Override
public int getIconWidth() {
return 0;
}
@Override
public int getIconHeight() {
return 0;
}
}
4、面板
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
public class JPanelDemo extends JFrame {
public JPanelDemo(){
Container contentPane = this.getContentPane();
contentPane.setLayout(new GridLayout(2,1,10,10));
JPanel jPanel1 = new JPanel(new GridLayout(1,3));
JPanel jPanel2 = new JPanel(new GridLayout(1,2));
JPanel jPanel3 = new JPanel(new GridLayout(2,1));
JPanel jPanel4 = new JPanel(new GridLayout(3,2));
jPanel1.add(new JButton("1"));
jPanel1.add(new JButton("1"));
jPanel1.add(new JButton("1"));
jPanel2.add(new JButton("2"));
jPanel2.add(new JButton("2"));
jPanel3.add(new JButton("3"));
jPanel3.add(new JButton("3"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
jPanel4.add(new JButton("4"));
contentPane.add(jPanel1);
contentPane.add(jPanel2);
contentPane.add(jPanel3);
contentPane.add(jPanel4);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(500,500);
}
public static void main(String[] args) {
new JPanelDemo();
}
}
滚动条
package com.xuchong.Swing;
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("小王八蛋,累死你爹了");
//JScroll面板
JScrollPane scrollPane = new JScrollPane(jTextArea);
contentPane.add(scrollPane);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(500,500);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
5、按钮
图片按钮
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo extends JFrame {
public JButtonDemo() {
Container contentPane = this.getContentPane();
//获取图片
URL resource = ImageIconDemo.class.getResource("item.jpg");
ImageIcon imageIcon = new ImageIcon(resource);
//把这个图标放到按钮上去
JButton jButton = new JButton(imageIcon);
jButton.setToolTipText("这一个图片按钮");
//add
contentPane.add(jButton);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(1000,1000);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
单选框:
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class OneSelectDemo extends JFrame {
public OneSelectDemo() {
Container contentPane = this.getContentPane();
//单选框
JRadioButton jRadioButton1 = new JRadioButton();
JRadioButton jRadioButton2 = new JRadioButton();
JRadioButton jRadioButton3 = new JRadioButton();
//由于单选框只能选一个,只能分组
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(jRadioButton1);
buttonGroup.add(jRadioButton2);
buttonGroup.add(jRadioButton3);
contentPane.add(jRadioButton1,BorderLayout.NORTH);
contentPane.add(jRadioButton2,BorderLayout.CENTER);
contentPane.add(jRadioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(1000, 1000);
}
public static void main(String[] args) {
new OneSelectDemo();
}
}
多选框:
package com.xuchong.Swing;
import javax.swing.*;
import java.awt.*;
public class ManySelectDemo extends JFrame {
public ManySelectDemo() {
Container contentPane = this.getContentPane();
//多选框
JCheckBox jCheckBox1 = new JCheckBox("jCheckBox1");
JCheckBox jCheckBox2 = new JCheckBox("jCheckBox2");
this.setLayout(new FlowLayout());
contentPane.add(jCheckBox1);
contentPane.add(jCheckBox2);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(1000, 1000);
}
public static void main(String[] args) {
new ManySelectDemo();
}
}
6、列表
下拉框
package com.xuchong.lesson4;
import com.sun.org.apache.bcel.internal.generic.NEW;
import javax.swing.*;
import java.awt.*;
public class ComboboxDemo extends JFrame {
public ComboboxDemo() {
Container contentPane = this.getContentPane();
JComboBox jComboBox = new JComboBox();
jComboBox.addItem("乱世佳人");
jComboBox.addItem("星际穿越");
jComboBox.addItem("The Last");
jComboBox.addItem("凤求凰");
contentPane.add(jComboBox);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(1000,1000);
}
public static void main(String[] args) {
new ComboboxDemo();
}
}
列表框
package com.xuchong.lesson4;
import javax.swing.*;
import java.awt.*;
public class ListDemo extends JFrame {
public ListDemo() {
Container contentPane = this.getContentPane();
//生成列表的内容,稀疏数组,压缩内容
//String[] contents ={"1","2","3"};
Vector contents=new Vector();
JList jList = new JList(contents);
contents.add("1");
contents.add("2");
contents.add("3");
contentPane.add(jList);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(1000, 1000);
}
public static void main(String[] args) {
new ListDemo();
}
}
应用场景:
选择地区
列表:展示信息
7、文本框
-
文本框
package com.xuchong.lesson4; import javax.swing.*; import java.awt.*; public class TextDemo extends JFrame { public TextDemo() { Container contentPane = this.getContentPane(); JTextField jTextField = new JTextField("hello"); JTextField jTextField1 = new JTextField("world",20); contentPane.add(jTextField,BorderLayout.NORTH); contentPane.add(jTextField1,BorderLayout.SOUTH); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(1000, 1000); } public static void main(String[] args) { new TextDemo(); } }
-
密码框
package com.xuchong.lesson4; import javax.swing.*; import java.awt.*; public class PWDDemo extends JFrame { public PWDDemo() { Container contentPane = this.getContentPane(); JPasswordField passwordField = new JPasswordField(); passwordField.setEchoChar('+'); contentPane.add(passwordField); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(1000, 1000); } public static void main(String[] args) { new PWDDemo(); } }
-
文本域
package com.xuchong.lesson4; import javax.swing.*; import java.awt.*; public class TextAreaDemo extends JFrame { public TextAreaDemo() { Container contentPane = this.getContentPane(); //文本域 JTextArea jTextArea = new JTextArea(20,50); jTextArea.setText("小王八蛋,累死你爹了"); //JScroll面板 JScrollPane scrollPane = new JScrollPane(jTextArea); contentPane.add(scrollPane); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setSize(1000, 1000); } public static void main(String[] args) { new TextAreaDemo(); } }
贪吃蛇游戏:
帧:如果时间片足够小,就是动画,一秒30帧。
键盘监听、定时器Timer
一、界面绘制
1、定义数据
2、画上去
3、监听事件
键盘
事件
数据类:
package com.xuchong.game;
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
//相对路径 tie.jpg
//绝对路径 / 相当于当前项目
public static URL headerURL= javax.xml.crypto.Data.class.getResource("/com/xuchong/game/images/ti.jpg");
public static ImageIcon header=new ImageIcon(headerURL);
public static URL upURL= javax.xml.crypto.Data.class.getResource("/com/xuchong/game/images/up.png");
public static URL downURL= javax.xml.crypto.Data.class.getResource("/com/xuchong/game/images/down.png");
public static URL rightURL= javax.xml.crypto.Data.class.getResource("/com/xuchong/game/images/right.png");
public static URL leftURL= javax.xml.crypto.Data.class.getResource("/com/xuchong/game/images/left.png");
public static ImageIcon up=new ImageIcon(upURL);
public static ImageIcon down=new ImageIcon(downURL);
public static ImageIcon right=new ImageIcon(rightURL);
public static ImageIcon left=new ImageIcon(leftURL);
public static URL bodyURL= javax.xml.crypto.Data.class.getResource("/com/xuchong/game/images/body.jpg");
public static ImageIcon body=new ImageIcon(bodyURL);
public static URL foodURL= javax.xml.crypto.Data.class.getResource("/com/xuchong/game/images/food.jpg");
public static ImageIcon food=new ImageIcon(foodURL);
}
面板类:
package com.xuchong.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坐标 25*25
int[] snakeY =new int[500];//蛇的Y坐标 25*25
String fx;
//食物的坐标
int foodX;
int foodY;
Random random=new Random();
//游戏当前的状态:开始、暂停
boolean isStart=false;
boolean isFail=false;
int grade;
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*random.nextInt(34);
foodY= 75 + 25*random.nextInt(24);
grade=0;
}
//定时器
Timer timer=new Timer(100,this);//100毫秒执行一次
//构造器
public GamePanel(){
init();
//获得焦点和键盘事件
this.setFocusable(true);//获得焦点事件
this.addKeyListener(this);
timer.start();//游戏一开始定时器启动
}
//绘制面板,游戏中的所有东西使用这个画笔来画
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);//清屏,不用的话会出现闪烁
this.setBackground(Color.WHITE);
//绘制静态的面板
Data.header.paintIcon(this,g,25,11);//头部广告栏
g.fillRect(25,75,850,600);//默认的游戏界面
//画积分
g.setColor(Color.BLACK);
g.setFont(new Font("微软雅黑",Font.BOLD,18));
g.drawString("长度"+length,750,35);
g.drawString("分数"+grade,750,55);
//把小蛇画上去
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,foodX);
//画状态
if(isFail){
g.setColor(Color.RED);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("失败,按下空格开始游戏",300,300);
}
if(isStart==false){
g.setColor(Color.WHITE);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("按下空格开始游戏",300,300);
}
}
//键盘监听事件
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();//获得键盘按键是哪一个
if(keyCode==KeyEvent.VK_SPACE){//按下的是空格键
if(isFail){
//重新开始
isFail=false;
init();
}else {
isStart=!isStart;
repaint();
}
}
//小蛇移动
if(keyCode==KeyEvent.VK_UP){
fx="U";
}else if(keyCode==KeyEvent.VK_DOWN){
fx="D";
}else if(keyCode==KeyEvent.VK_RIGHT){
fx="R";
}else if(keyCode==KeyEvent.VK_LEFT){
fx="L";
}
}
//事件监听----需要固定事件来刷新,1s 10次
@Override
public void actionPerformed(ActionEvent e) {
if(isStart&&isFail==false){
//小蛇长大
if(isStart){
if(snakeX[0]==foodX&&snakeY[0]==foodY){
length++;
//分数加10
grade=grade+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("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=!isFail;
}
}
repaint();
}
timer.start();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
游戏启动类:
package com.xuchong.game;
import javax.swing.*;
//游戏的主启动类
public class StartGame {
public static void main(String[] args) {
JFrame jFrame = new JFrame("贪吃蛇小游戏");
jFrame.add(new GamePanel());//加入游戏面板
jFrame.setBounds(10,10,900,720);
jFrame.setVisible(true);
jFrame.setResizable(false);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}