user2325652
user2325652

Reputation:

ActionListener Java issue

I have a GUI program that appends a text field depending on what button is pressed. I'm having a problem implementing my action listener. It doesn't matter what code I put in the ActionPerformed method, I always get the same errors. There are so many errors, I couldn't list them, but they appear to indicate that the actionListener isn't firing. I don't know if I'm not adding the ActionListener for the buttons properly or what. The code I have in the ActionPerformed method currently was just a test to see if it would work at all for any button I pressed and it still doesn't work. Thanks in advance.

*EDIT: Alright I changed the code in the ActionPerformed method so it would append the text area according to which button was pressed and I'm getting the same error again.

**EDIT: No more errors, just a problem with my output. I'm getting larger than normal white space for my ENTER and SPACE buttons. Changed the ActionPerformed method so it appends for each button appropriately now.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;

/**
 * GUI contains a grid of buttons and a text area. As buttons are pressed,
 * corresponding text is displayed in the text area.
 * 
 * This class serves as the program driver, the GUI frame, and the
 * ActionListener for JButton-generated events.
 * 
 **/
public class TextButtonsHW extends JFrame implements ActionListener {
    private JButton[] buttons;// Do not change
    private String[] labels;
    private JTextArea textArea; // Do not change
    // Assign values for these constants in the constructor
    private final int ENTER; // Index of Enter button in buttons
    private final int SPACE; // Index of Space button in buttons
    private final int CLEAR; // Index of Clear button in buttons

    /**
     * Set up this frame and its contents.
     * 
     * @param title
     *            Title to appear in JFrame title bar
     */
    public TextButtonsHW(String title) {
        super(title); // call parent JFrame constructor to set the title
        buttons = new JButton[12];
        String[] labels = { "A", "B", "C", "1", "2", "3", "X", "Y", "Z",
                "ENTER", "SPACE", "CLEAR" };
        // sets the value of the ENTER SPACE and CLEAR ints to indicate their
        // index in the array
        ENTER = 9;
        SPACE = 10;
        CLEAR = 11;
        // TODO: instantiate all JButtons, add them to the buttons array,
        // and register "this" as the ActionListener for each button.
        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = new JButton(labels[i]);
            buttons[i].addActionListener(this);

        }

        // TODO: create the JTextArea textArea
        textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setText("");
        // Create a TextButtonsHWPanel to display the buttons and textArea
        TextButtonsHWPanel mainPanel = new TextButtonsHWPanel(buttons, textArea);

        this.getContentPane().add(mainPanel);
        this.pack();
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO: update the text of textArea according to which
        // button generated the ActionEvent.
        for (int i = 0; i < buttons.length; i++) {
            if (i < ENTER && e.getSource() == buttons[i])
                textArea.append(buttons[i].getText());
            else if (e.getSource() == buttons[ENTER])
                textArea.append("\n");
            else if (e.getSource() == buttons[SPACE])
                textArea.append(" ");
            else if (e.getSource() == buttons[CLEAR])
                textArea.setText("");
        }

    }

    /**
     * Create this JFrame
     * 
     * @param args
     *            not used
     */
    public static void main(String[] args) {
        final TextButtonsHW f = new TextButtonsHW("Text Buttons");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null); // centers frame on screen
        f.setVisible(true);
    }
}

TextButtonsHWPanel code:

import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * Used by TextButtonsHW to display a grid of JButtons
 * and a JTextArea.
 * 
 */
public class TextButtonsHWPanel extends JPanel {

    /**
     * Constructor
     * @param buttons array of JButtons to appear in a grid for text input
     * @param textArea JTextArea for display of text in response to pressed buttons
     */
    public TextButtonsHWPanel(JButton[] buttons, JTextArea textArea) {
        //Creates a sub-panel with a 4 row, 3 column GridLayout and fills it with buttons
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(4, 3));
        for(int i=0; i<buttons.length; i++)
            buttonPanel.add(buttons[i]);
        //adds the buttonPanel
        add(buttonPanel);
        //TODO: Create a JScrollPane containing textArea
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(80, 120));
        //TODO: Set the preferred size of the scroll pane to 80x120
        //TODO: Add the scroll pane to this panel
        add(scrollPane);
    }
}

Stack Trace:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at TextButtonsHW.actionPerformed(TextButtonsHW.java:74)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Upvotes: 0

Views: 908

Answers (1)

Reimeus
Reimeus

Reputation: 159754

You are shadowing the textArea variable. Replace

JTextArea textArea = new JTextArea();

with

textArea = new JTextArea();

The same applys to the buttons array:

JButton[] buttons = new JButton[12];

replace with

buttons = new JButton[12];

Upvotes: 1

Related Questions