任何人都可以幫助我實現我的無響應jbutton線程?我想通過使用pepraredStatement插入到數據庫。然而,無論何時添加數據庫部分(connection和pepraredStatement),'UPLOAD'按鈕都不響應。但是當我刪除任何與數據庫相關的東西時,我所有的按鈕都在運行。你可以在這裏找到代碼http://pastebin.com/euKdWhr2。無響應的jbutton請求併發
我會很感激任何幫助或建議。我有關於線程的解釋,但我仍然無法將其包含到我的代碼中。
public void actionPerformed(ActionEvent ev)
{
String file = fileField.getText();
SetGetQuestionFileName pattern = new SetGetQuestionFileName(file);
ConnectToDatabase database = new ConnectToDatabase();
try
{
///////// check whether textfile is empty or not
if(ev.getActionCommand().equals("UPLOAD"))
{
if(fileField.getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"File field can not be empty!!! Please try again.","ALERT", JOptionPane.ERROR_MESSAGE);
}
else
{
File fi = new File(fileField.getText());
//////////////// perform upload
try
{
String sql = "INSERT INTO testsystem.questionnaire (category_questions, questions, correct_answer)" + "VALUES (?, ?, ?)";
PreparedStatement st = null;
Connection dbconnection = database.getConnection();
st = dbconnection.prepareStatement(sql);
if(fi.getAbsoluteFile().exists())
{
List<String> lines = Files.readAllLines(Paths.get(fileField.getText()), Charset.defaultCharset());
for (int i = 0; i < lines.size(); i+=10)
{
String category = lines.get(i);
System.out.println(category);
String question = lines.get(i+1);
System.out.println(question);
String answers =
lines.get(i+2)+System.lineSeparator()
+lines.get(i+3)+System.lineSeparator()
+lines.get(i+4)+System.lineSeparator()
+lines.get(i+5);
System.out.println(answers);
String correct = lines.get(i+7);
System.out.println("correct answer is: "+correct);
System.out.println("----------------");
st.setString(1, category);
st.setString(2, answers);
st.setString(3, correct);
st.executeUpdate();
}
JOptionPane.showMessageDialog(null,"File has been successfully uploaded in the database.","NOTIFCATION",JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null,"File could not be found. Please try again","ALERT",JOptionPane.ERROR_MESSAGE);
}
catch(SQLException ex)
{
}
catch(Exception ex)
{
}
認沽'e.printStackTrace()'到你的'catch'塊。 – 2014-11-14 23:10:46
您的問題:您在GUI線程中提供耗時的操作(調用EDT - 事件分派器線程)。只需將數據庫代碼移動到另一個線程中,例如使用[SwingWorker](https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html)。閱讀[這裏](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html),你會更好地理解你的問題。 – 2014-11-14 23:15:49
這就是我現在得到的錯誤java.lang.NullPointerException at Lecturer $ MyAction.actionPerformed(Lecturer.java:183)and the line 183 is this one st = dbconnection.prepareStatement(sql); – mkwilfreid 2014-11-14 23:18:58