我希望窗口在数据被输入时关闭

Sir*_*nur -2 java swing actionlistener

我希望在输入输入并单击添加按钮后关闭窗口.我还想要一条消息,通知用户输入数据已保存.此代码链接到将存储输入的数据库对象.

public class Add extends JFrame
             implements ActionListener {

/** {@link JTextField} where the user name is entered */
JTextField Inputusername = new JTextField(7);

/** {@link JTextField} where the user age is entered */
JTextField age = new JTextField(2);

/** {@link JTextField} where the user ID is entered */
JTextField inputuserid = new JTextField(4);

/** Add Client button */

JButton addnewclient = new JButton("Add Client");
/** male Jradiobutton */
JRadioButton male = new JRadioButton("Male");
/** female Jradiobutton */
JRadioButton female = new JRadioButton("Female");
/** label for the gender selection */
Label genders = new Label("please select gender of client");

/** call the database constructor*/

private Database db; 
public Add(Database db) 
    { this.db = db; 


    //allows the positioning 
    setLayout(new BorderLayout()); 

  //setting the size of the window
    setBounds(100, 100, 500, 200); 

 // the title of the window
    setTitle("add new Client"); 

    // dispose of the window when the close button is clicked
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

 // declared new panel  
    JPanel top = new JPanel(); 
    top.add(new JLabel("Enter username :"));
    top.add(Inputusername);
    top.add(new JLabel("Enter age:"));
    top.add(age);
    top.add(new JLabel("Enter userid:"));
    top.add(inputuserid);
    add("North",top);
    // declared new panel 
    JPanel bottom = new JPanel(); 
 // add the veritable of JButton to the top panel
    bottom.add(addnewclient); 
 // add the bottom panel to the bottom of the screen
    add("South",bottom); 

    JPanel middle = new JPanel();
    ButtonGroup bg = new ButtonGroup();
    bg.add(male);
    bg.add(female);
    middle.add(male);
    middle.add(female);
    add("Center",middle);

 // do not allow user to set the size of the screen
    setResizable(false);
 // make the program  visible
    setVisible(true);
 // listen to the button
   addnewclient.addActionListener(this);   
}  

public void actionPerformed(ActionEvent e) {

    String selection = "female"; 

    if (this.male.isSelected()) 
    {
         selection = "male"; 
    }

    User u = new User(Inputusername.getText(),  selection , age.getText(), inputuserid.getText());
    db.addUser(u); 
Run Code Online (Sandbox Code Playgroud)

}

mKo*_*bel 5

使用JOptionPane,你必须看看JOptionPane#showXxxDialog,可以返回所需的解决方法


dan*_*dev 5

您可以为执行的操作方法添加一些代码.有关方法列表,请查看JFrame 的API,但您可能需要调用它this.dispose();.

堆栈溢出也有一些现有的答案,例如这个.

编辑:请注意,这将处理您正在使用的课程; 所以如果你仍然需要一些繁忙的逻辑,那么你需要一个隐藏它的方法JFrame.我相信你自己可以找到这个,但是将GUI与业务逻辑分开是一个更好的主意.