簡體   English   中英

如何在actionListener中更新JTextArea文本?

[英]How do I update JTextArea text inside an actionListener?

我希望我的程序每當我單擊“添加員工”並輸入有關員工的信息時都更新TextArea。

(我尚未實現Add Production Worker按鈕的代碼,因為我無法使Add Employee按鈕起作用)。

/**
 * *****************************************************************************
 * 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

    }

}

員工階層

/*******************************************************************************
* 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;
    }



}

生產工人班

/*******************************************************************************
* 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

    }

}

如果要更新文本區域(或任何Swing組件),則需要對該組件的引用。

因此,您需要在類中將變量定義為實例變量。 然后,您可以直接在該類中更新變量,或者需要為可從ActionListener訪問的該類創建一個updateTextArea(...)方法。

查看Swing教程中有關如何編寫鼠標偵聽器的部分 那里的演示代碼顯示了一個示例,該示例說明如何構建代碼,以便可以從偵聽器更新文本區域。 它應該給您一個更好的主意,如何設計您的課程。

如果要設置JTextArea的文本,請使用textArea.setText("My Text");

如果您想在現有文本中添加更多文本,請使用textArea.append("Text To Add");

只需將要使用的任何一個放置在按鈕ActionListener ,就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM