tags:

views:

62

answers:

1

Hi,

given the following code:

public class DialogTest implements ActionListener {
  public static void main(String[] args) {DialogTest g = new DialogTest();}

  public DialogTest() {
    JButton b1 = new JButton("Button A");
    b1.addActionListener(this);
    JDialog d = new JDialog();
    d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    JPanel p = new JPanel();
    p.add(b1);
    d.add(p);
    d.getRootPane().setDefaultButton(b1);
    d.pack();
    d.setVisible(true);
    d.dispose();
    d.pack();
    d.setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {System.out.println("hello");}
}

Shouldn't pressing the Enter key write something to the console? According to the docs (http://java.sun.com/javase/7/docs/api/java/awt/Window.html#dispose()):

The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed

Is this intended behaviour?

+1  A: 

The reason is that in JButton.removeNotify (which seems to be called at dispose) the DefaultButton is reset:

Overrides JComponent.removeNotify to check if this button is currently set as the default button on the RootPane, and if so, sets the RootPane's default button to null to ensure the RootPane doesn't hold onto an invalid button reference.


public void removeNotify() {
    JRootPane root = SwingUtilities.getRootPane(this);
    if (root != null && root.getDefaultButton() == this) {
        root.setDefaultButton(null);
    }
    super.removeNotify();
}
Peter Lang
Thanks, that is the explanation. Though I still think the docs should be corrected then or at least be made more specific.
DaDaDom
@DaDaDom: Agreed, the documentation is not complete at this point, and there may be other things too that will not work after a `dispose`. Anyway, `setVisible` is what you really want (as you already know).
Peter Lang