初识Java gui

初识Java gui

基本关系图

component

  • Button

  • TextArea

  • Label

  • Container

    • Window

      • Frame
      • Dialog
    • Panel


Frame

制作第一个Java窗口,使用Frame类

  1. 创建类继承Frame类
		this.title=title;           //设置标题
        setLayout(null);            //设置布局
        setLocation(x, y);          //设置位置
        setVisible(true);           //设置可见性
        setSize(w,h);               //设置大小
        setBackground(color);       //设置背景颜色

这里注意setvisible属性参数必为true,否则将会不显示


在这里插入图片描述

这里是通过在子类构造函数中设置一些相关属性

  1. 在主函数也就是main方法里创建子类实例对象,并通过构造方法进行相关属性赋值
 		MyFrame myFrame = new MyFrame("01",100,100,100,100,Color.CYAN);     //实例1
        MyFrame myFrame1 = new MyFrame("02",100,100,200,100,Color.CYAN);    //实例2
        MyFrame myFrame2= new MyFrame("03",100,100,100,200,Color.CYAN);     //实例3
        MyFrame myFrame3= new MyFrame("04",100,100,200,200,Color.CYAN);     //实例4

在这里插入图片描述

Pannel

pannel可以看成一个空间,不能单独存在,可以加到Frame里

	    Panel panel=new Panel();        //创建面板实例
 		myFrame.add(panel);				//在窗口对象里添加pannel面板
        panel.setBackground(Color.BLUE);
        panel.setBounds(100,100,200,200);

在这里插入图片描述

解决窗口关闭
  1. 对象为Frame类的实例
addWindowListener(new WindowAdapter() {
            @Override                                           //添加窗口监听事件,重写window Closing方法
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }

这样窗口就可正常点击关闭


布局方式(layout)

  • 流式布局(Flowlayout)

    myFrame.setLayout(new FlowLayout());            				//流式布局
    myFrame.setLayout(new FlowLayout(FlowLayout.LEFT));             //流式布局
    myFrame.setLayout(new FlowLayout(FlowLayout.RIGHT));            //流式布局
    

在这里插入图片描述

在这里插入图片描述

  • 东南西北中(Borderlayout)

      		myFrame.setLayout(new BorderLayout());                          //东南西北中
            myFrame.add(new Button("east"),BorderLayout.EAST);
            myFrame.add(new Button("west"),BorderLayout.WEST);
            myFrame.add(new Button("south"),BorderLayout.SOUTH);
            myFrame.add(new Button("north"),BorderLayout.NORTH);
            myFrame.add(new Button("center"),BorderLayout.CENTER);
    

在这里插入图片描述

  • 表格布局(Gridlayout)

    		myFrame.setLayout(new GridLayout(3,2));          		   //表格布局,三行两列
            myFrame.add(new Button("button1"));
            myFrame.add(new Button("button2"));
            myFrame.add(new Button("button3"));
            myFrame.add(new Button("button4"));
            myFrame.add(new Button("button5"));
            myFrame.add(new Button("button6"));
            myFrame.pack();                                            //java函数,自动完整显示图形
    

在这里插入图片描述

布局使用

创建如下图所示布局

在这里插入图片描述


      MyFrame myFrame = new MyFrame("01",800,800,100,100,Color.CYAN);     //实例1
        myFrame.setLayout(new GridLayout(2,1));
        Panel panel=new Panel();
        Panel panel1 = new Panel();
        Panel panel2 = new Panel();
        Panel panel3 = new Panel();
        panel.setLayout(new GridLayout(2,1));
        panel1.setLayout(new GridLayout(2,2));
        panel2.setLayout(new BorderLayout());
        panel3.setLayout(new BorderLayout());
        myFrame.add(panel2);
        myFrame.add(panel3);
        panel2.add(new Button("button1"),BorderLayout.WEST);
        panel.add(new Button("button2"));
        panel.add(new Button("button3"));
        panel2.add(panel,BorderLayout.CENTER);
        panel2.add(new Button("button4"),BorderLayout.EAST);
        panel3.add(new Button("button5"),BorderLayout.WEST);
        panel1.add(new Button("button6"));
        panel1.add(new Button("button7"));
        panel1.add(new Button("button8"));
        panel1.add(new Button("button9"));
        panel3.add(panel1,BorderLayout.CENTER);
        panel3.add(new Button("button10"),BorderLayout.EAST);
        myFrame.pack();

主要应用三种布局结合,通过面板来实现


事件监听

前面已经使用过事件监听,窗口关闭的例子使用的是 addWindowListener 方法,通过在参数里传入事件对象。

Frame的监听事件为 addWindowLister ,而对于一般的组件使用 addActionLister 方法即可,参数需要传入监听实例

		Button button1 = new Button("button1");						//按钮创建
        frame.add(button1);
        button1.addActionListener(new mylister());					//监听实例对象
        Firstframe.windowclose(frame);								//封装的关闭窗口方法
//监听类,实现ActionListener接口
class mylister implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮被点击了");
    }
}

当再次点击按钮时,会在控制台输出 actionPerformed 方法体里的语句

System.out.println("按钮被点击了"+e.getSource()+"\t"+e.getActionCommand());	//e.getSource返回事件源对象

getActionCommand方法默认返回标签名,可以通过setActionCommand进行设置,参数为字符串类型

输入框监听

使用TextField或者TextArea类来创建输入框

TextField textField = new TextField("文本框");
textField.addActionListener(new lister1());
add(textField);
class lister1 implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(((TextField)e.getSource()).getText());                  //打印文本框信息
        ((TextField)e.getSource()).setText("");									   //设置文本框内容清空
    }
}

因为getSource返回的是object类型,所以需要进行强转,然后通过对象设置相关属性

文本框事件需要使用使用回车键来执行

简易计算器

  1. 首先创建计算器类继承Frame

    class Calcute extends Frame{}
    
  2. 分析需要的组件

    • 需要三个输入框,实现运算显示(操作数和结果数)

    • 需要标签实现操作符

    • 按钮实现事件绑定

      FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);        //流式布局
      setBounds(100,100,300,300);                  //窗口设置
      setTitle("简易计算器");
      setLayout(flowLayout);
      
      textField = new TextField(10);                          //文本组件
      textField1 = new TextField(10);
      result = new TextField(20);
      Label label = new Label("+");                              //标签组件
      Button button = new Button("=");                           //按钮组件
      setVisible(true);
      
      utton.addActionListener(new CalLister());              //监听器绑定
      add(textField);                                         //添加组件到容器
      add(label);
      add(textField1);
      add(button);
      add(result);
      pack();
      
  3. 监听类

    private class CalLister implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            result.setText(""+(Integer.parseInt(textField.getText())+Integer.parseInt(textField1.getText())));
            textField.setText("");
            textField1.setText("");
        }
    }
    

全部代码显示

public class Testcal {
    public static void main(String[] args) {
        Firstframe.windowclose(new Calcute());
    }
}
class Calcute extends Frame{
    private TextField textField,textField1,result;
    private void load1(){
        FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);        //流式布局
        setBounds(100,100,300,300);                  //窗口设置
        setTitle("简易计算器");
        setLayout(flowLayout);
    }
    private void load(){
        load1();
        textField = new TextField(10);                          //文本组件
        textField1 = new TextField(10);
        result = new TextField(20);
        Label label = new Label("+");                              //标签组件
        Button button = new Button("=");                           //按钮组件
        setVisible(true);
        button.addActionListener(new CalLister());              //监听器绑定
        add(textField);                                         //添加组件到容器
        add(label);
        add(textField1);
        add(button);
        add(result);
        pack();
    }
    Calcute(){
        load();
    }
    private class CalLister implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            result.setText(""+(Integer.parseInt(textField.getText())+Integer.parseInt(textField1.getText())));
            textField.setText("");
            textField1.setText("");
        }
    }
}

效果图

在这里插入图片描述

画笔工具

同样创建类继承Frame,在类中重写paint方法

 @Override
    public void paint(Graphics g) {
        g.setColor(Color.CYAN);										//画笔颜色
        g.drawOval(100,100,200,200);								//画圆
        g.fillOval(200,200,200,200);								//实心圆
    }

在这里插入图片描述

重写paint方法后,会自动执行paint方法里语句


鼠标监听事件

鼠标监听事件可以加到容器组件,例如Frame或者pannel类型对象。

addMouseListener(new MyLister());   //鼠标事件监听,newMyLister是监听类的一个实例对象
class MyLister extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
        //super.mousePressed(e);
        //System.out.println(e.getSource());
        ((MyMouse)e.getSource()).points.add(new Point(e.getX(),e.getY()));
        ((MyMouse)e.getSource()).repaint();
    }

MouseAdapter是鼠标适配器监听模式,可以按需去重写需要监听事件方法,对应的是MouseListener

还有一点需要注意,这里MouseAdapter是一个类可以被继承,而MouseListener是一个接口,只能被实现

前面对按钮和文本框添加的监听实例,也是由一个接口实现的 即ActionListener

简单模拟鼠标画点

案例分析

  1. 首先需要监听鼠标按压事件
  2. 重写paint方法进行画图
  3. 按压事件发生进行画图

其中可以通过鼠标按压事件每次调用paint进行作图,这就需要用集合存储每次按压事件所产生的点,通过这些点进行paint作图

全部代码如下

class MyMouse extends Frame{
    ArrayList<Point> points;					//Point类,有下x,y两个属性
    String title;
    @Override
    public void paint(Graphics g) {
        Iterator<Point> iterator = points.iterator();
        while (iterator.hasNext())
        {   Point point=iterator.next();
            g.setColor(Color.black);
            g.fillOval(point.x,point.y,10,10);
        }
//        for (Point x:points
//             ) {
//            g.fillOval(x.x,x.y,10,10);
//        }
    }
    void load1(){                            //主窗口加载
        setBounds(100,100,300,300);
        setVisible(true);
        addMouseListener(new MyLister());   //鼠标事件监听
    }
    void load(){
        load1();
        points= new ArrayList<>();
    }
    MyMouse(String title){
        super(title);
        load();
    }
    class MyLister extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            //super.mousePressed(e);
            //System.out.println(e.getSource());
            ((MyMouse)e.getSource()).points.add(new Point(e.getX(),e.getY()));			//向下转型
            ((MyMouse)e.getSource()).repaint();
        }
    }

通过鼠标事件可以获得每次点击的点的位置坐标,存储在集合属性上,通过每次点击调用repaint方法实现多次绘图。

遍历集合元素时还可通过增强for

窗口监听

窗口监听,WindowListener ,是窗口相关的一些事件

addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                System.out.println("窗口打开");
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("窗口关闭");
                System.exit(0);
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("窗口已关闭");
            }
            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("窗口被激活啦");
                setTitle("窗口被激活");
            }

        });

键盘监听

键盘监听也是绑定给容器的,比如Frame,通过addkeyListener方法,参数为键盘监听事件实例对象,可以用KeyListener接口或者keyAdapter类,区别是KeyAdapter可以按需重写方法,而keyListener需要重写所用方法

 addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
//                System.out.println(e.getKeyChar());
//                System.out.println(e.getModifiersEx());
//                System.out.println(e.getKeyCode());
//                System.out.println(e.getKeyLocation());
//                System.out.println(e.isActionKey());
                if (e.getKeyCode()==17)
                {
                    System.out.println("你按下啦ctrl键");
                }
                if (e.getKeyCode()==KeyEvent.VK_SHIFT)
                {                                                                   //判断按键可以用静态属性																						Keyevent.VK_SHIFT这种方法
                    System.out.println("你按下了shift");
                }
                System.out.println(KeyEvent.getKeyText(e.getKeyCode()));            //获取按键名字
                System.out.println(e.getKeyChar());
            }

getKeycode获取按键对映int值,可以通过此方法判断点击啦哪个按键


Swing之 Jframe

Swing类是在Awt的基础上进行改善优化的类,增加了一些功能,和Awt类里方法大致相同,Swing下子类都是以字母J开头

 //setLayout(new FlowLayout(FlowLayout.RIGHT));
        setBounds(100,100,500,500);
        setBackground(Color.cyan);                                                  //没有显示该效果
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);                    //窗口关闭
        JLabel jLabel = new JLabel();
        jLabel.setText("这是标签");
        jLabel.setBounds(100,100,200,200);
        //jLabel.setHorizontalAlignment(SwingConstants.CENTER);                         //设置文本标签居中,当没有添加容器布局时才生效
        //add(jLabel);
        Container contentPane = getContentPane();//获取容器面板
        contentPane.setBackground(Color.CYAN);										//显示效果
        contentPane.setBounds(200,200,100,100);
        Container contentPane1 = getContentPane();
        //contentPane.setLayout(null);
        //setLayout(new FlowLayout(FlowLayout.RIGHT));           //执行此布局
        contentPane.add(jLabel);                            //通过默认容器添加组件和直接添加组件效果相同,当创建默认容																器后,默认容器布局就是Jframe布局

Jframe与Frame大致相同,不同在于Jframe需要创建一个默认的容器,背景颜色可以在容器里设置,该容器默认就是窗口大小。

也可在该容器上设置布局方式,就是jframe的布局方式。

JDialog

JDialog也是继承Window的类,所以也是一个窗口,和Jframe的使用方法类似,也可设置title和可见性属性,同时也有默认容器,在容器里设置弹窗背景颜色

class Jd extends JFrame{
    void init(){
        setBounds(100,100,500,500);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);                    //窗口关闭
        Container contentPane = getContentPane();
        contentPane.setLayout(null);                                                //绝对布局
        JButton jButton = new JButton("点击弹出弹窗");
        jButton.setBounds(100,100,200,200);
        contentPane.add(jButton);
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog jDialog = new JDialog();
                jDialog.setBounds(100,100,200,200);             //和jframe的原点一样,并不是按钮为原点
                jDialog.setTitle("这是弹窗");
                jDialog.setVisible(true);
                jDialog.getContentPane().setBackground(Color.BLUE);
            }
        });
    }
    Jd(){
        init();
    }
}

注意JDialog默认具有窗口关闭功能

icon与ImageIcon

创建图标类实现Icon接口,重写paintIcon和getIconWidth和getIconHeight方法.或者通过匿名内部类的写法

Icon icon = new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                g.fillOval(x,y,10,10);
            }

            @Override
            public int getIconWidth() {
                return 0;
            }

            @Override
            public int getIconHeight() {
                return 0;
            }
        };

图标可以加在label标签里

JLabel iconlable = new JLabel("iconlable",icon,SwingConstants.CENTER);		//SwingConstants常量属性

ImageIcon和Icon相似,ImageIcon是图片图标

ImageIcon imageIcon = new ImageIcon(url);					//url可以通过class.getResource方法获得图片url

JscrollPanel与文本域

Jscrol滑动滚动条,当文本域大小大于窗口大小时就会出现

 JTextArea jTextArea = new JTextArea(100,100);					//行,列
        jTextArea.setText("文本框");
        JScrollPane jScrollPane = new JScrollPane(jTextArea);		//参数为组件
        setBounds(100,100,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
        add(jScrollPane);

效果图

在这里插入图片描述


图片按钮、单选框,多选框

图片按钮通过创建Jbutton组件然后添加图片图标

JButton jButton = new JButton();
        jButton.setIcon(imageIcon);											//图片图标
        contentPane.add(jButton);

单选框和多选框分别通过JRadiobutton和JCheckbox创建

		JRadioButton jRadioButton1 = new JRadioButton("1");
        JRadioButton jRadioButton2 = new JRadioButton("2");
        JRadioButton jRadioButton3 = new JRadioButton("3");
        ButtonGroup buttonGroup = new ButtonGroup();				//创建组
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);
        buttonGroup.add(jRadioButton3);
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(jRadioButton1,BorderLayout.NORTH);
        contentPane.add(jRadioButton2,BorderLayout.CENTER);
        contentPane.add(jRadioButton3,BorderLayout.SOUTH);
        setBounds(100,100,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

注意单选框需要创建button group,然后添加单选按钮,这样才能实现单选

多选框的实现较为简单

		JCheckBox jCheckBox = new JCheckBox("1");
        JCheckBox jCheckBox1 = new JCheckBox("2");
        Container contentPane = getContentPane();
        contentPane.setLayout(new FlowLayout());
        contentPane.add(jCheckBox);
        contentPane.add(jCheckBox1);
        setBounds(100,100,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

文本框,密码框

文本框通过JTextField创建,密码框通过JPasswordField创建

 		JTextField jTextField = new JTextField("文本框",20);						//后面参数代表字符个数
        Container contentPane = getContentPane();
        //contentPane.setLayout(new FlowLayout());
        contentPane.add(jTextField);
        setBounds(100,100,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
  		JPasswordField jPasswordField = new JPasswordField("密码框",10);
        jPasswordField.setEchoChar('#');									//设置显示样式,用#替代输入字符
        Container contentPane = getContentPane();
        contentPane.setLayout(new FlowLayout());
        contentPane.add(jPasswordField);
        setBounds(100,100,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

不设置布局方式,将会采用默认布局

r contentPane = getContentPane();
//contentPane.setLayout(new FlowLayout());
contentPane.add(jTextField);
setBounds(100,100,300,300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);

  		JPasswordField jPasswordField = new JPasswordField("密码框",10);
        jPasswordField.setEchoChar('#');									//设置显示样式,用#替代输入字符
        Container contentPane = getContentPane();
        contentPane.setLayout(new FlowLayout());
        contentPane.add(jPasswordField);
        setBounds(100,100,300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

不设置布局方式,将会采用默认布局

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值