将多个项添加到动作侦听器

时间:2017-12-04 00:37:50

标签: java jcombobox jcheckbox

我想知道有人可以指出我正确的方向。我有这个简单的计算器,用户输入两个数字,然后从下拉菜单中选择一个动作(+, - ,*,*)。

选择一个选项后,它会给出答案,但我试图添加一个复选框,以便在选中该复选框时将结果显示为浮点数。我对如何让actionPreformed处理JCheckBoxJComboBox感到困惑。我尝试添加newCheckBox,但这会导致JCheckBoxJComboBox之间的投射错误。

public class Calculator2 implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JPanel xpanel;
String[] mathStrings = { "Multiply", "Subtraction", "Division", "Addition"};  //Options for drop down menu
JComboBox mathList = new JComboBox(mathStrings);                              //Create drop down menu and fill it

public Calculator2() {      
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    xpanel = new JPanel();
    xpanel.setLayout(new GridLayout(3,2));

    xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
    xfield = new JTextField("0", 5);
    xpanel.add(xfield);

    xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
    yfield = new JTextField("0", 5);
    xpanel.add(yfield);

    xpanel.add(new JLabel("Result:"));
    result = new JLabel("0");
    xpanel.add(result);
    frame.add(xpanel, BorderLayout.NORTH);


    JPanel southPanel = new JPanel();                      //New panel for the drop down menu
    southPanel.setBorder(BorderFactory.createEtchedBorder());

    JCheckBox newCheckBox = new JCheckBox("Show My Answer In Floating Point Format");  //Check box to allow user to view answer in floating point
    southPanel.add(newCheckBox);
 //newCheckBox.addActionListener(this);

    southPanel.add(mathList);
    mathList.addActionListener(this);

    frame.add(southPanel , BorderLayout.SOUTH);

    Font thisFont = result.getFont();                                       //Get current font
    result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD));   //Make the result bold
    result.setForeground(Color.red);                                        //Male the result answer red in color
    result.setBackground(Color.yellow);                                     //Make result background yellow
    result.setOpaque(true);

    frame.pack();
    frame.setVisible(true);
  }

@Override
public void actionPerformed(ActionEvent event) { 
    String xText = xfield.getText();                        //Get the JLabel fiels and set them to strings
    String yText = yfield.getText();

    int xVal;
    int yVal;

    try {
        xVal = Integer.parseInt(xText);                     //Set global var xVal to incoming string
        yVal = Integer.parseInt(yText);                     //Set global var yVal to incoming string
    }
    catch (NumberFormatException e) {                       //xVal or yVal werent valid integers, print message and don't continue
        result.setText("ERROR");
        //clear();
        return ;
    } 

    JComboBox comboSource = (JComboBox)event.getSource();   //Get the item picked from the drop down menu
    String selectedItem = (String)comboSource.getSelectedItem();

    if(selectedItem.equalsIgnoreCase("Multiply")) {                  //multiply selected
        result.setText(Integer.toString(xVal*yVal)); 
    }
    else if(selectedItem.equalsIgnoreCase("Division")) {            //division selected
        if(yVal == 0) {                                   //Is the yVal (bottom number) 0?
            result.setForeground(Color.red);              //Yes it is, print message
            result.setText("CAN'T DIVIDE BY ZERO!");
            //clear();
        }
        else          
            result.setText(Integer.toString(xVal/yVal));  //No it's not, do the math
    }
    else if(selectedItem.equalsIgnoreCase("Subtraction")) {        //subtraction selected                                         
        result.setText(Integer.toString(xVal-yVal)); 
    }
    else if(selectedItem.equalsIgnoreCase("Addition")) {           //addition selected
        result.setText(Integer.toString(xVal+yVal)); 
    } 
  }
}

2 个答案:

答案 0 :(得分:0)

转换错误是因为event.getSource()根据触发事件的对象而更改。您可以根据以下内容检查事件和流程的来源:

if (event.getSource() instanceof JCheckBox) { ... act accordingly ... } else 

相反,您可以向JCheckBox添加不同的ActionListener实现,以便它创建的事件转到另一个地方。设置标志或调用不同方法的匿名侦听器也可以工作。

还有其他方法可以解决问题,您是希望复选框影响现有计算还是仅影响新计算?如果只有一个新的计算,你不需要复选框上的动作监听器,你可以找出在进行计算时是否检查它:

if (myCheckbox.isSelected()) {
    // do float calculation...
} else {
    // do int calculation
}

答案 1 :(得分:0)

我建议您在Calculator2类中保留对JCheckBox的引用。

之类的东西
public class Calculator implements ActionListener {
     ...
     JComboBox mathList = ...
     JCheckBox useFloatCheckBox = ...
     ...
}

然后在你的actionPerformed mehtod中,而不是从event.getSource()获取对小部件的引用,直接从类中的引用获取它。所以actionPerformed看起来像这样

public void actionPerformed(ActionEvent e) {
     String operator = (String)this.mathList.getSelected();
     boolean useFloat = this.useFloatCheckBox.isSelected();    
     ...
}

这样,您可以在两个对象上使用相同的侦听器,而无需担心转换窗口小部件。