mkwilfreid
mkwilfreid

Reputation: 128

Saving to database makes button unresponsive

Good day . i want to insert to the database by using the pepraredStatement . however whenever i'm adding the database part (connection and pepraredStatement ) the 'UPLOAD' button goes unresponsive . but when i remove anything related to the database , all my buttons are working . you can find here the code http://pastebin.com/euKdWhr2 .

I will really appreciate any help or suggestion . probably i'm missing something on the database part .

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)
                    {

                    }

Upvotes: 2

Views: 77

Answers (1)

Ren&#233; Link
Ren&#233; Link

Reputation: 51383

The actionPerformed() method is invoked by the ui thread. If you do long running task in this thread the ui will be unresponsive, because the ui thread can not do ui work anymore like repaint the ui or just handling user input.

Think about using a SwingWorker and reading the tutorial about concurrency in java.

EDIT

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

Here is a working example of how to a SwingWorker and long running background tasks work.

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);
    }
}

Upvotes: 6

Related Questions