按钮点击事件

直接上代码:

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

public class MainPanel extends JFrame
{
        JButton button_1;
        JPanel JP;
        public MainPanel(){
            button_1=new JButton("pink");
            JP=new JPanel();
            JP.add(button_1);
            ColorAction pinkAction=new ColorAction(Color.PINK);
            add(JP);
            button_1.addActionListener(pinkAction);
            
            setBounds(200,200,700,500);
            setVisible(true);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            validate();
        }
        private class ColorAction implements ActionListener{
            private Color backgroundColor;
            public ColorAction(Color c){
                backgroundColor=c;
            }
            public void actionPerformed(ActionEvent event){
                JP.setBackground((backgroundColor));
            }
        }
        
   
}

在这里插入图片描述
点击后:
在这里插入图片描述

发布了30 篇原创文章 · 获赞 12 · 访问量 1286

猜你喜欢

转载自blog.csdn.net/dawn_1108/article/details/102692213