0

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

通常它看起来像这样:

Student st1 = new student("Random","Name", 44);

我需要能够做的是调用学生类并产生类似的东西:

st1.setText("Random"); add(st1)

我不确定要对学生班级进行哪些更改。我想也许我可以使用compareTo运算符来产生所需的结果,但运气不佳,而且我在该主题上找到的教程并没有太大帮助。

我的学生班是这样的:

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;
  }
}
4

1 回答 1

1

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

public class Student extends JButton {
    ...
    public Student(String firstName, String lastName, int age) {
        return super(firstName + lastName + Integer.toString(age));
    }
    ...
}
于 2013-10-17T22:14:39.860 回答