該項目的目標是採用我已經編寫並實現了一個「manager」類的現有代碼,該類將負責創建和存儲Dog對象數組。我的問題在於,我不明白爲什麼需要這樣做,這阻礙了我理解我需要做什麼/更改爲我的代碼。任何幫助將不勝感激。謝謝!實現負責創建和存儲對象的「manager」類
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);
}
}
「爲什麼需要這樣做」 - 您在這裏指「這個」是什麼意思? – senyor
首先,重寫'public String setName(String Name){this.name = name; 返回名稱; } - 分成getter和setter。 – senyor
我的意思是說,在添加管理器類之後,程序本質上應該做與現在一樣的事情,只是以不同的方式。我不理解的是我需要放在經理類中。 – Ben