Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to actually select a JButton

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.

like image 453
Cristol.GdM Avatar asked Nov 18 '11 19:11

Cristol.GdM


1 Answers

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:
enter image description here

like image 179
Hovercraft Full Of Eels Avatar answered Oct 17 '22 22:10

Hovercraft Full Of Eels