Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Set Default Focus to a JButton...

 
claude jones
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Problem:
I have a simple program that creates two JButton's within a JPanel. When the application starts up, I would like to set the default focus to the second JButton.
It seems like the default focus is set to the first component that is added to the JPanel. I have tried "button2.requestFocus()", but the focus stay on the "button1".
Below is my test code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class TestSwingCode extends JFrame implements FocusListener {
/**
* Invoked when a component gains the keyboard focus.
*/
public void focusGained(FocusEvent e) {
JButton button = (JButton)e.getSource();
button.setBorder(new BevelBorder(BevelBorder.LOWERED));
button.setText("Selected");
}
/**
* Invoked when a component loses the keyboard focus.
*/
public void focusLost(FocusEvent e) {
JButton button = (JButton)e.getSource();
button.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
button.setText("Not Selected");
}
public TestSwingCode() {
super("Test Swing Code");
JButton button = new JButton("Simple Button");
//button.setFocusPainted(false);
//button.addFocusListener(this);
JButton button2 = new JButton("Simple Button 2");
button2.requestFocus();
//button2.setFocusPainted(false);
//button2.addFocusListener(this);
this.setSize(400, 200);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(button);
panel.add(button2);

this.getContentPane().add(panel);
this.addWindowListener(new BasicWindowMonitor());
}
public static void main(String[] args) {
TestSwingCode code = new TestSwingCode();
code.setVisible(true);
}
}
Thanks,
<cj>
 
Kent Farnsworth
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can set the default button using the following.
getRootPane().setDefaultButton(button1);
Kent
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic