我想使用文本字段和单选按钮制作一个简单的计算器。我已经有3个文本字段和一个带有操作侦听器的“计算”按钮。但是现在我想将3个新的单选按钮进行分组,其中乘数(例如1、10和1000)互为乘积(我希望它们乘以最终结果,但我只想将JButton
用作采取行动的人单选按钮)。
代码的相关部分如下所示:
JButton btnNewButton = new JButton("calculate!");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double x, y, z, result;
x= Double.parseDouble(textField.getText());
y= Double.parseDouble(textField_1.getText());
z= Double.parseDouble(textField_2.getText());
result = x * y * z;
textField_3.setText(Double.toString(your result is));
}
});
最佳答案
您可以将JRadioButtons与ButtonGroup一起使用,例如:
final ButtonGroup group = new ButtonGroup();
final JRadioButton btn1 = new JRadioButton("1");
final JRadioButton btn10 = new JRadioButton("10");
final JRadioButton btn1000 = new JRadioButton("1000");
group.add(btn1);
group.add(btn10);
group.add(btn1000);
...
public void actionPerformed(ActionEvent arg0) {
double x, y, z, result;
x= Double.parseDouble(textField.getText());
y= Double.parseDouble(textField_1.getText());
z= Double.parseDouble(textField_2.getText());
result = x * y * z;
if (btn10.isSelected()) result *= 10;
if (btn1000.isSelected()) result *= 1000;
textField_3.setText(Double.toString(result));
}