This week's book giveaway is in the JDBC forum.
We're giving away four copies of Make it so: Java DB Connections & Transactions and have Marcho Behler on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Set Default Focus to a JButton... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Set Default Focus to a JButton... " Watch "Set Default Focus to a JButton... " New topic

Set Default Focus to a JButton...

claude jones

Joined: Dec 14, 2001
Posts: 24
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));
* 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");
JButton button2 = new JButton("Simple Button 2");
this.setSize(400, 200);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

this.addWindowListener(new BasicWindowMonitor());
public static void main(String[] args) {
TestSwingCode code = new TestSwingCode();
Kent Farnsworth

Joined: May 31, 2000
Posts: 7
You can set the default button using the following.
Consider Paul's rocket mass heater.
subject: Set Default Focus to a JButton...
It's not a secret anymore!