问题
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