这个项目的目标只是输入一些文本,按一个按钮,让我的GUI在文本区域中创建一个“Dog”类的实例。然而,当我按下我的按钮时,它总是打印:“Dog @ 2a4c6a7d”或其他一些看似随机的数字和字母组合。任何有关此问题的帮助将不胜感激。谢谢!
以下正确且有效的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Dog {
private String name;
private String breed;
private String age;
public Dog(String name, String breed, String age) {
this.name = name;
this.breed = breed;
this.age = age;
}
public String setDogName(String name) {
this.name = name;
return name;
}
public String setDogBreed(String breed) {
this.breed = breed;
return breed;
}
public String SetDogAge(String age) {
this.age = age;
return age;
}
public String toString() {
return ("Name: " + this.name + " Breed: " + this.breed + " Age: " + this.age);
}
}
public class LabThree extends JFrame implements ActionListener {
public LabThree() {
setLayout(new GridLayout(8, 3));
// Creates TextFields, TextAreas, and the button
name = new JTextField();
breed = new JTextField();
age = new JTextField();
JButton jbtGenerate = new JButton("Generate Dog");
echoDog = new JTextArea();
// Adds TextFields, TextAreas, and the button
add(new JLabel("Name:"));
add(name);
add(new JLabel("Breed:"));
add(breed);
add(new JLabel("Age:"));
add(age);
add(jbtGenerate);
jbtGenerate.addActionListener(this);
add(echoDog);
echoDog.setEditable(false);
}
// Top TextFields
private JTextField name;
private JTextField breed;
private JTextField age;
// Bottom(echoed) TextArea
private JTextArea echoDog;
public void actionPerformed(ActionEvent a) {
Dog dog1 = new Dog(name.getText(), breed.getText(), age.getText());
echoDog.setText(dog1.toString());
}
public static void main(String[] args) {
LabThree frame = new LabThree();
frame.setTitle("Dog Generator");
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
答案 0 :(得分:2)
您需要覆盖Dog类中的toString()函数。像这样:
public String toString()
{
return this.name + this.breed + this.age;
}
一点解释:
You Dog类默认继承自Object。在object中,已经声明了一个返回getClass().getName() + '@' + Integer.toHexString(hashCode())
的toString()。当你说Dog@2a4c6a7d
时,这就是你所看到的。它是类的名称,然后是类的哈希码。
当您将类似上面的toString()函数添加到Dog类时,将调用新的toString()。这是面向对象编程的关键概念。