-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathToggleButton.java
More file actions
48 lines (43 loc) · 1.51 KB
/
Copy pathToggleButton.java
File metadata and controls
48 lines (43 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* Authors: Jerry Li & Victor Jiang
* Date: June 13, 2025
* Description: This class acts as a toggle button
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.function.Consumer;
import javax.swing.*;
/** A GameButton that toggles between ON and OFF states. */
public class ToggleButton extends GameButton {
private boolean state;
private final String baseText;
private final Consumer<Boolean> onChange;
// Constructor
public ToggleButton(String text, boolean initial, Consumer<Boolean> onChange) {
super("");
this.baseText = text;
this.state = initial;
this.onChange = onChange;
setFocusPainted(true);
updateVisual();
addActionListener(e -> toggle());
// Keyboard bindings for Enter/Space
getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke("SPACE"), "toggle");
getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"), "toggle");
getActionMap().put("toggle", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) { toggle(); }
});
}
private void toggle() {
state = !state;
updateVisual();
if (onChange != null) onChange.accept(state);
}
private void updateVisual() {
// Avoid Unicode symbols that may not render correctly on all systems
setText(baseText + ": " + (state ? "[ON]" : "[OFF]"));
setColor(state ? new Color(0, 120, 0) : new Color(120, 60, 60));
repaint();
}
}