I'm stuck trying to figure out how to update the text field after I click on the button in the GUI. The number of roaches is supposed to be updated each time I click, but I can't seem to find the right tool for the job in the APIs.


RoachPopulation.java

public class RoachPopulation
{
   public RoachPopulation(int initialPopulation)
   {
      pop = initialPopulation;
   }
   
   public void doublePopulation()
   {
      pop = pop * 2;
   }
   
   public int getPopulation()
   {
      return pop;
   }
   
   private int pop;
}

RoachPopulationViewer.java

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
   This program displays the growth of a roach population.
*/
public class RoachPopulationViewer
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame();

      JButton button = new JButton("Double roach population!");

      final RoachPopulation roachPopulation = new RoachPopulation(2);

      // The label for displaying the results
      JLabel label = new JLabel(
            "population: " + roachPopulation.getPopulation());

      // The panel that holds the user interface components
      JPanel panel = new JPanel();
      panel.add(button);
      panel.add(label);
      frame.add(panel);

      //your code goes here
      class ButtonListener implements ActionListener
      {
		  public void actionPerformed(ActionEvent e)
		  {
			  roachPopulation.doublePopulation();
		  }
	  }

	  ActionListener listener = new ButtonListener();
	  button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

   private static final int FRAME_WIDTH = 400;
   private static final int FRAME_HEIGHT = 100;
}

I think is something like:

roachPopulation.doublePopulation();
lable.setText( roachPopulation.getPopulation() );
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.