图形用户界面
Graphical User Interfaces
假设我们有一个 class 存储学生对象列表。还有另一个 class 使用图形用户界面要求用户创建学生对象。
我试过这样做
public class Database {
private List<Student> students;
public Database {
students = new ArrayList<Student>();
}
public void addStudent() {
StudentDialog dialog = new StudentDialog();
dialog.setVisible(true)
students.add(dialog.getStudent());
}
}
public class StudentDialog extends JDialog {
private JTextField field;
public StudentDialog(Frame owner) {
super(owner);
field = new JTextField();
}
public Student getStudent {
return new Student(field.getText());
}
}
public class Student {
private String name;
public Student(String name){
this.name = name;
}
}
但是,这不起作用,因为用户需要时间来输入学生。达到我的目标最惯用的方法是什么?明确地说,我希望能够使用 addStudent 方法随意添加学生。
When the addStudent method is called, it finishes before the user enters any data in the text field
要使对话框停止当前代码的执行直到关闭,您需要将对话框设置为模态。将 setModal(true)
添加到对话框构造函数
public class StudentDialog extends JDialog {
private JTextField field;
public StudentDialog(Frame owner) {
super(owner);
setModal(true);
field = new JTextField();
// I assume you're actually adding this text field to the dialog
}
public Student getStudent {
return new Student(field.getText());
}
}
您可以只使用 JOptionPane
而不是
有关详细信息,请参阅 How to Make Dialogs
假设我们有一个 class 存储学生对象列表。还有另一个 class 使用图形用户界面要求用户创建学生对象。
我试过这样做
public class Database {
private List<Student> students;
public Database {
students = new ArrayList<Student>();
}
public void addStudent() {
StudentDialog dialog = new StudentDialog();
dialog.setVisible(true)
students.add(dialog.getStudent());
}
}
public class StudentDialog extends JDialog {
private JTextField field;
public StudentDialog(Frame owner) {
super(owner);
field = new JTextField();
}
public Student getStudent {
return new Student(field.getText());
}
}
public class Student {
private String name;
public Student(String name){
this.name = name;
}
}
但是,这不起作用,因为用户需要时间来输入学生。达到我的目标最惯用的方法是什么?明确地说,我希望能够使用 addStudent 方法随意添加学生。
When the addStudent method is called, it finishes before the user enters any data in the text field
要使对话框停止当前代码的执行直到关闭,您需要将对话框设置为模态。将 setModal(true)
添加到对话框构造函数
public class StudentDialog extends JDialog {
private JTextField field;
public StudentDialog(Frame owner) {
super(owner);
setModal(true);
field = new JTextField();
// I assume you're actually adding this text field to the dialog
}
public Student getStudent {
return new Student(field.getText());
}
}
您可以只使用 JOptionPane
而不是
有关详细信息,请参阅 How to Make Dialogs