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.


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


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();

      //your code goes here
      class ButtonListener implements ActionListener
		  public void actionPerformed(ActionEvent e)

	  ActionListener listener = new ButtonListener();

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

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

I think is something like:

lable.setText( roachPopulation.getPopulation() );
This article has been dead for over six months. Start a new discussion instead.