文章目录
1、简介
Gui的核心技术:Swing AWT
不流行主要原因:
- 因为界面不美观。
- 需要 jre 环境!
为什么我们要学习?
- 可以写出自己心中想要的一些小工具。
- 工作时候,也可能需要维护到swing界面,概率极小!
- 了解MVC架构,了解监听!
2、AWT
2.1、AWT介绍
AWT:抽象的窗口工具,包含了很多的类和接口
元素:窗口、按钮、文本框
java.awt包下
2.2、组件和容器
2.2.1、Frame
public class TestFrame {
public static void main(String[] args) {
// Frame类 看源码
Frame frame = new Frame("我的第一个java图形界面窗口");
//需要设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400, 400);
//设置背景颜色
frame.setBackground(new Color(213, 124, 124));
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
问题:关闭按钮无反应,关闭程序进程才会关闭窗口
封装
public class TestFrame2 {
public static void main(String[] args) {
//展示多个窗口
MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.CYAN);
MyFrame myFrame2 = new MyFrame(300, 100, 200, 200, Color.GREEN);
MyFrame myFrame3 = new MyFrame(500, 100, 200, 200, Color.RED);
}
}
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.2.1、Panel
解决了窗口关闭问题
//Panel 可以看成是一个空间,但不能单独存在
public class TestPanel {
public static void main(String[] args) {
// Frame类
Frame frame = new Frame();
// 布局的概念
Panel panel = new Panel();
// 设置布局
frame.setLayout(null);
//坐标
frame.setBounds(300, 300, 400, 400);
frame.setBackground(Color.black);
//Panel设置坐标,相对于frame
panel.setBounds(50, 50, 300, 300);
panel.setBackground(Color.gray);
//frame.add(panel)
frame.add(panel);
frame.setVisible(true);
//监听事件,监听窗口关闭事件()system.exit(0)
//适配器模式
frame.addWindowListener(new WindowAdapter() {
//点击窗口关闭时需要做的事情
@Override
public void windowClosing(WindowEvent e) {
//super.windowClosing(e);
System.exit(0);
}
});
}
}
2.2.3、布局管理
-
流式布局
public class TestFlowLayout { public static void main(String[] args) { // Frame类 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); } }
-
东南西北中
public class TestBorderLayout { public static void main(String[] args) { // Frame类 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); } }
-
表格布局 grid
public class TestGridLayout { public static void main(String[] args) { // Frame类 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); } }
布局练习
public class TestDemo1 {
public static void main(String[] args) {
Frame frame = new Frame("练习");
//窗口设置
frame.setBackground(Color.black);
frame.setBounds(100,100,400,300);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
//创建四个面板
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));
//创建1和2的button
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);
//创建3和4d1button
p3.add(new Button("East-2"),BorderLayout.EAST);
p3.add(new Button("West-2"),BorderLayout.WEST);
p4.add(new Button("p4-btn-1"));
p4.add(new Button("p4-btn-2"));
p4.add(new Button("p4-btn-3"));
p4.add(new Button("p4-btn-4"));
p3.add(p4,BorderLayout.CENTER);
//添加面板
frame.add(p1);
frame.add(p3);
//关闭界面
//监听事件监听窗口关闭System.exit(0)
//适配器模式
frame.addWindowListener(new WindowAdapter() {
//点击窗口关闭要做的事情
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
总结:
Frame是一个顶级窗口
Paner无法单独显示,必须添加到某个容器中。
布局管理器
流式布局
东西南北中
表格布局
大小、定位、背景颜色、可见性、监听。
2.2.4、事件监听
事件监听:当某个事件发生的时候,干什么?
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮,出发一些事情
Frame frame = new Frame();
Button button = new Button();
//因为,addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
windowClose(frame);
}
//关闭窗口的事件
public 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");
}
}
多个按钮共享一个事件
public class TestActionEvent2 {
public static void main(String[] args) {
//两个按钮实现同一个监听
Frame frame = new Frame("开始-停止");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//可以显示的定义出发会返回的命令,如果不显式定义,则会走默认的值
//可以多个按钮只写一个监听类
button2.setActionCommand("button2-stop");
//因为,addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
MyMonitor myMonitor = new MyMonitor();
button1.addActionListener(myMonitor);
button2.addActionListener(myMonitor);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
windowClose(frame);
}
//关闭窗口的事件
public 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());
}
}
2.2.5、输入框TextField 监听
public class Test {
public static void main(String[] args){
new MyFrame();
}
}
class MyFrame extends Frame {
public MyFrame() {
TextField textField = new TextField();
add(textField);
//监听输入框输入的文字
textField.addActionListener(new MyActionListener());
//设置替换编码
textField.setEchoChar('*');
setVisible(true);
pack();
}
}
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField)e.getSource();
System.out.println(field.getText());//获得输入框的文本
field.setText(""); //清空输入框
}
}
2.2.6、简易计算器,(组合+内部类)
oop原则:组合大于继承!
//简易计算器
public class TestCalc {
public static void main(String[] args) {
new Calculator();
}
}
//计算器类
class Calculator extends Frame {
public Calculator() {
//三个文本框
TextField num1 = new TextField(10);//字符数
TextField num2 = new TextField(10);//字符数
TextField num3 = new TextField(20);//字符数
//一个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(num1,num2,num3));
//一个标签
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(""+(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);//字符数
Button button = new Button("=");//一个按钮
Label label = new Label("+");//一个标签
button.addActionListener(new MyCalculatorListener(this));//按钮的监听事件
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
//监听器类
class MyCalculatorListener implements ActionListener {
//获取三个变量
Calculator calculator;
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(""+(n1+n2));
//3、清除前两个框
calculator.num1.setText("");
calculator.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);//字符数
Button button = new Button("=");//一个按钮
Label label = new Label("+");//一个标签
button.addActionListener(new MyCalculatorListener());//按钮的监听事件
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
//监听器类
//内部类最大的好处,就是可以畅通无阻的访问外部的类和方法
private class MyCalculatorListener implements ActionListener {
@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("");
}
}
}
2.2.7、画笔
基本图形
public class TestPaint {
public static void main(String[] args) {
new MyPaint().loadFrame();
}
}
class MyPaint extends Frame{
public void loadFrame(){
setBounds(300,300,600,400);
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(200,100,100,100);
//养成习惯画笔用完,将他还原到最初的颜色
}
}
2.2.8、鼠标监听
public class TestMouseListener {
public static void main(String[] args) {
new MyFrames("画图");
}
}
class MyFrames extends Frame{
ArrayList points;
//画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
public MyFrames(String title){
super(title);
setBounds(200,200,500,400);
//存储鼠标点击的点
points = new ArrayList<>();
//鼠标监听器,正对着这个窗口
this.addMouseListener(new MyMouseListener());
setVisible(true);
}
@Override
public void paint(Graphics g) {
//画画需要监听鼠标的事件
Iterator iterator = points.iterator();
while (iterator.hasNext()){
Point point= (Point) iterator.next();
g.setColor(Color.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) {
super.mousePressed(e);
MyFrames frames = (MyFrames) e.getSource();
//这个我们点击的时候,就会在界面上显示一个点
//这个点就是鼠标的点
frames.addPoint(new Point(e.getX(),e.getY()));
//每次点击鼠标都需要重画一次
frames.repaint();//刷新
}
}
}
画图构造流程图
编程步骤:
- 生成main方法(1)
- 创建自己的类(2),框架类,画笔类(3),监听器类(5)
- (2)生成框架类内基本信息,super,Bounds,Visidle
- (2)生成集合ArrayLiset
- (3)画笔类:生成:迭代器iterator; 条件:假如迭代器内有元素,则赋值point; 并且画圆,坐标(point.x,y),大小,颜色;
- (4)创建一集合点,将未来监控的点传到画笔迭代器里
- (5)监听器继承MouseAdapter,生成mousePressed;获取按键来源;将点的来源传至集合点(4);再次刷漆
- (2)框架监控鼠标;(1)new 框架;运行
2.2.9、窗口监听
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame {
public WindowFrame() {
setBackground(Color.cyan);
setBounds(300, 300, 500, 400);
setVisible(true);
//addWindowListener(new MyWindowListener());
this.addWindowListener(
//匿名内部类
new WindowAdapter() {
//关闭窗口
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing");
System.exit(0);
}
//激活窗口
@Override
public void windowActivated(WindowEvent e) {
WindowFrame source = (WindowFrame) e.getSource();
source.setTitle("被激活了");
System.out.println("windowActivated");
}
}
);
}
//通过匿名内部类可以不用另外创建类
class MyWindowListener extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);//隐藏窗口,通过按钮,隐藏当前窗口
System.exit(0);//正常退出
}
}
}
2.2.10、键盘监听
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame{
public KeyFrame(){
setBounds(300,300,500,400);
setVisible(true);
this.addKeyListener(new KeyAdapter() {
//键盘按下
@Override
public void keyPressed(KeyEvent e) {
//键盘按下的键是哪一个
int keyCode = e.getKeyCode();
System.out.println(keyCode);
if (keyCode==KeyEvent.VK_UP){
System.out.println("你按下了上建");
}
}
});
}
}
3、Swing
3.1、窗口、面板
public class TestJFrame {
//init;初始化
public void init() {
JFrame jf = new JFrame("这是一个JFrame窗口");
jf.setVisible(true);
jf.setBounds(300, 300, 500, 400);
//设置文字JLabel
JLabel label = new JLabel("欢迎来到打击娘炮文化第一现场");
jf.add(label);
//让文本标签居中 设置水平对齐
label.setHorizontalAlignment(SwingConstants.CENTER);
//需要容器实例化,颜色才能现象
Container contentPane = jf.getContentPane();
contentPane.setBackground(Color.GREEN);
//关闭事件
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestJFrame().init();
}
}
3.2、弹窗
JDialog,用来被弹出,默认就有关闭事件!
//主窗口
public class TestDialog extends JFrame {
public TestDialog(){
this.setVisible(true);
this.setSize(600,450);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame 放东西容器
Container contentPane = this.getContentPane();
//绝对布局
contentPane.setLayout(null);
//按钮
JButton button = new JButton("点击弹出一个对话框");
button.setBounds(30,30,200,200);
//点击按钮弹出弹窗
button.addActionListener(new AbstractAction() { //监听器
@Override
public void actionPerformed(ActionEvent e) {
new MyTestDialog();
}
});
contentPane.add(button);
}
public static void main(String[] args) {
new TestDialog();
}
}
//弹窗的窗口
class MyTestDialog extends JDialog{
public MyTestDialog(){
this.setVisible(true);
this.setBounds(400,300,300,300);
Container contentPane = this.getContentPane();
contentPane.setLayout(null);
JLabel label = new JLabel("这不是一个JButton");
label.setSize(200,100);
contentPane.add(label);
}
}
3.3、标签
label
new JLabel("xxx")
Iocn
//图标,需要实现类 Frame继承
public class TestIcon extends JFrame implements Icon {
private int width;
private int height;
public TestIcon(){
}
public TestIcon(int width, int height) {
this.width = width;
this.height = height;
}
public void init(){
TestIcon icon = new TestIcon(10, 10);
//图标放在标签上,也可放在按钮上
JLabel label = new JLabel("icon", icon, SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestIcon().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;
}
}
图标 Icon
public class TestImageIcon extends JFrame{
public TestImageIcon(){
//获取图片的地址
JLabel label = new JLabel("logo");
URL url = TestImageIcon.class.getResource("logo.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);
setBounds(200,200,500,500);
}
public static void main(String[] args) {
new TestImageIcon();
}
}
3.4、面板
JPanel
public class TestJPanel extends JFrame {
public TestJPanel(){
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(2,2));
jPanel1.add(new Button("1"));
jPanel1.add(new Button("1"));
jPanel1.add(new Button("1"));
jPanel2.add(new Button("2"));
jPanel2.add(new Button("2"));
jPanel3.add(new Button("3"));
jPanel3.add(new Button("3"));
jPanel4.add(new Button("4"));
jPanel4.add(new Button("4"));
jPanel4.add(new Button("4"));
jPanel4.add(new Button("4"));
contentPane.add(jPanel1);
contentPane.add(jPanel2);
contentPane.add(jPanel3);
contentPane.add(jPanel4);
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestJPanel();
}
}
其他创建和使用与awt类似,类名加J前缀,增加了一些快捷实现
滚动条面板JScrollPanel
public class TestJScrollPanel extends JFrame {
public TestJScrollPanel(){
Container contentPane = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(20,50);
textArea.setText("这是文本域");
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(scrollPane);
this.setVisible(true);
this.setBounds(300,300,500,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestJScrollPanel();
}
}
3.5、按钮
图片按钮
public class TestJButton extends JFrame {
public TestJButton(){
Container contentPane = this.getContentPane();
//将一个图片变为图标
URL url = TestJButton.class.getResource("logo.png");
ImageIcon icon = new ImageIcon(url);
//把这个图片放在按钮上
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
contentPane.add(button);
this.setVisible(true);
this.setBounds(200,200,480,480);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestJButton();
}
}
- 单选按钮
public class TestJButton2 extends JFrame {
public TestJButton2(){
Container contentPane = this.getContentPane();
//将一个图片变为图标
URL url = TestJButton2.class.getResource("logo.png");
ImageIcon icon = new ImageIcon(url);
//单选框
JRadioButton jb1 = new JRadioButton("JB1");
JRadioButton jb2 = new JRadioButton("JB2");
JRadioButton jb3 = new JRadioButton("JB3");
//由于单选框只能选择一个,可以将他们分组,一个组只能选一个。
ButtonGroup group = new ButtonGroup();
group.add(jb1);
group.add(jb2);
group.add(jb3);
contentPane.add(jb1,BorderLayout.CENTER);
contentPane.add(jb2,BorderLayout.NORTH);
contentPane.add(jb3,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(200,200,480,480);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestJButton2();
}
}
- 多选按钮
public class TestJButton3 extends JFrame {
public TestJButton3(){
Container contentPane = this.getContentPane();
//将一个图片变为图标
URL url = TestJButton3.class.getResource("logo.png");
ImageIcon icon = new ImageIcon(url);
//单选框
JCheckBox jb1 = new JCheckBox("JB1");
JCheckBox jb2 = new JCheckBox("JB2");
contentPane.add(jb1,BorderLayout.SOUTH);
contentPane.add(jb2,BorderLayout.NORTH);
this.setVisible(true);
this.setBounds(200,200,480,480);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestJButton3();
}
}
3.6、列表
- 下拉框
public class TestCombobox extends JFrame {
public TestCombobox(){
Container contentPane = this.getContentPane();
JComboBox comboBox = new JComboBox();
comboBox.addItem(null);
comboBox.addItem("正在上映");
comboBox.addItem("已下架");
comboBox.addItem("即将上映");
contentPane.add(comboBox);
this.setVisible(true);
this.setSize(480,480);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestCombobox();
}
}
- 列表框
public class TestCombobox2 extends JFrame {
public TestCombobox2(){
Container contentPane = this.getContentPane();
//生成列表的内容
//String []contents = {"1","2","3"};
Vector contents = new Vector();
JList list = new JList(contents);
contents.add("张三");
contents.add("李四");
contents.add("王五");
contentPane.add(list);
this.setVisible(true);
this.setSize(480,480);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestCombobox2();
}
}
- 应用场景
- 下拉框:选择地址或者一些单个选项(一到两个最好使用按钮,两个以上使用下拉框,节省内存布局)
- 列表框:展示信息,一般是动态扩容。
3.7、文本框
- 文本框 TextField
public class TestText extends JFrame {
public TestText(){
Container contentPane = this.getContentPane();
JTextField textField1 = new JTextField("hello");
JTextField textField2 = new JTextField("world",20);//文本框+尺寸
contentPane.add(textField1,BorderLayout.WEST);
contentPane.add(textField2,BorderLayout.EAST);
this.setVisible(true);
this.setSize(480,480);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestText();
}
}
- 密码框 PasswordField
public class TestText1 extends JFrame {
public TestText1(){
Container contentPane = this.getContentPane();
JPasswordField passwordField = new JPasswordField();//***
passwordField.setEchoChar('?');
contentPane.add(passwordField);
this.setVisible(true);
this.setSize(480,480);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestText1();
}
}
- 文本域 TextArea
public class JScrollDemo extends JFrame {
public JScrollDemo() {
Container container = this.getContentPane();
//文本域
JTextArea textArea = new JTextArea(20, 50);
textArea.setText("这个是文本域");
//Scroll 面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setBounds(100,100,300,350);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JScrollDemo();
}
}
4、贪吃蛇
编程流程
-
定义数据
-
画上去
-
监听事件
- 键盘监听
- 事件监听
游戏主启动类
//游戏主启动类
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 GamePanel extends JPanel implements KeyListener , ActionListener {
//定义贪吃蛇的数据结构
int length;//长度
int[] snakeX = new int[600];//蛇的x坐标
int[] snakeY = new int[500];//蛇的x坐标
String fx;//脑袋的方向
Boolean isStart;//游戏当前的状态:开始、停止
Boolean isFail;//游戏状态:失败,未失败
//食物坐标
int foodX;
int foodY;
Random random = new Random();
//积分
int score;
//上一次方向
String lastFx;
//构造器
public GamePanel() {
init();
//获得焦点和键盘事件
this.setFocusable(true);//获得焦点事件
this.addKeyListener(this);//获得键盘监听事件
timer.start();//游戏一开始定时器就启动
}
//定时器 1毫秒为单位
Timer timer = new Timer(100,this);//100毫秒执行一次
//初始化方法
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"; //初始方向向右
isStart = false;// 默认不开始
//把食物随机分布在界面上
foodX = 25 + 25*random.nextInt(34);
foodY = 100 + 25*random.nextInt(24);
isFail = false;//默认不失败
score=length*10;
//lastFx = "R";//上一次方向初始向右
}
//绘制面板 我们游戏中的所有东西,都用这个画笔来画
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);//清屏,提高画面
//绘制静态面板
this.setBackground(Color.WHITE);//绘制静态的面板
Data.heardIcon.paintIcon(this, g, 15, 11);//头部广告栏
g.fillRect(15, 75, 850, 600);//默认的游戏界面
//画积分
g.setColor(Color.white);
g.setFont(new Font("微软雅黑", Font.BOLD, 15));//设置字体
g.drawString("长度"+length,750,35);
g.drawString("分数"+score,750,50);
//画食物
Data.foodIcon.paintIcon(this,g,foodX,foodY);
//把小蛇画上去
if (fx.equals("R")) {
Data.rightIcon.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头初始化向右,需要通过方向来判断
} else if (fx.equals("L")) {
Data.leftIcon.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头初始化向左,需要通过方向来判断
} else if (fx.equals("U")) {
Data.upIcon.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头初始化向上,需要通过方向来判断
} else if (fx.equals("D")) {
Data.downIcon.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇头初始化向下,需要通过方向来判断
}
for (int i = 1; i < length; i++) {
Data.bodyIcon.paintIcon(this, g, snakeX[i], snakeY[i]);//身体的坐标
}
//游戏状态
if (!isStart) {
g.setColor(Color.white);
g.setFont(new Font("微软雅黑", Font.BOLD, 40));//设置字体
g.drawString("按下空格开始游戏", 300, 300);
}
if (isFail){
g.setColor(Color.RED);
g.setFont(new Font("微软雅黑", Font.BOLD, 40));//设置字体
g.drawString("游戏失败,按下空格重新开始游戏", 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_LEFT){
fx="L";
}else if (keyCode==KeyEvent.VK_RIGHT){
fx="R";
}
}
//事件监听--需要固定事件来刷新 1s=10次
@Override
public void actionPerformed(ActionEvent e) {
if (isStart && !isFail){//如果游戏是开始状态,就让小蛇动起来
//吃食物
if (snakeX[0] == foodX && snakeY[0] == foodY){
length++;//长速加1
score+=10;//分数加10
//再次随机食物
foodX = 25 + 25*random.nextInt(34);
foodY = 25 + 25*random.nextInt(24);
}
//右移
for (int i = length-1; i > 0 ; i--) {//后一节移到前一节位置 snakeX[1] = snakeX[0];
snakeX[i] = snakeX[i-1];//向前移动一节
snakeY[i] = snakeY[i-1];//向前移动一节
}
//走向
if (fx.equals("R")){
snakeX[0] = snakeX[0]+25;
if (snakeX[0]>840){snakeX[0]=15;}//边界判断
}else if (fx.equals("L")){
snakeX[0] = snakeX[0]-25;
if (snakeX[0]<15){snakeX[0]=840;}//边界判断
} 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 keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
}
数据中心
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);
}
}
常用码
Frame; 框架
Panel; 面板
setVisible; 可见性true
setSize(x,x); 初始尺寸
setLocation(x,x); 初始位置,x,y
setBounds(x,x,x,x); 初始坐标+尺寸
setBackground(new color(x,x,x)); 颜色,三基色
setResizable; 大小是否可调,true,false
setLayout(new FlowLayout(FlowLayout.LEFT)); 流式布局
frame.add(east,BorderLayout.EAST); 方向布局
frame.setLayout(new GridLayout(3,2)); 表格布局
ActionListener; 监听器
TextField; 文本框
TextArea; 文本域
PasswordField; 密码框
Integer.parseInt(); String类转int类
paint; 画笔
MouseAdapter; 鼠标监听器
WindowListener; 窗口监听
KeyListener; 键盘监听
DefaultCloseOperation(WindowConstants.); 关闭事件(JFrame)
ContentPane; 容器(JFrame)
Layout; 容器自动定位(JFrame)
Button; 按钮
RadioButton; 单选按钮
ButtonGroup; 组
CheckBox; 多选按钮
ComboBox; 下拉框
List; 列表框
Dialog; 对话框
Label; 标签
IconDemo; 图标
ImageIcon; 图片
Scroll; 滚动条
Timer; 定时器
贪吃蛇素材:
链接:https://pan.baidu.com/s/1gomqbEOvskVdVGQ0h8wy1A
提取码:h12a
视频学习地址:https://www.bilibili.com/video/BV1DJ411B75F?spm_id_from=333.999.0.0