2011-11-23 85 views
1

是否有可能在單擊jButton時直接執行SQL查詢?如何在jButton中用java執行特定的SQL查詢

例如,在jDialog中,我有一個用於用戶名和保存按鈕的文本框。

JButton的操作:

@Action 
public void saveNewUser() { 
    Statement s = con.createStatement(); 
    s.executeUpdate("INSERT INTO User (username) " + " VALUES ('"+ username + "')") 
} 

所以我需要從用戶名文本框獲取字符串,但如何?

+1

是的,任何事情都是可能的。閱讀搖擺教程以掌握框架。 http://docs.oracle.com/javase/tutorial/uiswing/ –

回答

4

您應該查看Swing API。該文本字段將是一個JTextField。下面是對Java JDK API鏈接:http://docs.oracle.com/javase/6/docs/api/這裏是一個直接的JTextField:http://docs.oracle.com/javase/6/docs/api/javax/swing/JTextField.html

下面是一些非常簡單的代碼,你想要做什麼(我忽略佈局,國際化功能,以及其他各種改進):

JTextField usernameTextField = new JTextField("Username:"); 
JButton saveButton = new JButton("Save"); 

saveButton.addActionListener(new ActionListener()) 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
    String username = usernameTextField.getText(); 
    //Put validation code here if you want 

    //Then put your SQL insert statement code here 
    } 
}); 

//Generally you will be adding them to a JPanel, but can be a JFrame for simple cases 
panel.add(usernameTextField); 
panel.add(saveButton); 

... 
+0

謝謝你的回答 – user1036529

+0

如果你喜歡它,那麼請接受它作爲答案。 –