I started coding in Java recently. I wanted to code a Window which contains:
- 1 Frame
- 1 Container
- 2 JPanel objects (To make sure to not confuse Panels, Container and Frame's object)
- 1 Scroll's object
- 1 JTextArea and 1 JTextField
- 1 JButtonGroup with 3 JRadioButton associated
Its purpose were like a one-man chat. Write in the TextField, submit button and print it in the TextArea appending to any previous message. Next step, I named 3 Radio Buttons "User 1", "User 2" and "User 3" On their selection they will print: user_x.GetName+(String)message;
My first try was an ActionListener. (This is a prototype):
ActionListener updateUserTalking = new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
JTextField tf = textField; //New message
JTextArea ta = textArea; //Previous message to track an history
String str = ta.getText()+"Radio button changed"; //This should print "User_x"
str = str+tf.setText(str+System.lineSeparator());
}
};
My second try was an ItemListener. (This is a prototype)
public void itemStateChanged(ItemEvent e) {
updateSystemMessage();
This updateSystemMessage() call this method:
ItemListener updateSystemMessage = new ItemListener(){
public void itemStateChanged(ItemEvent e) {
JTextField tf = textField; //New message
JTextArea ta = textArea; //Previous message to track an history
String str = ta.getText()+"RadioButton changed"; //This should print "User_x"
str = str+tf.setText(str+System.lineSeparator());
}
};
The latest print a double message. Because the same method is shared. So when selection is changed there are two commutation so this method will be called twice. Here comes my question:
I know I can make one method for each JRadioButton istantiated. I was guessing if there was a way to make an unique method viable. Where the JRadioButton selected give its name as parameter to the ActionListener or ItemListener.
I already tried something like this:
private void updateSystemMessage() {
JRadioButton jrb = (JRadioButton)this.bGroup.getSelection();
this.system =jrb.getText();
}
But it doesn't work because bGroup.getSelection() return a ButtonModel that can't be casted as (JRadioButton). Therefore is there a way like this? Or I have to code one method for each JRadioButton (Who basically do the same thing)?