【发布时间】:2014-11-14 23:04:58
【问题描述】:
谁能帮我为我的反应迟钝的 jbutton 实现线程?我想使用 pepraredStatement 插入数据库。但是,每当我添加数据库部分(连接和 pepraredStatement)时,“上传”按钮就会无响应。但是当我删除与数据库相关的任何内容时,我所有的按钮都在工作。你可以在这里找到代码http://pastebin.com/euKdWhr2。
我将非常感谢任何帮助或建议。我已经对线程进行了解释,但我仍然无法将其包含在我的代码中。
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块中。 -
您的问题:您在 GUI 线程中提供了耗时的操作(调用 EDT - 事件调度程序线程)。只需将您的数据库代码移动到另一个线程,例如使用SwingWorker。阅读here,你会更好地理解你的问题。
-
这就是我现在在 Lecturer$MyAction.actionPerformed(Lecturer.java:183) 处得到的 java.lang.NullPointerException 错误,第 183 行是这个 st = dbconnection.prepareStatement(sql);
-
Sergiy Medvynskyy 如果您不介意,您能否解释一下我如何从发布的代码中做到这一点。我是 Java 新手,对多线程了解不多
标签: java multithreading swing concurrency swingworker