- Joined
- Jul 19, 2017
- Messages
- 13
- Reaction score
- 2
I'm trying to make a GUI that will increase a number when you click one button and decrease that number when you click another button. This is my code:
It compiles, but the GUI itself doesn't work. What's wrong with it? How would you create something like this and why?
Java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PushCounter
{
static JTextField textArea;
static int count = 0;
public static void main(String[] args)
{
JFrame frame = new JFrame("PushCounter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton upButton = new JButton("Up");
JButton downButton = new JButton("Down");
JTextField textArea = new JTextField(15);
JLabel label = new JLabel("Count");
upButton.addActionListener(new upButtonListener());
downButton.addActionListener(new downButtonListener());
panel.add(label);
panel.add(textArea);
panel.add(downButton);
panel.add(upButton);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.pack();
}
private static class upButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
++count;
textArea.setText(Integer.toString(count));
}
}
private static class downButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
--count;
textArea.setText(Integer.toString(count));
}
}
}
It compiles, but the GUI itself doesn't work. What's wrong with it? How would you create something like this and why?
Last edited by a moderator: