java 实现监听事件(使用按钮连续改变标签的颜色和字号)(上机倒数第二次作业)

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

import javax.swing.*;

public class xizang1 extends JFrame implements ActionListener {
    // 实现的点击按钮
    JFrame f;
    JButton b1, b2;
    JLabel j;

    public xizang1() {
        f = new JFrame();

        j = new JLabel("西藏民族大学");
        b1 = new JButton("红色");
        b2 = new JButton("48");

        Font f1 = new Font("黑体", Font.BOLD, 48);
        b2.setBackground(Color.yellow);//
        b1.setBackground(Color.red);
        j.setForeground(Color.RED);
        j.setFont(f1);

        JPanel jp = new JPanel();
        JPanel jp1 = new JPanel();

        jp.add(b1);
        jp.add(b2);
        jp1.add(j);

        this.add(jp, BorderLayout.CENTER);
        this.add(jp1,BorderLayout.NORTH);

        this.setVisible(true);
        this.setSize(500, 500);

        // 需要对按钮就行监听
        b1.addActionListener(this);// 这里需要指的是当前类
        b2.addActionListener(this);

    }

    public void actionPerformed(ActionEvent e) {

        if (e.getSource()==b1) {
                if(b1.getText()=="红色")
                {
                    b1.setBackground(Color.blue);// 蓝色
                    b1.setText("蓝色");
                    j.setForeground(Color.BLUE);
                }
                else
                {
                    b1.setBackground(Color.red);// 红色
                    j.setForeground(Color.red);
                    b1.setText("红色");
                }
        }

       else if (e.getSource()==b2){

            if(b2.getText()=="48")
            {
                Font f1 = new Font("黑体", Font.BOLD, 72);
                j.setFont(f1);
                b2.setText("72");

            }
            else
            {
                Font f1 = new Font("黑体", Font.BOLD, 48);
                j.setFont(f1);
                b2.setText("48");
            }
        }
        }

    public static void main(String[] args) {
        new xizang1();
    }
}
原文地址:https://www.cnblogs.com/zhouxiaoyue/p/14136479.html