Execute the following PushCounter class and PushCounterPanel class. import javax
ID: 3706259 • Letter: E
Question
Execute the following PushCounter class and PushCounterPanel class.
import javax.swing.JFrame;
public class PushCounter
{
public static void main(String[] args)
JFrame frame = new JFrame("Push Counter");
PushCounterPanel panel = new PushCounterPanel();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PushCounterPanel extends JPanel
{
private int count;
private JButton push;
private JLabel label;
public PushCounterPanel()
count = 0;
push = new JButton("Increment");
label = new JLabel();
label.setText("Value: " + count);
push.addActionListener(new ButtonListener());
setPreferredSize(new Dimension(300, 40));
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
label.setText("Value: " + count);
}
}
1) Add another button called “Decrement”, and modify the PushCounterPanel class so that each time the Decrement button is pressed, count value is decremented.
Explanation / Answer
public class PushCounterPanel extends JPanel
{
private int count;
private JButton push,pushDec;
private JLabel label;
public PushCounterPanel()
count = 0;
push = new JButton("Increment");
push = new JButton("Decrement");
label = new JLabel();
label.setText("Value: " + count);
push.addActionListener(new ButtonListener());
pushDec.addActionListener(new ButtonListener());
setPreferredSize(new Dimension(300, 40));
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
count = count-1;
label.setText("Value: " + count);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.