【发布时间】:2019-05-14 00:27:21
【问题描述】:
我最近开始使用 Java 编码。我想编写一个包含以下内容的窗口:
- 1 帧
- 1 个容器
- 2个JPanel对象(确保不会混淆Panels、Container和Frame的对象)
- 1 卷轴的对象
- 1 个 JTextArea 和 1 个 JTextField
- 1 个 JButtonGroup 与 3 个 JRadioButton 关联
它的目的就像一个人聊天。在 TextField 中写入,提交按钮并将其打印在 TextArea 中,附加到任何先前的消息。 下一步,我将 3 个单选按钮命名为“用户 1”、“用户 2”和“用户 3” 在他们的选择中,他们将打印:user_x.GetName+(String)message;
我的第一次尝试是 ActionListener。 (这是一个原型):
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());
}
};
我的第二次尝试是使用 ItemListener。 (这是一个原型)
public void itemStateChanged(ItemEvent e) {
updateSystemMessage();
这个 updateSystemMessage() 调用这个方法:
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());
}
};
最新打印一条双重消息。因为相同的方法是共享的。 So when selection is changed there are two commutation so this method will be called twice. 我的问题来了:
我知道我可以为每个已实例化的 JRadioButton 创建一种方法。我在猜测是否有办法使一种独特的方法可行。选择的 JRadioButton 将其名称作为参数提供给 ActionListener 或 ItemListener。
我已经尝试过这样的事情:
private void updateSystemMessage() {
JRadioButton jrb = (JRadioButton)this.bGroup.getSelection();
this.system =jrb.getText();
}
但它不起作用,因为 bGroup.getSelection() 返回一个无法转换为 (JRadioButton) 的 ButtonModel。因此有这样的方法吗?或者我必须为每个 JRadioButton 编写一个方法(谁基本上做同样的事情)?
【问题讨论】:
标签: java performance swing jradiobutton itemlistener