Why is the component not being called?

I have a CardDetailsPanel class that contains several JLabel and JTextField s. This class is contained in the AddCardsPanel and initialized as follows:

  cardDetailsPanel = new CardDetailsPanel(true); add(cardDetailsPanel, java.awt.BorderLayout.CENTER); 

I also have a JLabel containing instructions. I want to update this label when the CardDetailsPanel first appears and when the focus changes to each JTextField . I found the addFocusListener() method that will work for a later one. However, my compenentShown() method does not work for the first:

  addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { formComponentShown(evt); } }); 

(Well, I know this is ugly. It was created by NetBeans.)

 private void formComponentShown(java.awt.event.ComponentEvent evt) { this.frame = (BaseballFrame) this.getParent().getParent().getParent().getParent().getParent().getParent(); } 

(Yes, this is even more ugly. I will deal with the chained getParent() calls later. I also want to do other things.)

So why is my listener not called? And how do I write a listener that will perform some actions when my CardDetailsPanel appears on the screen?

+4
source share
1 answer

Use AncestorListener as described in the dialog focus .

When a JDialog (or JFrame , for that matter) becomes visible, focus is placed on the first custom component by default. There may be times when you want to change this behavior. The obvious solution would be to call the requestFocusInWindow() method on the component you want to get focus on. The problem is that this does not work all the time.

...

The problem is that the component cannot request focus if it has not been added to the "implemented" dialog. The implemented dialog basically means that the Swing JDialog been added to the peer component that represents the dialog in the underlying OS. This happens when you call pack() or setVisible(true) JDialog on JDialog .

And this is where the ancestor listener comes in handy. For a component in a modal dialog box, it will be launched after the component becomes visible, and - implemented and configured.

Edit: The above comment applies to components in any Swing container, including JFrame and JPanel .

+6
source

All Articles