Java按钮无法正常工作

时间:2016-05-01 19:38:30

标签: java swing user-interface

按钮似乎只是在我的程序中繁殖而不是分开。我不知道是什么导致了这一点,但任何建议都会受到高度赞赏。

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

            }

        }



    }
}

1 个答案:

答案 0 :(得分:3)

您正在检查isSelected(),这只适用于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));
        }
    }
}