The goal of this project is simply to enter some text, press a button, and have my GUI create an instance of the "Dog" class in the text area. However, when I press my button, it always prints: "Dog@2a4c6a7d" or some other seemingly random combination of numbers and letters. Any help with this issue would be greatly appreciated. Thanks!
Correct and functioning code below:
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);
}
}