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

时间:2013-10-17 22:03:15

标签: java

我有一个作业,我必须在“学生”课程中进行更改(我猜)将其从字符串转换为按钮。例如,我需要能够调用学生类并创建一个新的运算符(?)并将其作为按钮添加到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;
  }
}

1 个答案:

答案 0 :(得分:1)

在风格上,您的课程应该大写,以便与您的方法轻松区分。 JButton构造函数采用String,Icon或Action。使您的Student类成为JButton的子类。

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