You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Lambda函数实现Java Swing按钮点击时变色

Java Swing按钮点击变色的两种实现方法

你推测的方向是对的,有两种常用方式实现这个需求:

方法一:通过事件源获取按钮

在Lambda表达式中,利用ActionEvent的getSource()方法获取触发事件的按钮实例,强转为JButton后即可修改其颜色:

修改后的window类代码:

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

public class window {
    JFrame frame;
    window(String title){
        this.frame = new JFrame(title);
        JButton button = new JButton("Text");
        // 点击时修改按钮背景色
        button.addActionListener(x -> {
            JButton sourceBtn = (JButton) x.getSource();
            sourceBtn.setBackground(Color.RED);
            // 可选:修改前景色(文字颜色)
            sourceBtn.setForeground(Color.WHITE);
        });
        this.frame.setSize(550,550);
        button.setBounds(550/2-75,550/2-75,150,50);

        this.frame.add(button);
        this.frame.setLayout(null);
        this.frame.setVisible(true);
    }
}

方法二:将按钮设为类成员变量

把JButton定义为类的成员变量,这样在Lambda中可以直接访问并修改:

修改后的window类代码:

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

public class window {
    JFrame frame;
    JButton button; // 设为类成员变量
    window(String title){
        this.frame = new JFrame(title);
        this.button = new JButton("Text");
        // 直接访问类成员修改颜色
        button.addActionListener(x -> {
            button.setBackground(Color.BLUE);
            button.setForeground(Color.WHITE);
        });
        this.frame.setSize(550,550);
        button.setBounds(550/2-75,550/2-75,150,50);

        this.frame.add(button);
        this.frame.setLayout(null);
        this.frame.setVisible(true);
    }
}

补充说明

  • 需要导入java.awt.Color类才能使用颜色常量
  • 实际开发中不推荐使用null布局,建议用FlowLayout、BorderLayout等标准布局管理器管理组件位置

内容的提问来源于stack exchange,提问作者BigBlueWhale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:27:10