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

Adding multiple items to an action listener

我想知道是否有人可以为此指出正确的方向。我有这个简单的计算器,用户在其中输入两个数字,然后必须 select 从下拉菜单中执行操作(+、-、*、*)。

在他们 select 一个选项之后,它给了他们一个答案,但我试图添加一个复选框以允许在选中该框时将结果显示为浮点数。我对如何让 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)); 
    } 
  }
}

转换错误是因为 event.getSource() 会根据触发事件的对象而变化。您可以查看事件的来源和流程:

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

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

您可以通过其他方式解决该问题,您希望复选框影响现有计算,还是仅影响新计算?如果只是一个新的计算你不需要复选框上的动作监听器,你可以在计算时查看它是否被选中:

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

我建议您在 Calculator2 class 中保留对 JCheckBox 的引用。所以类似于

public class Calculator implements ActionListener {
     ...
     JComboBox mathList = ...
     JCheckBox useFloatCheckBox = ...
     ...
}

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

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

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