如何通过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
相关产品推荐
相关产品推荐

