gpt4 book ai didi

java - 将一个类中的 String 构造函数转换为另一个类中的按钮

转载 作者:行者123 更新时间:2023-12-01 13:59:12 28 4
gpt4 key购买 nike

我有一个作业,我必须在“Student”类中进行更改,以(我猜)将其从字符串转换为按钮。例如,我需要能够调用学生类并创建一个新的运算符(?)并将其作为按钮添加到 JPanel 中。

通常它看起来像这样:

学生 st1 = 新学生("随机","姓名", 44);

我需要做的是调用学生类并生成如下内容:

st1.setText("随机");添加(st1)

我不确定学生类(class)要做什么改变。我想也许我可以使用 compareTo 运算符来产生所需的结果,但运气不佳,而且我在该主题上找到的教程也没有多大帮助。

我的学生类(class)如下所示:

public class student {
// Tried calling a JButton to send to the JPanel class which didn't work
// Also tried to create a method which would convert a string to a JButton, but still couldn't send to JPanel

String firstName;
String lastName;
int age;

public student(String a, String b, int x) // Tried calling a JButton as a constructor which didn't work
{
super();
firstName = a;
lastName = b;
age = x;
}

String getInfo() {
return "NAME = " + firstName + " " + lastName + " " + "Age = " + age;
}

String whatsUp() {
double r = Math.random();
int myNumber = (int) (r * 3f); //comment: a random number between 0 and 2
String answer = "I don't know";
if (myNumber == 0) {
answer = "searching the web";
}
if (myNumber == 1) {
answer = "doing Java";
}
if (myNumber == 2) {
answer = "Listening to endless lecture";
}
return answer;
}
}

最佳答案

在风格上,你的类应该大写,以便它们很容易与你的方法区分开来。 JButton构造函数采用字符串、图标或操作。让您的 Student 类成为 JButton 的子类。

public class Student extends JButton {
...
public Student(String firstName, String lastName, int age) {
return super(firstName + lastName + Integer.toString(age));
}
...
}

关于java - 将一个类中的 String 构造函数转换为另一个类中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19438120/

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