gpt4 book ai didi

java - 让我的 GUI 从类创建实例并将该信息拉入文本区域

转载 作者:行者123 更新时间:2023-12-02 06:12:33 25 4
gpt4 key购买 nike

这个项目的目标只是输入一些文本,按下按钮,然后让我的 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);

}

}

最佳答案

您需要重写 Dog 类中的 toString() 函数。像这样的事情:

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

一点解释:

You Dog 类默认继承自 Object。在对象中,已经声明了一个 toString(),它返回 getClass().getName() + '@' + Integer.toHexString(hashCode()) 。这就是当您说 Dog@2a4c6a7d 时所看到的内容。它是类的名称,然后是类的哈希代码。

当您将上面的 toString() 函数添加到 Dog 类时,您的新 toString() 会被调用。这是面向对象编程的一个关键概念。

关于java - 让我的 GUI 从类创建实例并将该信息拉入文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21765429/

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