Reputation: 9
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?
Upvotes: 0
Views: 43
Reputation: 35011
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);
Upvotes: 1