实现一个负责创建和存储对象的“manager”类

时间:2014-03-03 17:54:58

标签: java swing user-interface

输入文本并按下按钮后,GUI应创建用户定义的Dog类的实例,然后将其打印回下面textArea中的GUI。 Manager类应该负责通过使用数组来创建和存储Dog Objects。目前我的代码将运行,但是当输入文本并按下按钮时,我收到一条错误消息:“狗无法解析为变量”任何有助于让我的代码正常工作的帮助将非常感激。谢谢!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Manager {
    private Dog[] Dogs = new Dog[50];
    private int counter = 0;

    public void createDog(String name, String breed, String age) {
        Dogs[counter] = Dog;
        counter++;
    }

    public String returnLastDog() {
        return "Dog: " + Dogs[counter - 1] + "\n";

    }
}

class Dog {
    public String name;
    public String breed;
    public String age;

    // Constructs fields
    public Dog(String name, String breed, String age) {
        this.name = name;
        this.breed = breed;
        this.age = age;

    }

    public String setName(String Name) {
        this.name = name;
        return name;
    }

    public String setbreed(String breed) {
        this.breed = breed;
        return breed;
    }

    public String setage(String age) {
        this.age = age;
        return age;
    }

    public String toString() {
        return ("Name: " + this.name + " breed: " + this.breed + " age: " + this.age);
    }
}

public class LabFour extends JFrame implements ActionListener {
    public LabFour() {
        setLayout(new GridLayout(5, 1, 1, 1));

        // Creates TextField, TextArea, and button components
        name = new JTextField();
        breed = new JTextField();
        age = new JTextField();
        JButton jbtSubmit = new JButton("Submit");
        echoDog = new JTextArea();

        // Add TextField, TextArea, and button components to the frame
        add(new JLabel("Name: "));
        add(name);
        add(new JLabel("Breed: "));
        add(breed);
        add(new JLabel("Age: "));
        add(age);
        add(new JLabel("Submit Button: "));
        add(jbtSubmit);
        jbtSubmit.addActionListener(this);
        add(new JLabel("Submitted Text: "));
        add(echoDog);
        echoDog.setEditable(false);

    }

    // TextFields
    private JTextField name;
    private JTextField breed;
    private JTextField age;

    // Echo TextArea
    private JTextArea echoDog;

    // Manager Object
    private Manager m1 = new Manager();

    // Listener
    public void actionPerformed(ActionEvent a) {
        m1.createDog(name.getText(), breed.getText(), age.getText());
        echoDog.append(m1.returnLastDog());

    }

    // Main
    public static void main(String[] args) {
        LabFour frame = new LabFour();
        frame.setTitle("Dog Interface");
        frame.setSize(1200, 900);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);

    }

}

1 个答案:

答案 0 :(得分:3)

您需要创建Dog的实例以分配给数组元素

dogs[counter] = new Dog(name, breed, age);