任何人都可以帮助我实现我的无响应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