Results 1 to 3 of 3
  1. #1
    eXistenZ is offline Member
    Join Date
    Mar 2011
    Posts
    7
    Rep Power
    0

    Default actionListener/Performed different classes (CS106A NameSurfer)

    Stanford CS106A online course Name Surfer Assignment6.

    Challenge / Problem: ActionListener actionPerformed() implemented in different class from addActionListener() class.

    NameSurfer graphs the popularity of names over the 20th century. Main NameSurfer class is the frame, with controls on SOUTH from BottomPanel class, and output graph on CENTER from NameSurferGraph class.

    As per assignment, the actionPerformed(e) method must be in the main class, but I want to have the JFields and JButtons in a separate class. How should I change the code so that the (event e) generated in BottomPanel class is recognized in NameSurfer class? I get a NullPointerException.

    Note that, as a switch, I comment out the different approaches tried, which includes method heading changes. System.out.println() sends to console messages whether JButton clicks and JField entries are recognized.

    Is it a requirement that actionPerformed() be in same class as addActionListener() ? Books donít make this clear enough. (Or maybe they do . . . ?)

    Thanks.

    PHP Code:
    /*
     * File: NameSurfer.java
     * ---------------------
     * When it is finished, this program will implements the viewer for
     * the baby-name database described in the assignment handout.
     */
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import acm.program.*;
    import javax.swing.*;
    
    /**
     * Main method
     */
    public class NameSurfer extends Program implements NameSurferConstants,
    		ActionListener {
    
    	/**
    	 * This method has the responsibility for reading in the data base and
    	 * initializing the interactors at the bottom of the window.
    	 */
    	public void run() {
    
    		// surfer = new NameSurfer();
    		init();
    
    		bottPanel = new BottomPanel();
    		frame.add(bottPanel, SOUTH);
    
    		grafPanel = new NameSurferGraph();
    		frame.add(grafPanel, CENTER);
    
    		frame.setVisible(true);
    	}
    
    	/**
    	 * This class is responsible for detecting when the buttons are clicked, so
    	 * you will have to define a method to respond to button actions.
    	 */
    	public void actionPerformed(ActionEvent e) {
    
    		System.out.println("mouse clicked -- main");
    		if (e.getSource() == bottPanel.nameChoice) {
    			nameText = nameChoice.getText();
    			System.out.println(("JText: " + nameText));
    		}
    		if (e.getSource() == bottPanel.buttonGraph) {
    			if (nameText.equals("")) {
    				System.out.println("Need to enter a name. ");
    			} else {
    				System.out.println("Graph: " + nameText);
    			}
    		}
    		if (e.getSource() == bottPanel.buttonClear) {
    			nameChoice.setText("");
    			System.out.println("Clear: " + nameText);
    		}
    	}
    
    	public void init() {
    
    		frame = new JFrame();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(NameSurferConstants.APPLICATION_WIDTH,
    				NameSurferConstants.APPLICATION_HEIGHT);
    		frame.setVisible(true);
    
    	}
    
    	/* Instance Variables */
    
    	private JLabel nameLabel;
    
    	private JTextField nameChoice;
    
    	private JButton buttonGraph;
    
    	private JButton buttonClear;
    
    	private String nameText = "";
    
    	public NameSurferGraph graph;
    
    	private JFrame frame;
    
    	public NameSurfer surfer;
    
    	private BottomPanel bottPanel;
    
    	private NameSurferGraph grafPanel;
    
    	public ActionListener nameSurf;
    
    }
    PHP Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    //public class BottomPanel extends JPanel implements ActionListener {
    public class BottomPanel extends JPanel {
    
    	public BottomPanel() {
    
    		createTextField();
    		createButtons();
    	}
    
    	private void createButtons() {
    
    		buttonGraph = new JButton("Graph");
    		buttonClear = new JButton("Clear");
    		add(buttonGraph);
    		add(buttonClear);
    		
    		// Which actionListener in place of (this)?? * 
    		//(surfListener), (new NameSurfer()), (surfer) ?
    		
    		buttonGraph.addActionListener(surfListener);
    		buttonClear.addActionListener(surfListener);
    		// buttonGraph.addActionListener(this);
    		// buttonClear.addActionListener(this);
    	}
    
    	private void createTextField() {
    
    		nameLabel = new JLabel("Name");
    		add(nameLabel);
    		nameChoice = new JTextField(20);
    		add(nameChoice);
    		nameChoice.addActionListener(surfListener);
    		// nameChoice.addActionListener(this);
    	}
    
    	public void actionPerformed(ActionEvent e) {
    
    		System.out.println("mouse clicked");
    		// System.out.println("e.getSource" + e.getSource()); ////////
    		if (e.getSource() == nameChoice) {
    			nameText = nameChoice.getText();
    			System.out.println(("JText: " + nameText));
    		}
    		if (e.getSource() == buttonGraph) {
    			if (nameText.equals("")) {
    				System.out.println("Need to enter a name. ");
    			} else {
    				System.out.println("Graph: " + nameText);
    			}
    		}
    		if (e.getSource() == buttonClear) {
    			nameChoice.setText("");
    			System.out.println("Clear: " + nameText);
    		}
    	}
    
    	/* Instance Variables */
    
    	private JLabel nameLabel;
    
    	public JTextField nameChoice;
    
    	public JButton buttonGraph;
    
    	public JButton buttonClear;
    
    	private String nameText = "";
    
    	public ActionListener surfListener; // Remain public ?
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    The actionPerformed method must be in the class that implements ActionListener, and that's the only requirement.

  3. #3
    eXistenZ is offline Member
    Join Date
    Mar 2011
    Posts
    7
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    The actionPerformed method must be in the class that implements ActionListener, and that's the only requirement.
    Thanks.

    Then why does the addActionListener() method take any other parameter than (this) ? I noticed in Horstman BigJava(2e) that addActionListener() can take the parameter of (outerClass). I thought maybe it could take (OTHERclass).


    Later -- Works fine.

    PHP Code:
    /*
     * File: NameSurfer.java
     * ---------------------
     * When it is finished, this program will implements the viewer for
     * the baby-name database described in the assignment handout.
     */
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import acm.program.*;
    import javax.swing.*;
    
    /**
     * Main method
     */
    public class NameSurfer extends Program implements NameSurferConstants,
    		ActionListener {
    
    	/**
    	 * This method has the responsibility for reading in the data base and
    	 * initializing the interactors at the bottom of the window.
    	 */
    	public void run() {
    
    		init();
    
    		bottomPanel = createBottomPanel();
    		frame.add(bottomPanel, SOUTH);
    
    		grafPanel = new NameSurferGraph();
    		frame.add(grafPanel, CENTER);
    
    		frame.setVisible(true);
    	}
    
    	/**
    	 * Makes a control panel for bottom of frame.
    	 * 
    	 * @return Control panel.
    	 */
    	public JPanel createBottomPanel() {
    
    		myBottPanel = new JPanel();
    		createTextField();
    		createButtons();
    
    		return myBottPanel;
    	}
    
    	private void createButtons() {
    
    		buttonGraph = new JButton("Graph");
    		buttonClear = new JButton("Clear");
    		myBottPanel.add(buttonGraph);
    		myBottPanel.add(buttonClear);
    
    		buttonGraph.addActionListener(this);
    		buttonClear.addActionListener(this);
    	}
    
    	private void createTextField() {
    
    		nameLabel = new JLabel("Name");
    		myBottPanel.add(nameLabel);
    		nameChoice = new JTextField(20);
    		myBottPanel.add(nameChoice);
    
    		nameChoice.addActionListener(this);
    	}
    
    	/**
    	 * This class is responsible for detecting when the buttons are clicked, so
    	 * you will have to define a method to respond to button actions.
    	 */
    	public void actionPerformed(ActionEvent e) {
    
    		System.out.println("mouse clicked -- main");
    		if (e.getSource() == nameChoice) {
    			nameText = nameChoice.getText();
    			System.out.println(("JText: " + nameText));
    			if (surfers.findEntry(nameText)==null) {
    				nameChoice.setText(null);
    			}else{
    				String nameTextUp= nameText.toUpperCase();
    				nameChoice.setText(nameTextUp);
    				surfer = surfers.findEntry(nameText);
    			}
    			System.out.println(surfer + " t " + grafPanel.surferList.size());
    		}
    		if (e.getSource() == buttonGraph) {
    			if (nameText.equals("")) {
    				System.out.println("Need to enter a name. ");
    			} else {
    				System.out.println("Graph: " + nameText);
    				grafPanel.addEntry(surfer);
    				grafPanel.update(); // update then buildgraph
    				System.out.println(surfer + " g  "
    						+ grafPanel.surferList.size());
    			}
    		}
    		if (e.getSource() == buttonClear) {
    			nameChoice.setText("");
    			System.out.println("Clear: " + nameText);
    			grafPanel.clear();
    		}
    	}
    
    	/**
    	 * Initializes program with single frame
    	 */
    	public void init() {
    
    		frame = new JFrame();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(NameSurferConstants.APPLICATION_WIDTH,
    				NameSurferConstants.APPLICATION_HEIGHT);
    	}
    
    	/* Instance Variables */
    
    	private JLabel nameLabel;
    
    	private JTextField nameChoice;
    
    	private JButton buttonGraph;
    
    	private JButton buttonClear;
    
    	private String nameText = "";
    
    	public NameSurferGraph graph;
    
    	private JFrame frame;
    
    	public NameSurferEntry surfer;
    
    	private NameSurferGraph grafPanel;
    
    	public ActionListener nameSurf;
    
    	private JPanel myBottPanel;
    
    	private JPanel bottomPanel;
    
    	public NameSurferDataBase surfers = new NameSurferDataBase("names-data.txt");
    
    }
    PHP Code:
    /*
     * File: NameSurferGraph.java
     * ---------------------------
     * This class represents the canvas on which the graph of
     * names is drawn. This class is responsible for updating
     * (redrawing) the graphs whenever the list of entries 
     * changes or the window is resized.
     */
    
    import java.util.*;
    import java.awt.*;
    import java.awt.event.ComponentEvent;
    import java.awt.geom.Line2D;
    import javax.swing.*;
    
    public class NameSurferGraph extends JPanel implements NameSurferConstants {
    
    	@Override
    	protected void paintComponent(Graphics g) {
    
    		super.paintComponent(g);
    
    		g2 = (Graphics2D) (g);
    		buildGraph();
    
    	}
    
    	/**
    	 * Draws lines and borders. Draws points and labels for names in surferList
    	 * array
    	 * 
    	 */
    	private void buildGraph() {
    
    		// System.out.println("buildGraph");////
    		// System.out.println(" bg surferList size " + surferList.size());////
    
    		Rectangle centerRect = new Rectangle(0, 0, wide, high);
    		g2.setPaint(Color.white);
    		g2.fill(centerRect);
    		g2.draw(centerRect);
    		g2.setPaint(Color.black);
    
    		wide = getWidth();
    		high = getHeight() - 5;
    		Line2D.Double topp = new Line2D.Double(0, 0, wide, 0);
    		g2.draw(topp);
    		Line2D.Double bott = new Line2D.Double(0, high, wide, high);
    		g2.draw(bott);
    		Line2D.Double righ = new Line2D.Double(wide, 0, wide, high);
    		g2.draw(righ);
    		Line2D.Double bordBott = new Line2D.Double(0, high - marg, wide, high
    				- marg);
    		g2.draw(bordBott);
    		Line2D.Double bordTopp = new Line2D.Double(0, marg, wide, marg);
    		g2.draw(bordTopp);
    		graphRange = (high - marg) - marg;
    		// System.out.println("graph max " + graphRange);////
    		int graphMin = marg;
    		int graphMax = graphRange - marg;
    
    		Line2D.Double[] decsLine = new Line2D.Double[decs];
    		int decsWide = wide / (decs);
    		String decadeStr = "";
    		int decade = 1900;
    
    		for (int i = 0; i < decsLine.length; i++) {
    			decsLine[i] = new Line2D.Double(decsWide * i, 0, decsWide * i, high);
    			g2.draw(decsLine[i]);
    
    			decade = (1900 + 10 * i);
    			decadeStr = Integer.toString(1900 + 10 * i);
    			g2.drawString(decadeStr, decsWide * i + 5, high - 5);
    		}
    
    		for (int j = 0; j < surferList.size(); j++) {
    			String listName = surferList.get(j).getName();
    			// System.out.println(listName);
    
    			int x1 = 0;
    			int y1 = 0;
    			int x2 = 0;
    			int y2 = 0;
    			for (int k = 0; k < decsLine.length; k++) {
    
    				decade = (1900 + 10 * k);
    				int listRank = surferList.get(j).getRank(decade);
    				int listSpot = (graphRange * surferList.get(j).getRank(decade)) / 1000;
    				if (listRank == 0) {
    					listSpot = graphMax + graphMin;
    				}
    				x2 = decsWide * k;
    				y2 = graphMin + listSpot;
    				g2.drawLine(x1, y1, x2, y2);
    				x1 = x2;
    				y1 = y2;
    
    				// System.out.println(j + " " + k + " list rank " + listRank);
    				g2.drawString(listName + " " + listRank, decsWide * k, listSpot
    						+ marg);
    			}
    		}
    	}
    
    	/**
    	 * Clears the list of name surfer entries stored inside this class.
    	 */
    	public void clear() {
    		// System.out.println("clear method");////
    		removeAll();
    		surferList.clear();
    		update();
    		repaint();
    	}
    
    	/**
    	 * Adds a new NameSurferEntry to the list of entries on the display. Note
    	 * that this method does not actually draw the graph, but simply stores the
    	 * entry; the graph is drawn by calling update.
    	 */
    	public void addEntry(NameSurferEntry entry) {
    
    		System.out.println("Add entry");// //
    		surferList.add(entry);
    		// int size = surferList.size(); //////
    		// System.out.println("surferlist addentry "+size); /////
    		update();
    	}
    
    	/**
    	 * Updates the display image by deleting all the graphical objects from the
    	 * canvas and then reassembling the display according to the list of
    	 * entries. Your application must call update after calling either clear or
    	 * addEntry; update is also called whenever the size of the canvas changes.
    	 */
    	public void update() {
    		// System.out.println(surfer +" up "+ grafPanel.surferList.size());///
    		removeAll();
    		buildGraph();
    		System.out.println("update");
    		repaint();
    	}
    
    	/* Implementation of the ComponentListener interface */
    
    	public void componentHidden(ComponentEvent e) {
    	}
    
    	public void componentMoved(ComponentEvent e) {
    	}
    
    	public void componentResized(ComponentEvent e) {
    		update();
    	}
    
    	public void componentShown(ComponentEvent e) {
    	}
    
    	/* Instance Variables */
    
    	public int down = 70;
    
    	private int high = NameSurferConstants.APPLICATION_HEIGHT - down;
    
    	private int wide = NameSurferConstants.APPLICATION_WIDTH - 10;
    
    	private int marg = NameSurferConstants.GRAPH_MARGIN_SIZE;
    
    	private int decs = NameSurferConstants.NDECADES;
    
    	private Graphics2D g2;
    
    	public ArrayList<NameSurferEntry> surferList = new ArrayList<NameSurferEntry>();
    
    	private int graphRange;
    
    }
    Last edited by eXistenZ; 03-31-2011 at 05:00 AM.

Similar Threads

  1. CS106A Stanford University
    By Learning Java in forum New To Java
    Replies: 116
    Last Post: 07-09-2011, 05:43 PM
  2. MousePressed event help needed(CS106A )
    By ccie007 in forum New To Java
    Replies: 4
    Last Post: 11-09-2010, 08:29 PM
  3. Replies: 2
    Last Post: 03-23-2009, 10:02 AM
  4. Replies: 3
    Last Post: 08-08-2008, 03:53 AM
  5. JXTaskPane Action performed
    By Rama Koti Reddy in forum AWT / Swing
    Replies: 0
    Last Post: 12-10-2007, 02:27 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •