- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个 CardDetailsPanel
类,它包含几个 JLabel
和 JTextField
。此类包含在 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
出现在屏幕上时执行某些操作?
最佳答案
使用 AncestorListener
如 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
.
这就是祖先监听器派上用场的地方。对于模态对话框中的组件,一旦组件变得可见并且实现并可聚焦,它就会被触发。
编辑:上述注释适用于任何 Swing 容器中的组件,包括 JFrame 和 JPanel
。
关于java - 为什么不调用 componentShown()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11962804/
我有一个 CardDetailsPanel 类,它包含几个 JLabel 和 JTextField。此类包含在 AddCardsPanel 中,初始化如下: cardDetailsPanel
我想在显示 WorldPanel 时获取 (Graphics g)。感谢 stackoverflow,我看到了应该在哪里使用 getGraphics 方法 (ComponentListener.com
为什么这段代码从不打印“Hello2”? public class Test4 { public static void main(String[] args) { JFram
如果发生 componentShown/componentHidden 事件,我想得到通知。我使用 ComponentListener,但效果不如我需要。我在官方 Swing 教程中找到了这些信息:
我想在上一帧中选择一个特定的 RadioButton 时显示一个 JLabel 和一个 JComboBox ,否则它应该被隐藏。即使当我在该类中实现 ComponentListener 时,他的抽象方
我是一名优秀的程序员,十分优秀!