一起使用Calc按钮和radiobutton听众

时间:2016-04-06 04:21:05

标签: java swing button radio-button listeners

我正在开发一个项目,根据通话时间和通话时间来计算通话价格。一切都有效,除了计算按钮。我不确定如何制作它,所以单击“计算”按钮时,它会查找选择了哪个单选按钮并执行相应的等式。我尝试过使用循环,但它无法正常工作。

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;


public class RateChargeGUI extends JFrame
{
private JPanel panel;  
private JLabel messageLabel; //message to the  user
private JTextField timeTextField; //user inputs time of call in minutes
private JPanel Buttons;
private JRadioButton DayTimeButton;  //declares a new radio button called DayTimeButton
private JRadioButton EveningButton; //declares a new radio button called EveningButton
private JRadioButton Off_PeakButton; //declares a new radio button called Off_PeakButton
private ButtonGroup radioButtonGroup; //places the buttons in a group
private JButton exitButton; 
private JButton calcButton;
private final int WINDOW_WIDTH = 300; //window width
private final int WINDOW_HEIGHT = 300; //window height

/**
Constructor 
*/

public RateChargeGUI ()
{
    //sets the text for the title bar
    setTitle("Call Prices");
    //sets the size of the window
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //build a panel that will be added to the frame
    buildPanel();
    buildButtons();

    //add the panel to the frame
    add(panel);
    add(Buttons, BorderLayout.SOUTH);

    //display the window
    setVisible(true);
}


//The buildPanel method adds a label, text field, and the buttons to the panel.

private void buildPanel()
{
messageLabel = new JLabel(" Enter Number of minutes "); //label left of the text box telling the user what to do.
timeTextField = new JTextField(10); //text field that accepts the duration of the call
DayTimeButton = new JRadioButton("Day Time"); // radio buttons for the time of day that the call is made
EveningButton = new JRadioButton("Evening");
Off_PeakButton = new JRadioButton("Off_Peak");


//add and group the radio buttons

radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(DayTimeButton);
radioButtonGroup.add(EveningButton);
radioButtonGroup.add(Off_PeakButton);

//action listeners for the radio buttons that make it possible to select one of them
//DayTimeButton.addActionListener(new RadioButtonListener ());
//EveningButton.addActionListener(new RadioButtonListener ());
//Off_PeakButton.addActionListener(new RadioButtonListener ());

//create a panel and add the components to it. such as the label telling the user to enter the number of minutes
//or the radio buttons
panel = new JPanel();
panel.add(messageLabel);
panel.add(timeTextField);
panel.add(DayTimeButton);
panel.add(EveningButton);
panel.add(Off_PeakButton);

Buttons = new JPanel();
add(Buttons, BorderLayout.SOUTH);
}
private void buildButtons()
{
    exitButton = new JButton("Exit");
    calcButton = new JButton("Calculate");

    exitButton.addActionListener(new ExitButtonListener ());
    calcButton.addActionListener(new CalcButtonListener ());

    Buttons.add(calcButton);
    Buttons.add(exitButton);
}
/**
Private inner class that handles the event when the user clicks one of the radio buttons.
*/

private class CalcButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String input; //holds user input
        double result = 0.0; //holds the conversion
        input = timeTextField.getText(); //enables the text field to accept text

        //Determine which radio button was selected and perform a mathmatical equation based on which button was selected.
        //6AM-6PM
        if (e.getSource() == DayTimeButton)
        {
            result = Double.parseDouble(input) * 0.20;
        }
        //6PM-12AM
        else if (e.getSource() == EveningButton)
        {
            result = Double.parseDouble(input) * 0.12;
        }
        //12AM-6AM
        else if (e.getSource() == Off_PeakButton)
        {
            result = Double.parseDouble(input) * 0.04;
        }
        if (DaytimeButton.is
        //display the ammount that it will cost
        JOptionPane.showMessageDialog(null, " The call price is: $ " + result);
    }
}
private class ExitButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }
}
//calls the ratechargegui class. The RateChargeGUI class was build above and is now being called.
public static void main(String[] args)// stringargs[] allows the program to accept arguments.
    {
    new RateChargeGUI();
    }
}

3 个答案:

答案 0 :(得分:1)

我的代码中没有看到任何与一天中的小时数相关的按钮的addActionListener()方法。如果您希望事件处理程序工作,则每个单选按钮都必须附加一个actionListener。所以,你可以在某处做到这一点:

DayTimeButton.addActionListener(CalcButtonListener);
EveningButton.addActionListener(CalcButtonListener);
Off_PeakButton.addActionListener(CalcButtonListener);

此外,在Java中,变量名称必须是camelCase。类/接口名称可以以大写字母开头,但不能以变量开头。

如果您不需要处理单击其中一个单选按钮时发生的事件,但只需要单选按钮的状态,请尝试使用方法isSelected()。你在actionPerformed中的测试看起来像这样:

if (DaytimeButton.isSelected()) {
    // do stuff for this button
}
else if (EveningButton.isSelected()) {
    // do stuff for this button
}

答案 1 :(得分:1)

如果仅将此侦听器应用于calcButton,它始终将成为事件源。执行操作时,您必须检查选择了哪个单选按钮。

private class CalcButtonListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
    String input; //holds user input
    double result = 0.0; //holds the conversion
    input = timeTextField.getText(); //enables the text field to accept text

    // Determine which radio button was selected and perform a mathmatical equation based on which button was selected.
    //6AM-6PM
    if (DayTimeButton.isSelected()) {
        result = Double.parseDouble(input) * 0.20;
    }
    //6PM-12AM
    else if (EveningButton.isSelected()) {
        result = Double.parseDouble(input) * 0.12;
    }
    //12AM-6AM
    else if (Off_PeakButton.isSelected()) {
        result = Double.parseDouble(input) * 0.04;
    }

    //display the ammount that it will cost
    JOptionPane.showMessageDialog(null, " The call price is: $ " + result);
}
}

答案 2 :(得分:1)

你不需要为此设置循环。正如其他人指示的那样,你可以使用

ArrayList<User> users; // already contains info
private String userName;
private String pass;
private EditText userText;
private EditText passText;
private String inputUser;
private String inputPass;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
users = new ArrayList<>();
  for(User user: users){
        userName = user.getName();
        pass = user.getPassword()'
    }
    // EditText where user enters the username
userText = (EditText) findViewById(R.id.username);
// EditText where user enters the password
passText = (EditText) findViewById(R.id.password);
}
public void login(View view){ 
    inputPass = passText.getText().toString(); //password string
    inputUser = userText.getText().toString(); //username string


    if (inputPass.equals(pass) && (inputUser.equals(userName))) {
        Toast toast = Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG);
        toast.show();
        intent = new Intent(MainActivity.this, EnteredPage.class);
        startActivity(intent);
        break;
    }
    if (i == users.size() - 1) { //if this is the last User object         

            Toast toast = Toast.makeText(getApplicationContext(), "User does not exist!", Toast.LENGTH_LONG);
            toast.show();
    }
}
}
检查单选按钮选择时的

方法。

注意 但请注意这些。

  1. 每当您期望来自用户的输入时,在调用逻辑内的方法之前都要进行文本字段验证。现在,对于您的实例,您应该在单击Caculate按钮时立即检查输入有效性(空输入,字母输入等)。
  2. 使用double时,输出可能有很多小数位。因此,在将输出显示给您的用途之前,最好先对其进行格式化。
  3. 遵循java命名约定。使用&#34; eveningButton&#34;,&#34; dayTimeButton&#34;变量为@ Daniel.Schroeder强调。同时为组件使用有意义的变量。对于一个实例,你可以使用&#34; dayTimeRadioBtn&#34;所以你知道以后这是关于你的单选按钮而不是按钮。