繁体   English   中英

Java按钮无法正常工作

[英]Java Buttons not working as intended

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

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

            }

        }



    }
}

你正在检查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));
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM