2

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

                    }
mkwilfreid
  • 128
  • 2
  • 12
  • Never catch exceptions without handling them. Or you rethrow them or, at the very minimum, log them. Also, do not perform non-trivial logic in the thread that launches the listener; if your logic may be not instantaneous, then you should launch a different thread to process it. – SJuan76 Nov 14 '14 at 08:27
  • Swing is single thread, any long running or blocking code will stop the UI from been able to update, see [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) and [Worker Threads and SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) – MadProgrammer Nov 14 '14 at 08:28
  • Why do you have `catch(SQLException e) {}` and `catch(Exception e) {}`? If something goes wrong, don't you want to know what went wrong? – user253751 Nov 14 '14 at 08:31

1 Answers1

6

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);
    }
}
Community
  • 1
  • 1
René Link
  • 48,224
  • 13
  • 108
  • 140
  • 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 – mkwilfreid Nov 14 '14 at 08:35
  • @mkwilfreid you're welcome... hope it helps you to adapt it to our needs – René Link Nov 14 '14 at 09:11
  • i really hoped so, but i couldn't manage to get it work, i got errors. i can't use this final BoundedRangeModel model = uploadBtn.getModel(); seems – mkwilfreid Nov 14 '14 at 09:17