Tommy Saechao
Tommy Saechao

Reputation: 1139

How do I update JTextArea text inside an actionListener?

I want my program to update the TextArea whenever I click Add Employee and enter information about the employee.

(I haven't implemented the code for the Add Production Worker button yet because I can't get the Add Employee button to work).

/**
 * *****************************************************************************
 * Program Name: EmployeeAndProductionWorkerClasses.java Created Date: 1/31/2016 Created By: Tommy Saechao Purpose: The
 * main class of this program. This program demonstrates the use of inheritance in Java.
 * *****************************************************************************
 */
package pkg10.pkg1.employee.and.productionworker.classes;

import java.awt.*; //Abstract Window ToolKit, Container and Layouts
import java.awt.event.*; //ActionListener, ActionEvent
import javax.swing.*; //Swing classes

public class EmployeeAndProductionWorkerClasses {

    //default employee
    static Employee defaultEmployee = new Employee();

    //default production worker
    static ProductionWorker defaultProductionWorker = new ProductionWorker();



    public static void main(String[] args) {

        //Window sizes
        final int WINDOW_WIDTH = 450;
        final int WINDOW_HEIGHT = 350;

        //Creates a JFrame Window
        JFrame window = new JFrame();
        //sets the title of the JFrame window
        window.setTitle("Employee and Production Worker Classes");
        //Sets size of fthe JFrame window
        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        //Closes the window if the exit button is clicked
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //sets location of the program being displayed on the screen
        window.setLocation(200, 200);

        //Creates a container using border layout
        Container c = window.getContentPane();
        c.setLayout(new BorderLayout());

        //Add worker button
        JButton addEmployeeBtn = new JButton("Add Employee"); //Creates a button for adding Employees
        c.add(addEmployeeBtn, BorderLayout.LINE_START); //Adds the addEmployeeBtn to the left side of the container (c)

        //Remove worker button
        JButton addProductionWorkerBtn = new JButton("Add Production Worker"); //Creates a button for adding Production Workers
        c.add(addProductionWorkerBtn, BorderLayout.LINE_END); //Adds the addProductionWorkerBtn to the right side of the container (c)

        //View Workers TextArea
        JTextArea viewWorkersTA = new JTextArea(defaultEmployee.toString());
        c.add(viewWorkersTA, BorderLayout.CENTER);

        addEmployeeBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String name = JOptionPane.showInputDialog("Name: ");
                String employeeNumber = JOptionPane.showInputDialog("Employee Number (###-L): ");
                String hireDate = JOptionPane.showInputDialog("Hire Date (mm/dd/yyyy): ");

                defaultEmployee = new Employee(name, employeeNumber, hireDate);

            }

        });

        //Display the window.
        window.setVisible(true); //sets the window frame visible

    }

}

Employee Class

/*******************************************************************************
* Program Name: Employee.java
* Created Date: 1/31/2016
* Created By: Tommy Saechao
* Purpose: A superclass that holds information about a typical employee.
*******************************************************************************/

package pkg10.pkg1.employee.and.productionworker.classes;
import javax.swing.*; //Swing classes

//Employee Class
public class Employee {

    private String name; //Holds the employee's name
    private String employeeNumber; //Holds the employee's number
    private String hireDate; //Holds when the employee was hired

    Employee(String name, String employeeNumber, String hireDate) {
        this.name = name; //Initializes employee's name
        setEmployeeNumber(employeeNumber); //Initializes employee's number
        this.hireDate = hireDate; //initializes hireDate
    }

    //Default constructor
    Employee() {
        name = ""; //Default name (blank)
        employeeNumber = ""; //Default employee number (blank)
        hireDate = ""; //Default employee hire date (blank)
    }

    //Sets the employee's name
    public void setName(String name) {
        this.name = name; 
    }

    //Returns the employee's name
    public String getName() {
        return this.name;
    }

    //Sets the employee's number
    private void setEmployeeNumber(String employeeNumber) {


        if (isValidEmployeeNumber(employeeNumber)) { //Determines if the employee number given is valid
            this.employeeNumber = employeeNumber; //sets employee number
        } else {
            this.employeeNumber = ""; //sets employee number to default (blank)
        }
    }


    //Returns employee number
    private String getEmployeeNumber() {
        return employeeNumber;
    }

    //sets employee's hire date
    private void setHireDate(String hireDate) {
        this.hireDate = hireDate;
    }

    //returns employee's hire date
    private String getHireDate() {
        return hireDate;
    }

    //determines if an employee number is valid
    private boolean isValidEmployeeNumber(String employeeNumber) {
        boolean status = true; //default status value

        if (employeeNumber.length() != 5) //an employee number is a length of 5 characters
        {
            status = false;
        } else if ((!Character.isDigit(employeeNumber.charAt(0))) //First character must be a digit
                || (!Character.isDigit(employeeNumber.charAt(1))) //Second character must be a digit
                || (!Character.isDigit(employeeNumber.charAt(2))) //Third character must be a digit
                || (employeeNumber.charAt(3) != '-') //fourth character must be a hyphen
                || (Character.toUpperCase(employeeNumber.charAt(4)) < 'A') //4th character must be in between letters A-Z
                || (Character.toUpperCase(employeeNumber.charAt(4)) > 'M')) 
        {
            status = false; //status is false if conditions don't meet
        }
        return status; //returns if the employee number is valid (true for valid)
    }


    //Returns a string value holding informatino about the employee
    public String toString()
    {

        String str = "Name: " + name + "\nEmployee Number: "; //sets str equal to the employee's name

        if (employeeNumber == "") //employee must have a valid number, if they have a blank number, it is invalid
            str += "INVALID EMPLOYEE NUMBER";
        else //concatenate str with the employee's number
            str += employeeNumber;
        str += ("\nHire Date: " + hireDate); //concatenate the str with the employee's hire date
        return str; //return str
    }

    //////////////////////////////////////////////////GUI///////////////////////////////////

    ////////Show Info////////
    private JPanel showInfoPanel;
    private JTextArea employeeInformation;

    public void buildPanel()
    {
        showInfoPanel = new JPanel();
        employeeInformation = new JTextArea(this.toString(), 10, 50);
        showInfoPanel.add(employeeInformation);
    }

    public JPanel getInfoPanel()
    {
        this.buildPanel();
        return showInfoPanel;
    }



}

ProductionWorker Class

/*******************************************************************************
* Program Name: ProductionWorker.java
* Created Date: 1/31/2016
* Created By: Tommy Saechao
* Purpose: A subclass that inherits information from the Employee superclass. 
*          This subclass contains information about a production worker. 
*******************************************************************************/
package pkg10.pkg1.employee.and.productionworker.classes;

import java.text.DecimalFormat;

//subclass of Employee
public class ProductionWorker extends Employee{

    //Day Shift value is 1, Night shift value is 2
    public static final int DAY_SHIFT = 1;
    public static final int NIGHT_SHIFT = 2;

    private int shift; //holds the shift value
    private double hourlyPayRate; //holds the hourly pay rate

    //default constructor
    ProductionWorker()
    {
        super(); //calls the default super class constructor 
                //Employee's name, employeeNumber, and hireDate will be blank ("")
        shift = DAY_SHIFT; //default shift is day shift
        hourlyPayRate = 0.0; //default pay is zero
    }

    //constructor
    ProductionWorker(String name, String employeeNumber, String hireDate, int shift, int hourlyPayRate)
    {
        super(name, employeeNumber, hireDate); //calls superclass constructor
                                            //Employee's name, emloyee number, and hire date will be set equal to
                                            //name, employeeNumber, and hireDate from this constructor's givevn arguments
        this.shift = shift; //sets shift value
        this.hourlyPayRate = hourlyPayRate; //sets employee's hourly pay rate value
    }


    //sets shift
    public void setShift (int shift)
    {
        this.shift = shift;
    }

    //sets pay rate
    public void setPayRate (double hourlyPayRate)
    {
        this.hourlyPayRate = hourlyPayRate;
    }

    //returns shift number
    public int getShift() 
    {
        return shift;
    }

    //returns pay rate
    public double getPayRate()
    {
        return hourlyPayRate;
    }

    //provides information about a production worker
    public String toString()
    {

        //formats a double value to appear as the dollar format
        DecimalFormat dollar = new DecimalFormat("#,##0.00"); 

        /*calls superclass' toString method, which gives str information about the employee's
        name, employee number, and hire date*/
        String str = super.toString();

        //adds shift time to str
        str += "\nShift: ";
        if (shift == DAY_SHIFT)
            str += "Day";
        else if (shift == NIGHT_SHIFT)
            str += "Night";
        else
            //the employee doesn't have a valid shift number (valid is DAY_SHIFT (1) and NIGHT_SHIFT (2) )
            str += "INVALID SHIFT NUMBER"; 

        //adds hourly pay rate information to str
        str += ("\nHourly Pay Rate: $" + dollar.format(hourlyPayRate));

        return str; //returns str

    }

}

Upvotes: 0

Views: 1308

Answers (2)

camickr
camickr

Reputation: 324197

If you want to update the text area (or any Swing component) then you need a reference to the component.

So you need to define the variable as an instance variable in your class. Then you either update the variable directly in that class or you need to create an updateTextArea(...) method for that class that you can access from the ActionListener.

Check out the section from the Swing tutorial on How to Write a Mouse Listener. The demo code there shows an example of how you can structure your code so you can update a text area from a listener. It should give you a better idea how to design your class.

Upvotes: 2

Jonah
Jonah

Reputation: 1003

If you would like to set the text of a JTextArea use textArea.setText("My Text");

If you would like to add more text to the existing text, use textArea.append("Text To Add");

Just place whichever one you would like to use in the buttons ActionListener and you should be good to go.

Upvotes: 0

Related Questions