I have this simple class Cat
to describe the features of a cat:
public class Cat {
private String name;
private String race;
private String colour;
private int age;
public Cat(String name, String race, String colour, int age) {
this.name=name;
this.race=race;
this.colour=colour;
this.age=age;
}
public String getRace() {
return race;
}
public String getName() {
return name;
}
public String getColour() {
return colour;
}
public int getAge() {
return age;
}
}
I also have a CatDemo
class that creates an instance of a Frame class (that extends JFrame) from which one can insert cat's information:
public class CatDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Frame f = new Frame();
f.setVisible(true);
}
}
When one presses OK
I have to create an instance of Cat
class (I have to create a Cat
object with the features inserted in the blanks of the GUI). It's easy to create this instance inside actionPerformed
method:
public void actionPerformed(ActionEvent arg0) {
Cat c = new Cat(textField.getText(),textField_1.getText(),
textField_2.getText(),Integer.parseInt(textField_3.getText()));
}
But now I need my Cat object to make something else. How can I use c
from CatDemo
class (where there is main)?
You need to extend Frame.
public class MyFrame extends Frame {
public Cat buildCatFromInputFields() {
...
return cat;
}
}
Also what you need to understand is, that you are leaving your main thread, when entering the AWT world (with that frame). What i mean is, that after you call f.setVisible(true) , your main method and the main thread end! Thus it would be completely advisable to just use your cat inside your ActionHandler methods (like actionPerformed() ).
您可以在主程序和框架中拥有一个公共静态猫列表,当用户按下OK时,您可以执行类似的操作
CatDemo.cats.Add(new Cat(name, race, color, age));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.