This will be a really theoretical question, just bear with me a bit. I need to do something with my JButtons, and I have no idea where to start.
So what I need is to be able to click on a JButton, and have a visual proof that it is selected, for example a red border or white background or something. And I want it to stay like that until another JButton is selected in the same way. Right now, when I click on a Jbutton there is a short visual display that it was clicked, but I can't make it lasts longer.
I tried to play a bit with ChangeListeners, but no results.
So my question is basically: what kind of approach would you advise me to try?
1 - go back to ChangeListener, it's the only option 2 - JButton has another option that does exactly that
Sorry if it's too vague, but everything else I found was super specific, and didn't answer my questions.
I wonder if you want to use a JToggleButton, perhaps one added to a ButtonGroup so that only one button is selected at a time.
edit
for example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ToggleArray extends JPanel {
private static final int SIDE = 5;
public ToggleArray() {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button selected: " + e.getActionCommand());
}
};
setLayout(new GridLayout(SIDE, SIDE));
ButtonGroup btnGroup = new ButtonGroup();
for (int i = 0; i < SIDE * SIDE; i++) {
String text = String.format("[%d, %d]", i % SIDE, i / SIDE);
JToggleButton btn = new JToggleButton(text);
btn.addActionListener(listener);
btnGroup.add(btn);
add(btn);
}
}
private static void createAndShowGui() {
ToggleArray mainPanel = new ToggleArray();
JFrame frame = new JFrame("ToggleArray");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
which would look like:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With