2017-12-04 24 views
0

私は、誰かがこのために正しい方向に私を指すことができるのだろうかと思っていました。私はこの単純な電卓を持っています。ユーザーは2つの数字を入力し、ドロップダウンメニューからアクション(+、 - 、*、*)を選択する必要があります。アクションリスナーに複数のアイテムを追加する

オプションを選択すると、回答が得られますが、チェックボックスをオンにすると、チェックボックスをオンにすると結果がフロートとして表示されます。私は、actionPreformedをどうすればJCheckBoxJComboBoxの両方を扱うのか混乱していました。私はちょうどnewCheckBoxを追加しようとしましたが、キャストエラーの原因はJCheckBoxJComboBoxです。どのオブジェクトに応じて、event.getSource()変更がイベントを発射したので

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)); 
    } 
    } 
} 

答えて

0

はあなたへの参照を保持していることですCalculator2クラスのJCheckBox。だからではなく、event.getSource(からウィジェットへの参照を得ることのあなたのactionPerformed mehtodで、その後

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

の線に沿って何かは、)クラスの参照から直接それを得ます。だから、actionPerformedのは、この

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

ようにあなたがウィジェットをキャストを心配することなく、両方のオブジェクトに同じリスナーを使用することができます。この方法を見てしまいます。

0

キャストエラーがあります。あなたはそれに基づいてイベントとプロセスのソースを確認することができます。

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

代わりに、作成したイベントが別の場所に行くように、あなたはJCheckBoxのに異なるのActionListenerの実装を追加することができます。フラグを設定するか、別のメソッドを呼び出す匿名のリスナーも機能します。

問題に近づける他の方法があります。チェックボックスを既存の計算に適用したいのですか、それとも新しいものだけにするのでしょうか?あなたがチェックボックスにアクションリスナーを必要としない新たな計算だけであれば、あなたは計算を行うときに、それがチェックされているかどうかを調べることができます:私が推薦する何

if (myCheckbox.isSelected()) { 
    // do float calculation... 
} else { 
    // do int calculation 
} 
関連する問題