I’m working on a simple java GUI program with two buttons and a displayed variable (num). The buttons are named ‘increment’ and ‘decrement’, and their functions are to increment or decrement the displayed variable num, which is initially set to 50.
Although the program will compile, the increment and decrement buttons increase/decrease the value of num by two instead of one. I’ve tried things such as changing the code ‘num++’ to ‘num = num + 1’, but this still causes the button to increment by two.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assignment_4 extends JFrame {
private int num = 50;
private JButton increment;
private JButton decrement;
private JLabel label;
private JPanel buttonPanel;
private JPanel displayPanel;
public Assignment_4() {
increment = new JButton ("Increment");
decrement = new JButton ("Decrement");
increment.addActionListener (new incListener());
decrement.addActionListener (new decListener());
increment.addActionListener (new incListener());
decrement.addActionListener (new decListener());
num = 50;
label = new JLabel ("" + num);
buttonPanel = new JPanel();
displayPanel = new JPanel();
buttonPanel.add(increment);
buttonPanel.add(decrement);
displayPanel.add(label);
setLayout(new BorderLayout());
add(buttonPanel, BorderLayout.CENTER);
add(displayPanel, BorderLayout.NORTH);
}
private class incListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
num++;
label.setText("" + num);
}
}
private class decListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
num--;
label.setText("" + num);
}
}
public static void main(String[] args) {
Assignment_4 win = new Assignment_4();
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.pack();
win.setVisible(true);
}
}
I appreciate any help you can offer.
You have attached two instances of action listeners for both, you just need one of each.