I have a CardDetailsPanel
class which contains several JLabel
s and JTextField
s. This class in contained in a AddCardsPanel
and is initialized as follows:
cardDetailsPanel = new CardDetailsPanel(true);
add(cardDetailsPanel, java.awt.BorderLayout.CENTER);
I also have a JLabel
that contains instructions. I want to update this label when the CardDetailsPanel
first appears and when focus changes to each JTextField
. I have found the addFocusListener()
method that will work for the later. However, my compenentShown()
method isn't working for the former:
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
(Okay, I know this is ugly. It was generated by NetBeans.)
private void formComponentShown(java.awt.event.ComponentEvent evt) {
this.frame = (BaseballFrame) this.getParent().getParent().getParent().getParent().getParent().getParent();
}
(Yah, this is even uglier. I'll deal with the chained getParent()
calls later. I want to do other things here as well.)
So why doesn't my listener get called? And how do I write a listener that will perform some actions whenever my CardDetailsPanel
appears on the screen?
componentResized. Invoked when the component's size changes.
A GUI in Java program is made up of on-screen components, events that those components generate, and listeners that respond to events when they occur.
Which of these events is generated when the size of an event is changed? Explanation: A ComponentEvent is generated when the size, position or visibility of a component is changed.
Use an AncestorListener
as described in dialog focus.
When a
JDialog
(orJFrame
for that matter) is made visible, focus is placed on the first focusable component by default. There may be times when you want to change this behaviour. The obvious solution would be to invoke therequestFocusInWindow()
method on the component you wish to receive focus. The problem is that this doesn’t work all the time....
The problem is .. a component can’t request focus unless it has been added to a “realized” dialog. A realized dialog basically means that the Swing
JDialog
has been added to a peer component that represents a dialog on the underlying OS. This occurs when you invoke thepack()
orsetVisible(true)
methods on theJDialog
.
And that is where the ancestor listener comes in handy. For a component in a modal dialog, it will be fired once the component becomes visible, and is realized & focusable.
Edit:
The above comment applies to components in any Swing container, including JFrame and JPanel
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With