Adding ActionListener to a Panel - Panel implements ActionListener vs Panel HAS A ActionListener

╄→尐↘猪︶ㄣ 提交于 2019-12-01 10:28:46

问题


I made a panel for my program. It consists of RadioButtons only. When a radiobutton is selected, I want to set a boolean in other code. This panel will be used as a component of a bigger panel or frame which should also be able to listen to the events happening inside this panel.

So, which of the following options should I choose for listening to events -

1 -

RadioButtonPanel extends JPanel implements ActionListener{

  public void actionPerformed(ActionEvent e){}
  //code to add the action listener to the radio buttons 
  oneRadioButton.addActionListener(this);   
}

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) 

}

3 - Any other way to do it that I did not think of ?


回答1:


Add a add/RemoveActionListener method to your panel. Use these as proxy to you radio button and register the ActionListener directly to it

Alternatively, you could provide a isSelected method which returns the state of the radio button.




回答2:


Option 3. Don't extend JPanel at all if you can reach the goal by using it :-)

All JSomething have built-in functionality that's designed to be used as-is. The built-in functionality of a JPanel is that of a general purpose container. As all you are doing is to add children, there's no need to extend - configuring the children with listeners can be done in ... configuration code.

If extending indeed adds functionality (for a JPanel that might be implementing custom background painting), the general rule is - as always for a well-behaved OO citizen - to never expose public api that's not intended for public usage: consequently, variant 1 is not an option.



来源:https://stackoverflow.com/questions/15739710/adding-actionlistener-to-a-panel-panel-implements-actionlistener-vs-panel-has

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