简体   繁体   中英

Incrementing/Decrementing using JPanel and JButton

I have been trying to solve this for quite some time now and I can't figure out what am I doing wrong here

Here is the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PushCounterPanelMath extends JPanel
{
    private int count;
    private JButton inc;
    private JButton dec;
    private JLabel label;

    public PushCounterPanelMath()
    {
        count = 0;
        inc = new JButton("Increment");
        dec = new JButton("Decrement");
        label = new JLabel();
        inc.addActionListener(new ButtonListener());
        dec.addActionListener(new ButtonListener());
        add(inc);
        add(dec);
        add(label);
        setBackground(Color.cyan);
        setPreferredSize(new Dimension(300, 40));
    }

    private class ButtonListener implements ActionListener
    {
        
        public void actionPerformed(ActionEvent event)
        {
            
            count++;
            label.setText("Value: " + count);
            if(event.equals(dec))
                count--;
            label.setText("Value "  + count);
        }
    }
}

I am trying to increment and decrement value using two buttons, but for some reason it only increments it whether I press "Increment" or Decrement" How can I fix this?

event.equals(dec) is never going to be true; an ActionEvent is never equals to a JButton. But you can use event.getSource();

        if(event.getSource().equals(dec))
            count--;
        else count++;
        label.setText("Value "  + count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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