Java - Actionlistener: Get components from parent

可紊 提交于 2019-12-11 19:05:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21961778/java-actionlistener-get-components-from-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!