java无响应jbutton请求并发性
有人能帮我实现无响应jbutton的线程吗?我想使用pepraredStatement插入到数据库中。但是,每当我添加数据库部分(connection和pepraredStatement)时,“UPLOAD”按钮就没有响应。但是当我删除任何与数据库相关的内容时,我所有的按钮都在工作。您可以在这里找到代码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)
{
}
# 1 楼答案
当您有一个操作时,强烈建议您封装实际执行该操作的代码。在您的例子中,它是db(称为DBThread)。为了使按钮不会失去响应,您需要将其分为3部分(起初听起来太多,但这很有意义)。所以你会有
因此,前面提到的DBThread是您的业务逻辑。该操作将调用一个进度线程,在该线程中,您可以在面板上放置一个gif图像,显示最终用户正在后台进行的操作。此progressThread还允许您等待DBthread完成,以便向最终用户提供有关结果的建议。我通常在开始时将按钮设置为setEnable(false)和setEnable(true),这样用户就知道他不能单击两次
希望这有帮助:-)