Java-Actionlistener:从父级获取组件 [英] Java - Actionlistener: Get components from parent
问题描述
到目前为止,我发现激活动作事件时获取其他组件信息的唯一方法是:
((Swing Component)ActionEvent.getSource())。getParent()。getComponent(---)。method();
虽然它起作用了,但并不实用或难以理解,更何况如果我在父组件中移动了这些组件。
那么解决这个问题的最佳方法是什么?
让监听器成为一个内在的东西吗?
类,并直接访问该组件:
私有JLabel标签;
私人JButton按钮;
MyPanel(){
...
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
label.setText( clicked clicked);
}
}
}
http://docs.oracle.com /javase/tutorial/uiswing/events/intro.html
内部类主要是出于特定原因而发明的。
The only way I found so far to get other components' info when an actionevent is activated is by doing the following:
((Swing Component)ActionEvent.getSource()).getParent().getComponent(---).method();
and while it work it's not that practical or readable, not to mention would most likely stop working properly if I moved around the components in the parent component.
So what is the best way to go about this? Should I even use an actionlistener to begin with or are there better classes/design for this purpose?
Make the listener an inner class, and access the component directly:
private JLabel label;
private JButton button;
MyPanel() {
...
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("button clicked");
}
}
}
http://docs.oracle.com/javase/tutorial/uiswing/events/intro.html
Inner classes were invented mainly for that specific reason.
这篇关于Java-Actionlistener:从父级获取组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!