Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make default JButton in child class

 
Craig Hagerman
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I make a button the default button?


I have read that I can use

getRootPane().setDefaultButton(buttonName);


This worked in a test program where there was only one class. However in another program involving two classes I can't get it to work.


Here is a snippet from the simple working class which extended JFrame:


...
Container contentpane = getContentPane();
JPanel panel = new JPanel();
JButton doit = new JButton("Do It");
panel.add(doit);
getRootPane().setDefaultButton(quit);
...


But in the second case the JPanel component above is a different class (TestPanel.java). And here this technique results in a nullPointer exception at runtime.


...
class TestPanel extends JPanel
{ public TestPanel()
{ JButton doit = new JButton("Do It");
add(doit);
getRootPane().setDefaultButton(doit);
....


I also tried other things like:

getParent().getRootPane().setDefaultButton(doit);


thinking that that would reference the parent JFrame-extended class, but no luck. (How do you use getParent()?)


Can anyone tell me how to set up a default JButton in such a case?
Craig Hagerman
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic