How to choose JButton

It will be a really theoretical question, just rub me. I need to do something with my JButtons, and I don't know where to start.

So I need it so that I can click on JButton and get a visual confirmation that it is selected, for example, a red frame or white background or something like that. And I want it to stay that way until another JButton is selected in the same way. Right now, when I click on Jbutton, there is a short visual display that it was clicked on, but I can’t do this any longer.

I tried playing a little with ChangeListeners, but no results.

So my question is basically: what approach would you recommend me to try?

1 - go back to ChangeListener, this is the only option 2 - JButton has another option that does just that

Sorry if it's too vague, but everything else I found was super-specific and did not answer my questions.

+6
source share
2 answers

I wonder if you want to use JToggleButton, maybe one of them is added to ButtonGroup to select only one button at a time.

change
eg:

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 will look like this:
enter image description here

+10
source

You can try changing the background color:

 boolean jButton1clicked = false; jButton1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { jButton1selected = !jButton1selected; } ); jButton1.setBackgroundColor(jButton1clicked ? Color.green : Color.red); 
0
source

Source: https://habr.com/ru/post/901837/


All Articles