2016-05-01 272 views
1

這些按鈕似乎只是在我的程序中繁殖而不會分裂。我不知道是什麼導致了這一點,但任何建議將不勝感激。Java按鈕不能按預期工作

//View the buttom to be pushed 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public class MultDivide extends JFrame 
{ 

    private static final int FRAME_WIDTH = 300; 
    private static final int FRAME_HEIGHT = 100; 
    private double value; 
    private JButton multbutton; 
    private JButton divbutton; 
    private JLabel label; 

    public MultDivide() 
    { 
     super("I Multiply and Divide"); 

     //get content pane and sets its layout 
     Color background = new Color(100,100,0); 
     Container contain = getContentPane(); 
     contain.setLayout(new FlowLayout()); 
     contain.setBackground(background); 



     //create multiple button 
     multbutton = new JButton("x5 "); 
     contain.add(multbutton); 

     //create divide button 
     divbutton = new JButton("/5"); 
     contain.add(divbutton); 

     //initialize the value to 50 
     value = 50; 

     // create a label to display value 
     label = new JLabel("Value: " + Double.toString(value)); 
     contain.add(label); 

     //creates listener and executes desired result 
     ButtonListener listener = new ButtonListener(); 
     multbutton.addActionListener(listener); 
     divbutton.addActionListener(listener); 

     setSize(FRAME_WIDTH, FRAME_HEIGHT); 
     setVisible(true); 

    } 
    privateclass ButtonListener implements ActionListener 
    { 
     //handle button event 
     public void actionPerformed(ActionEvent mult) 
     { 
      //updates counter when the button is pushed 
      if(divbutton.isSelected()) 
      { 
       value = value/5.0; 
       label.setText("Value: " + Double.toString(value)); 
      } 
      else 
      { 


        value = value* 5.0; 
        label.setText("Value: " + Double.toString(value)); 

      } 

     } 



    } 
} 

回答

3

你檢查​​和只適用於JToggleButtons和它的孩子,包括一個JRadioButton和JCheckBox的。取而代之的是,獲取ActionEvent的源代碼並檢查按下了哪個按鈕。請在ActionEvent參數上調用getSource()來執行此操作。

例如,

private class ButtonListener implements ActionListener { 
    public void actionPerformed(ActionEvent mult) { 
     JButton sourceBtn = (JButton) mult.getSource(); 
     if(sourceBtn == divbutton) { 
      value = value/5.0; 
      label.setText("Value: " + Double.toString(value)); 
     } else { 
      value = value* 5.0; 
      label.setText("Value: " + Double.toString(value)); 
     } 
    } 
} 
+0

@AnaviLucus解。 +1 – DarkV1