GUI编程

GUI

核心技术:Swing AWT

缺点:界面不美观、需要jre环境

1.AWT

  • Frame 是一个顶级窗口
  • Panel无法单独显示,必须添加到某个容器中

1.1创建窗口

Frame frame=new Frame("我的第一个界面");
//设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置颜色
frame.setBackground(new Color(123, 238, 139));
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);

结果:不能关闭!!

image

1.2创建多个窗口

public class TestFrame02 {
    public static void main(String[] args) {
        //展示多个窗口
        Color color=new Color(151, 229, 243, 255);
        MyFrame f1=new MyFrame(100,100,400,200,color);
        MyFrame f2=new MyFrame(500,100,400,200,color);
        MyFrame f3=new MyFrame(100,300,400,200,color);
        MyFrame f4=new MyFrame(500,300,400,200,color);
    }
}
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);
    }
}

image

1.3面板

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(Color.BLUE);
        //panel设置坐标,相对于frame
        panel.setBounds(50,50,400,400);
        panel.setBackground(Color.green);
        //将面板放置在frame中
        frame.add(panel);
        //设置可见
        frame.setVisible(true);
    }
}

image

1.4监听事件

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();

        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("完成事件");
    }
}

多个按钮可以公用一个监听事件

setActionCommand()不设置的话,默认是其label

MyActionListener myActionListener=new MyActionListener();
button.setActionCommand("开始");
button2.setActionCommand("结束");
button.addActionListener(myActionListener);
button2.addActionListener(myActionListener);

class MyActionListener implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
  System.out.println("完成事件:"+e.getActionCommand());
}
}

监听文本框

public class TestText01 {
public static void main(String[] args) {
  //启动
  TestActionEvent.windowClose(new MyFrame());
}
}
class MyFrame extends Frame {
public MyFrame(){
  TextField textField=new TextField();
  add(textField);

  //监听这个文本框输入的文字
  MyActionListener02 myActionListener02=new MyActionListener02();
  textField.addActionListener(myActionListener02);

  setVisible(true);
  pack();

  //设置替换符号,输入时显示替换的符号(像密码)
  textField.setEchoChar('*');
}
}

class MyActionListener02 implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
  //获得一些资源,返回的一个对象,这里监听的是文本框,就强转成TextField
  TextField field=(TextField) e.getSource();
  //获得输入框中的文本
  System.out.println(field.getText());
  field.setText("");//获取后清空文本框
}
}

1.5布局管理器

  • 流式布局
		Frame frame=new Frame();
		frame.setSize(400,400);
        //组件--按钮
        Button button1=new Button("button1");
        Button button2=new Button("button1");
        Button button3=new Button("button1");
        //设置为流式布局
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
    	//frame.setLayout(new FlowLayout());
        //frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
        //添加按钮
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);

        frame.setVisible(true);

image

  • 东西南北中
public static void main(String[] args) {
        Frame frame=new Frame();
        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(north,BorderLayout.NORTH);
        frame.add(south,BorderLayout.SOUTH);
        frame.add(center,BorderLayout.CENTER);

        frame.setSize(500,400);
        frame.setVisible(true);
}

image

  • 网格布局
public static void main(String[] args) {        
Frame frame=new Frame();        
Button button1=new Button("1");        
Button button2=new Button("2");        
Button button3=new Button("3");        
Button button4=new Button("4");        
Button button5=new Button("5");       
Button button6=new Button("6");        
frame.setLayout(new GridLayout(3,2));        
frame.add(button1);        
frame.add(button2);        
frame.add(button3);        
frame.add(button4);        
frame.add(button5);        
frame.add(button6);        
frame.pack();//自动选择最优排列?        
frame.setVisible(true);    
}

image

1.6计算器

image

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        TestActionEvent.windowClose(new Calculator());
    }
}
//计算器类
class Calculator extends Frame{
    public Calculator() {
        //3个文本框
        TextField textField1=new TextField(10);//传入字符数
        TextField textField2=new TextField(10);
        TextField textField3=new TextField(20);
        //1个按钮
        Button button=new Button("=");
        //1个标签
        Label label=new Label("+");

        //流式布局
        setLayout(new FlowLayout());

        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);

        setVisible(true);
        pack();

        //添加监听
        MyCalcListener myCalcListener=new MyCalcListener(textField1,textField2,textField3);
        button.addActionListener(myCalcListener);

    }
}
//监听器类
class MyCalcListener implements ActionListener{
    private TextField t1,t2,t3;
    public MyCalcListener() {
    }
    //在构造方法里传入操作对象
    public MyCalcListener(TextField t1,TextField t2,TextField t3) {
        this.t1=t1;
        this.t2=t2;
        this.t3=t3;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取操作数
        int num1=Integer.parseInt(t1.getText());
        int num2=Integer.parseInt(t2.getText());
        //显示结果
        t3.setText(""+(num1+num2));
        //清空输入窗口
        t1.setText("");
        t2.setText("");
    }
}

面向对象代码改进:

//简易计算器
public class TestCalc {
    public static void main(String[] args) {
        Calculator calculator=new Calculator();
        TestActionEvent.windowClose(calculator);
        calculator.loadFrame();
    }
}
//计算器类
class Calculator extends Frame{
    //属性
    TextField textField1,textField2,textField3;
    //方法
    public void loadFrame(){
        textField1=new TextField(10);//传入字符数
        textField2=new TextField(10);
        textField3=new TextField(20);
        Button button=new Button("=");
        Label label=new Label("+");
        //流式布局
        setLayout(new FlowLayout());

        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);
        setVisible(true);
        pack();
        //添加监听
        MyCalcListener myCalcListener=new MyCalcListener();
        button.addActionListener(myCalcListener);
    }
    //监听器类  ====>匿名内部类,直接访问外面的TextField
    class MyCalcListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            //获取操作数
            int num1=Integer.parseInt(textField1.getText());
            int num2=Integer.parseInt(textField2.getText());
            //显示结果
            textField3.setText(""+(num1+num2));
            //清空输入窗口
            textField1.setText("");
            textField2.setText("");
        }
    }
}

1.7画笔

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);
   }
   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.drawRect(250,250,60,40);//长方形
       //画笔用完回到默认的黑色
       g.setColor(Color.BLACK);
   }

}

image

1.8鼠标监听画点

//鼠标监听
public class TestMouseListener {
    public static void main(String[] args) {//入口
        TestActionEvent.windowClose(new MyFrame02("画图"));
    }
}

class MyFrame02 extends Frame{
     ArrayList points;//点坐标集合
    public MyFrame02(String title) {
        super(title);
        setBounds(200,200,400,300);
        
        //存鼠标点击的点
        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();//将点位取出
            //Point是自带的引用数据类型,用来存储点
            g.setColor(Color.CYAN);
            g.fillOval(point.x,point.y,10,10);
        }
    }

    //监听事件,用适配器模式,继承"MouseAdapter"不用重写所有方法
    private class MyMouseListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent e) {
           MyFrame02 frame02= (MyFrame02) e.getSource();//???
           //点击事件发生,将点存入集合
            frame02.points.add(new Point(e.getX(),e.getY()));
           //每次点击都重画
           frame02.repaint();
        }
    }
}

1.9窗口监听

public class TestWindow {
    public static void main(String[] args) {
        new WindowFrame();
    }
}
class WindowFrame extends Frame{
    public WindowFrame() {
        setBackground(Color.BLUE);
        setBounds(200,200,400,200);
        setVisible(true);
        //addWindowListener(new MyWindowListener());
        this.addWindowListener(
                //匿名内部类
                new WindowAdapter() {
            @Override//关闭窗口
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭");
                System.exit(0);
            }
        });
    }
    /*class MyWindowListener extends WindowAdapter{
        @Override
        public void windowClosing(WindowEvent e) {
            setVisible(false);
            System.exit(0);
        }
    }*/
}

1.10键盘监听

public class TestKeyListener {
    public static void main(String[] args) {
            new KeyFrame();
    }
}
class KeyFrame extends Frame{
    public KeyFrame(){
        setBounds(200,200,400,200);
        setVisible(true);
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                super.keyTyped(e);
            }
            //键盘按下
            @Override
            public void keyPressed(KeyEvent e) {
                //获得当前按下的键盘的编码
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
                if (keyCode==KeyEvent.VK_UP){
                    System.out.println("按下了上键");
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                super.keyReleased(e);
            }
        });
    }
}

2.Swing

2.1窗口、面板

public class JFrameDemo {
    public static void main(String[] args) {
       new MyJFrame().init();
    }
}
class MyJFrame extends JFrame{
    //初始化
    public void init(){
        JFrame jFrame=new JFrame("这是JFrame窗口");
        jFrame.setVisible(true);
        jFrame.setBounds(100,100,200,200);
        JLabel jLabel=new JLabel("123");
        jFrame.add(jLabel);
        //关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

2.2弹窗

//主窗口
public class DialogDemo extends JFrame {
    public DialogDemo(){
        this.setVisible(true);
        this.setSize(700,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //JFrame 放东西,容器
        Container container=this.getContentPane();
        //绝对布局
        container.setLayout(null);

        //按钮
        JButton jButton=new JButton("点击弹出对话框");
        jButton.setBounds(30,30,200,50);

        //监听事件
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹出窗口
                new MyDialog();
            }
        });
        //按钮放入容器中
        container.add(jButton);
    }

    public static void main(String[] args) {
        new DialogDemo();
    }

}

//弹出的窗口
class MyDialog extends JDialog{
    public MyDialog() {
        this.setVisible(true);
        this.setBounds(100,100,200,100);
        //this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //弹窗默认可以关闭,不需要设置
        
        Container container=this.getContentPane();
        container.setLayout(null);
       
        JLabel jLabel = new JLabel("nb~~~~");
        jLabel.setBounds(20,20,80,40);
        container.add(jLabel);

    }
}

2.3图标

  • 画图
//图标,需要实现类,Frame继承
public class IconDemo extends JFrame implements Icon {

    private int width;
    private int heigth;
    public IconDemo(int width, int heigth) throws HeadlessException {
        this.width = width;
        this.heigth = heigth;
        this.setBounds(200,200,400,300);
    }

    public IconDemo()  {
        this.setBounds(200,200,400,300);
    }
    //初始化
    public void init(){
        //创建图标
        IconDemo iconDemo=new IconDemo(width,heigth);
        //图标可以放在标签上,也可以放在按钮上
        //创建标签,放置图标,并指明位置SwingConstants.CENTER
        JLabel jLabel = new JLabel("icon", iconDemo, SwingConstants.CENTER);

        Container container =getContentPane();
        container.add(jLabel);

        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,heigth);
    }

    @Override
    public int getIconWidth() {
        return this.width;
    }

    @Override
    public int getIconHeight() {
        return this.heigth;
    }

    public static void main(String[] args) {
        new IconDemo(20,20).init();
    }
}
  • 图片
public class ImageIconDemo extends JFrame {
    public ImageIconDemo() {
        //获取图片地址,创建图标
        //ImageIconDemo.class.getResource(“***”);  获取ImageIconDemo类同级名叫***的图片地址
        URL url=ImageIconDemo.class.getResource("img.png");
        ImageIcon imageIcon=new ImageIcon(url);

        //两种方法将图标放入标签,并定位
        //JLabel jLabel=new JLabel("imageIcon",imageIcon,SwingConstants.CENTER);
        JLabel jLabel=new JLabel("imageIcon");
        jLabel.setIcon(imageIcon);
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);

        Container container =getContentPane();
        container.add(jLabel);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,200,200,100);


    }

    public static void main(String[] args) {
        new ImageIconDemo();
    }
}

2.4面板

  • JPanel
public class TestJPanel extends JFrame {
    public TestJPanel(){
        Container container=this.getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));//后面10是间距

        JPanel jPanel1=new JPanel(new GridLayout(2,1));
        JPanel jPanel2=new JPanel(new GridLayout(3,2));
        JPanel jPanel3=new JPanel(new GridLayout(2,2));
        JPanel jPanel4=new JPanel(new GridLayout(1,2));

        jPanel1.add(new JButton("1"));
        jPanel1.add(new JButton("1"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel3.add(new JButton("3"));
        jPanel3.add(new JButton("3"));
        jPanel3.add(new JButton("3"));
        jPanel3.add(new JButton("3"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));

        container.add(jPanel1);
        container.add(jPanel2);
        container.add(jPanel3);
        container.add(jPanel4);

        setVisible(true);
        setBounds(100,100,400,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestJPanel();
    }
}
  • JScrollPanel
public class JScrollDemo extends JFrame{
    public JScrollDemo() {
        Container container=this.getContentPane();

        //文本域
        JTextArea textArea=new JTextArea(20,40);
        textArea.setText("123阿斯顿匿名");

        //Scroll面板
        JScrollPane scrollPane=new JScrollPane(textArea);
        container.add(scrollPane);

        this.setVisible(true);
        this.setBounds(100,100,400,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JScrollDemo();
    }
}

image

2.5按钮

  • 悬浮解释文本
public class JButtonDemo01 extends JFrame {
    public JButtonDemo01(){
        Container container=this.getContentPane();
        //图片====》图标
        URL resource = JButtonDemo01.class.getResource("img.png");
        ImageIcon imageIcon = new ImageIcon(resource);
        //图标放按钮上
        JButton jButton=new JButton();
        jButton.setIcon(imageIcon);
        jButton.setToolTipText("悬浮解释文本");

        container.add(jButton);

        setVisible(true);
        setSize(500,400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JButtonDemo01();
    }
}
  • 单选框
public class JButtonDemo02 extends JFrame{
    public JButtonDemo02(){
        Container container=this.getContentPane();
        //单选框
        JRadioButton radioButton1=new JRadioButton("1");
        JRadioButton radioButton2=new JRadioButton("2");
        JRadioButton radioButton3=new JRadioButton("3");
        //由于单选框只能选一个:将其分组,同组中只能选一个
        ButtonGroup group=new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        group.add(radioButton3);

        container.add(radioButton1,BorderLayout.CENTER);
        container.add(radioButton2,BorderLayout.SOUTH);
        container.add(radioButton3,BorderLayout.NORTH);

        setVisible(true);
        setSize(500,400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JButtonDemo02();

    }
}

image

  • 多选框
public class JButtonDemo03 extends JFrame{
    public JButtonDemo03(){
        Container container=this.getContentPane();
        //多选框
        JCheckBox checkBox1=new JCheckBox("1");
        JCheckBox checkBox2=new JCheckBox("2");
        JCheckBox checkBox3=new JCheckBox("3");

        container.add(checkBox1,BorderLayout.NORTH);
        container.add(checkBox2,BorderLayout.CENTER);
        container.add(checkBox3,BorderLayout.SOUTH);

        setVisible(true);
        setSize(500,400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo03();
    }
}

image

2.6列表

  • 下拉框
public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01() {
        Container container=this.getContentPane();
		//下拉框
        JComboBox status=new JComboBox();
        //添加选项
        status.addItem(null);
        status.addItem("123");
        status.addItem("asd");
        status.addItem("xyz");

        container.add(status);

        this.setVisible(true);
        this.setSize(200,160);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestComboboxDemo01();
    }
}
  • 列表框
public class TestComboboxDemo02 extends JFrame{
    public TestComboboxDemo02() {
        Container container=this.getContentPane();
        //存储内容的集合
        Vector vector=new Vector();
        //将集合放入将要显示的列表中
        JList jList=new JList(vector);
        //这里动态添加
        vector.add("张三");
        vector.add("李四");
        vector.add("王五");

        container.add(jList);
        
        this.setVisible(true);
        this.setSize(200,160);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestComboboxDemo02();
    }
}

2.7文本框

  • 文本框
JTextField textField1=new JTextField("hello");
JTextField textField2=new JTextField("wrold",20);//20是规定字长

container.add(textField1,BorderLayout.SOUTH);
container.add(textField2,BorderLayout.NORTH);

image

  • 密码框
JPasswordField passwordField=new JPasswordField();
passwordField.setEchoChar('*');
container.add(passwordField);

image

  • 文本域
//文本域
JTextArea textArea=new JTextArea(20,40);
textArea.setText("123阿斯顿匿名");

//Scroll面板
JScrollPane scrollPane=new JScrollPane(textArea);
container.add(scrollPane);
posted @ 2021-08-19 14:51  酷酷丶吖  阅读(16)  评论(0)    收藏  举报