File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Set Default Focus to a JButton... " Watch "Set Default Focus to a JButton... " New topic
Author

Set Default Focus to a JButton...

claude jones
Greenhorn

Joined: Dec 14, 2001
Posts: 24
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

Joined: May 31, 2000
Posts: 7
You can set the default button using the following.
getRootPane().setDefaultButton(button1);
Kent
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Set Default Focus to a JButton...
 
Similar Threads
Help with a simple gui
update the JVM from 1.5 to 1.6, JDialog background cant paint
validate revalidate !!
JTabbedPane with Keyevents
Frame.dispose() - does this get rid of the frame in memory too?