problem getting rootPane
I've created a very simple app to play around with the FocusTraversalPolicy. The app consists of a JFrame that has 2 JPanels that contain a few text fields. In the JFrame, I added the enter key to the FORWARD_TRAVERSAL_KEYS set in the KeyboardManager. That worked fine and I was able to change the traversal order easily.
Now I want to make the last text field on one of the the Jpanels handle the enter key differently. I want it to fire off a dialog.
The problem I'm having is when I try to get the rootPane. Everything I've tried returns null. Below is the simple JPanel class. In it are 3 different methods I've tried to get the rootPane and all of them return null.
What am I doing wrong? Is there a best practices example that I can follow?
public class P1 extends JPanel {
private JTextField jTextField1 = new JTextField();
private JTextField jTextField2 = new JTextField();
private JTextField jTextField3 = new JTextField();
private JTextField jTextField4 = new JTextField();
public P1() {
init();
}
public void init() {
setBorder( BorderFactory.createEtchedBorder() );
this.add( jTextField1, null );
this.add( jTextField2, null );
this.add( jTextField3, null );
this.add( jTextField4, null );
jTextField1.setText( "Field1" );
jTextField2.setText( "Field2" );
jTextField3.setText( "Field3" );
jTextField4.setText( "Field4" );
MyFocusTraversalPolicy policy = ( MyFocusTraversalPolicy ) KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalPolicy();
policy.addComponent( jTextField1 );
policy.addComponent( jTextField2 );
policy.addComponent( jTextField3 );
policy.addComponent( jTextField4 );
initEventHandlers();
}
private void initEventHandlers() {
// define ids for actions
Object dlg = new Object();
Action dialogAction =
new AbstractAction() {
public void actionPerformed( ActionEvent e ) {
JOptionPane.showMessageDialog( getParent(), "This is a test message." );
}
};
// ********** PROBLEMS START HERE **********
//JComponent rootPane = getRootPane();
//JComponent rootPane = ( JComponent ) SwingUtilities.getRoot( this );
JComponent rootPane = Application1.getFrame().getRootPane();
// Here's where it breaks because rootPane is null
ActionMap am = rootPane.getActionMap();
InputMap im = rootPane.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// add Actions to ActionMap
am.put( dlg, dialogAction );
// add KeyStrokes to InputMap
im.put( KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 ), dlg );
// add Actions to buttons
jTextField4.addActionListener( dialogAction );
}
}

