Question: Modify the class so that when you click on the Counter label it changes to Decrementer and changes the text of the button to Decrement

Modify the class so that when you click on the Counter label it changes to Decrementer and changes the text of the button to Decrement as well. If you click on the label again, it will change back to Counter. The button in decrement mode will subtract from the count, rather than add. To accomplish this you will want the label to have a MouseListener.

import java.awt.*; // Using AWT layouts

import java.awt.event.*; // Using AWT event classes and listener interfaces

import javax.swing.*; // Using Swing components and containers

// A Swing GUI application inherits from top-level container javax.swing.JFrame

public class GUICounter extends JFrame { // JFrame instead of Frame

private JTextField tfCount;

private JTextField tfWrite;

private JButton btnCount;

private int count = 0;

// Constructor to setup the GUI components and event handlers

public GUICounter() {

// Retrieve the content-pane of the top-level container JFrame

// All operations done on the content-pane

Container cp = getContentPane();

cp.setLayout(new GridLayout(3,3)); // The content-pane sets its layout

cp.add(new JLabel("Counter"));

tfCount = new JTextField("0");

tfCount.setEditable(false);

cp.add(tfCount);

cp.add(new JLabel("Type Number: "));

tfWrite = new JTextField("");

tfWrite.setEditable(true);

cp.add(tfWrite);

btnCount = new JButton("Count");

cp.add(btnCount);

// Allocate an anonymous instance that implements ActionListener as ActionEvent listener

btnCount.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {

count++;

tfCount.setText(count + "");

}

});

tfWrite.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt2){

count = Integer.parseInt(tfWrite.getText());

tfCount.setText(count + "");

tfWrite.setText("");

}

});

}

// The entry main() method

public static void main(String[] args) {

GUICounter counter = new GUICounter();

counter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window button clicked

counter.setTitle("GUI Counter"); // "super" JFrame sets title

counter.setSize(300, 100); // "super" JFrame sets initial size

counter.setVisible(true); // "super" JFrame shows

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!