我想使用文本字段和单选按钮制作一个简单的计算器。我已经有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));
}
});
答案 0 :(得分:2)
您可以将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));
}