gpt4 book ai didi

java - 实现一个负责创建和存储对象的 "manager"类

转载 作者:行者123 更新时间:2023-11-30 04:00:31 25 4
gpt4 key购买 nike

这个项目的目标是利用我已经编写的现有代码并实现一个“管理器”类,该类将负责在数组中创建和存储 Dog 对象。我的问题是,我不明白为什么需要这样做,这阻碍了我理解我需要做什么/更改我的代码。任何帮助将不胜感激。谢谢!

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

class Dog {
private String name;
private String breed;
private 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;

// Listener
public void actionPerformed(ActionEvent a) {

Dog[] Dogs = new Dog[50];
int arrayLocation = 0;

Dog Dog1 = new Dog(name.getText(), breed.getText(),
age.getText());
// Checks remaining array space
if (arrayLocation < 50) {
Dogs[arrayLocation] = Dog1;
++arrayLocation;
}
// Echos back entered text while storing the previous text
echoDog.setText(echoDog.getText() + "\n" + Dog1.toString());
}

// 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);

}

}

最佳答案

正如您所写的“Manager 将负责在数组中创建和存储 Dog 对象”,因此您需要创建更好的 Dog 对象列表(以便您可以添加和删除 Dogs),为此列表添加 CRUD 方法。如果您需要列表中的数组,稍后可以轻松转换它。

所以放这样的东西

public class Manager {

private List<Dog> = new ArrayList<>();

...

CRUD operations here

}

然后您需要添加 UI 控件来实际输入有关狗的信息,并显示狗的表格。所以它将是 Pane 、文本输入、按钮等。

关于java - 实现一个负责创建和存储对象的 "manager"类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com