java - 保存到数据库使按钮无响应

标签 java mysql swing jdbc swingworker

美好的一天。我想使用 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)
                    {

                    }

最佳答案

actionPerformed() 方法由 ui 线程调用。如果您在此线程中执行长时间运行的任务,则 ui 将无响应,因为 ui 线程无法再执行 ui 工作,例如重新绘制 ui 或仅处理用户输入。

考虑使用 SwingWorker并阅读有关 concurrency in java 的教程.

编辑

i went to the proposed websites but i don't really understand what you meant by the SwingWorker . i'm not really used to the thread yet

这是一个工作示例,说明 SwingWorker 和长时间运行的后台任务如何工作。

public class SwingWorkerExample  {

    public static class ProgressSimulatorSwingWoker extends SwingWorker<Void, Void> {

        private BoundedRangeModel progressModel;

        public ProgressSimulatorSwingWoker(BoundedRangeModel progressModel) {
            this.progressModel = progressModel;
        }

        @Override
        protected Void doInBackground() throws Exception {
            int start = 0;
            int end = 100;

            progressModel.setMinimum(start);
            progressModel.setMaximum(end);

            for (int i = start; i <= end; i++) {
                progressModel.setValue(i);
                Thread.sleep(50);
            }
            return null;
        }

    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame("SwingWorker example");
        jFrame.setSize(640, 150);
        jFrame.setLocationRelativeTo(null); // center on screen
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container contentPane = jFrame.getContentPane();
        contentPane.setLayout(new BorderLayout());

        JProgressBar jProgressBar = new JProgressBar();
        final BoundedRangeModel model = jProgressBar.getModel();

        JButton jButton = new JButton("Simulate Progress");
        jButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ProgressSimulatorSwingWoker progressSimulatorSwingWoker = new ProgressSimulatorSwingWoker(model);
                progressSimulatorSwingWoker.execute();

            }
        });

        contentPane.add(jProgressBar, BorderLayout.CENTER);
        contentPane.add(jButton, BorderLayout.SOUTH);

        jFrame.setVisible(true);
    }
}

关于java - 保存到数据库使按钮无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925741/

相关文章:

java - 如何围绕框布局制作 JScrollpane

java - 如何通过传递数据从另一个 Activity 调用方法?

java - 以编程方式一次又一次地运行 TestNG 测试

mysql - 在表中插入行时的外键约束

java - Netbeans 平台布局

java - JTable 模型上的计算模式

java - Firestore SetOptions.mergeFields 不存储字段

java - 如何使用 Mockito 模拟 void 方法

mysql - Wordpress,第二个 mySQL 数据库的自定义查询字符串,以及漂亮的永久链接

php - 选择具有动态内容的 MySQL 表