Java的事件驱动入门(二)——点击按钮触发事件

前言

生成一个圆,点击“放大”按钮,这个圆可以被放大;点击“缩小”按钮,这个圆可以被缩小。

效果

代码

ControlCircle2.java:

package Test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ControlCircle2 extends JFrame {
    private JButton jbtEnlarge=new JButton("放大");
    private JButton jbtShrink=new JButton("缩小");
    private CirclePanel canvas=new CirclePanel();

    public ControlCircle2(){
        JPanel panel=new JPanel();
        panel.add(jbtEnlarge);
        panel.add(jbtShrink);

        add(canvas, BorderLayout.CENTER);
        add(panel,BorderLayout.SOUTH);

        jbtEnlarge.addActionListener(new EnlargeListener());
        jbtShrink.addActionListener(new ShrinkListener() );
    }

    public static void main(String[] args) {
        ControlCircle2 frame=new ControlCircle2();
        frame.setTitle("ControlCircle2");
        frame.setSize(200,200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    class EnlargeListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            canvas.enlarge();
        }
    }
    class ShrinkListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            canvas.shrink();
        }
    }
    class CirclePanel extends JPanel{
        private int radius=5;
        public void enlarge(){
            radius++;
            repaint();
        }
        public void shrink(){
            radius--;
            repaint();
        }
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawOval(getWidth()/2-radius,getHeight()/2-radius,2*radius,2*radius);
        }
    }

}

解析

当我们点击了“放大”按钮的时候,放大的事件监听器被触发,同理,当点击“缩小”的按钮时,缩小的监听器也会被触发。

所以监听器的设置是比较重要的,代码如下:

	jbtEnlarge.addActionListener(new EnlargeListener());
    jbtShrink.addActionListener(new ShrinkListener() );

两个按钮都被设置了事件监听器,里面的EnlargeListener和ShrinkListener就是监听器,需要手动定义,代码如下:

	class EnlargeListener implements ActionListener{
    @Override
 	   public void actionPerformed(ActionEvent e) {
 	       canvas.enlarge();
    }
 }

	class ShrinkListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        canvas.shrink();
    }
}

当“放大”事件被触发的时候,enlarge方法被调用,圆的半径会自增一次,并且调用repaint()方法重新绘制一个圆,“缩小”事件同理,代码如下:

class CirclePanel extends JPanel{
    private int radius=5;
    public void enlarge(){
        radius++;
        repaint();
    }
    public void shrink(){
        radius--;
        repaint();
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(getWidth()/2-radius,getHeight()/2-radius,2*radius,2*radius);
    }
}

你可能感兴趣的:(Java)