您每次引發一個單選按鈕事件時都會覆蓋textarea。 嘗試使用JTextAre.append()而不是setText。
在任何情況下,您都必須記住ActionListener中的單選按鈕組的任何一種狀態,以達到預期的行爲。
更新由於評論:
這是不完全正確的。我沒有'檢查它。但它顯示了主要方面。 起初,它更好地實現了一個具體的類的監聽器接口,而不是 要通過它作爲anonoumys類型。在這種情況下,RadioButton類實現actionListener方法。現在您可以將任何類型的參數或對象引用傳遞給偵聽器類。你可以在你的偵聽器方法中使用它。
進一步看看我如何獲得事件的來源。這是通過
JRadioButton source = (JRadioButton)e.getSource();
如果您分配一個名稱或ID你可以檢查該名稱,並在適當的方式作出反應 的單選按鈕來完成。
在這裏,示例代碼:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class RadioButton implements ActionListener {
boolean group1Clicked = false;
boolean group2Clicked = false;
JRadioButton rb1 = new JRadioButton();
...
JTextArea text = new JTextArea();
public RadioButton() {
rb1.addActionListener(this);
rb2.addActionListener(this);
rb3.addActionListener(this);
ButtonGroup group = new ButtonGroup();
rb1.setName("rb1");
rb2.setName("rb2");
// cpu group
rb4.addActionListener(this);
rb5.addActionListener(this);
rb6.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
JRadioButton source = (JRadioButton)e.getSource();
if (source.getName().equals("rb1") ||
source.getName().equals("rb2") ||
source.getName().equals("rb3")) {
//Changing the state
if (group1Clicked) {
group2Clicked = false;
} else {
group1Clicked = true;
}
}
if (source.getName().equals("rb4") ||
source.getName().equals("rb5") ||
source.getName().equals("rb6")) {
//Changing the state
if (group2Clicked) {
group1Clicked = false;
} else {
group2Clicked = true;
}
}
if (group1Clicked==false || group2Clicked ==false) {
text.clear();
} else {
text.append(e.getActionCommand());
}
}
};
該組的值或從組中選擇的「JRadioButton」的值? – Sage