2017-12-04 6 views
0

누군가 내가 올바른 방향으로 나를 가리킬 수 있는지 궁금합니다. 나는 사용자가 두 개의 숫자를 입력 한 다음 드롭 다운 메뉴에서 동작 (+, -, *, *)을 선택해야하는이 간단한 계산기를 가지고 있습니다.액션 리스너에 여러 항목 추가하기

옵션을 선택하면 대답이 표시되지만 확인란을 선택하면 결과가 플로트로 표시되도록 확인란을 추가하려고했습니다. 나는 actionPreformedJCheckBoxJComboBox 모두 처리하는 방법에 대해 혼란스러워했습니다. 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 
} 
관련 문제