Sup*_*tar 1 java inheritance swing composition actionlistener
我为我的节目制作了一个小组.它仅由RadioButtons组成.当选择radiobutton时,我想在其他代码中设置一个布尔值.此面板将用作更大面板或框架的组件,该面板或框架还应能够收听此面板内发生的事件.
那么,我应该选择以下哪个选项来收听事件 -
1 -
RadioButtonPanel extends JPanel implements ActionListener{
public void actionPerformed(ActionEvent e){}
//code to add the action listener to the radio buttons
oneRadioButton.addActionListener(this);
}
Run Code Online (Sandbox Code Playgroud)
2 -
RadioButtonPanel extends JPanel{
class InnerStrength implements ActionListener{
public void actionPerformed(ActionEvent e){}
}
//code to add the action listener to the radio buttons
oneRadioButton.addActionListener(Anonymous InnerStrength)
}
Run Code Online (Sandbox Code Playgroud)
3 - 我没想到的任何其他方式吗?
选项3. 如果您可以通过使用它来达到目标,请不要扩展 JPanel :-)
所有JSomething都具有内置功能,旨在按原样使用.JPanel的内置功能是通用容器的功能.正如您所做的那样是添加子项,不需要扩展 - 使用侦听器配置子项可以在...配置代码中完成.
如果扩展确实增加了功能(对于可能正在实现自定义背景绘制的JPanel),一般规则 - 对于表现良好的OO公民 - 始终不会暴露不适合公共使用的公共API:因此,变体1是不是一种选择.