3

I created a small tool set which is composed of around 10 buttons. These buttons are added to a JToolBar. Currently, it puts a square around the first button by default; however, I would like a different button to be the default. How can I accomplish this? Below is an example of how I am adding the buttons. I have tried select.setSelected and a few other methods but haven't had any luck.

  JToolBar sideBar = new JToolBar();

  JButton select = new JButton(new ImageIcon("Media/select.png"));
  select.setBorderPainted(false);
  select.setContentAreaFilled(false);

  sideBar.add(select);

Here's an image of the current result:

current result - notice square on top left button

wchargin
  • 15,589
  • 12
  • 71
  • 110
Pedrom
  • 378
  • 1
  • 5
  • 13
  • 1
    In the future, a print screen would be useful so we understand what the "square" you are seeing is (which in this case, I presume, is the "focus" square that Swing assigns) – CodeGuy Apr 01 '13 at 00:08

2 Answers2

2

If you know which button you want to be active, you can use

button.requestFocusInWindow();

You can also try to set the default button at the root pane, depending on the set up of your Swing elements.

rootPane.setDefaultButton(button);

And finally, there is a handy method called setFocusedPainted(false);

CodeGuy
  • 28,427
  • 76
  • 200
  • 317
2

You may want to set one button as the default button for the toolbar this way:

yourToolBar.getRootPane().setDefaultButton(okButton);

I often use the setDefaultButton method within Dialog boxes so the user can select the default button by pressing [Enter].

Thorn
  • 4,015
  • 4
  • 23
  • 42