gpt4 book ai didi

java - 为什么不调用 componentShown()?

转载 作者:搜寻专家 更新时间:2023-11-01 01:55:07 24 4
gpt4 key购买 nike

我有一个 CardDetailsPanel 类,它包含几个 JLabelJTextField。此类包含在 AddCardsPanel 中,初始化如下:

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

我还有一个包含说明的 JLabel。我想在 CardDetailsPanel 首次出现时以及焦点更改到每个 JTextField 时更新此标签。我找到了适用于后者的 addFocusListener() 方法。但是,我的 compenentShown() 方法不适用于前者:

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

(好吧,我知道这很丑。它是由 NetBeans 生成的。)

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

(是的,这更丑陋。我稍后会处理链式 getParent() 调用。我还想在这里做其他事情。)

那么为什么我的监听器没有被调用?我如何编写一个监听器,当我的 CardDetailsPanel 出现在屏幕上时执行某些操作?

最佳答案

使用 AncestorListenerdialog focus 中所述.

When a JDialog (or JFrame 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 the requestFocusInWindow() 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 the pack() or setVisible(true) methods on the JDialog.

这就是祖先监听器派上用场的地方。对于模态对话框中的组件,一旦组件变得可见并且实现并可聚焦,它就会被触发。

编辑:上述注释适用于任何 Swing 容器中的组件,包括 JFrame 和 JPanel

关于java - 为什么不调用 componentShown()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11962804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com