Search code examples
javamysqlswingactionlistenerjoptionpane

How to pass a ResultSet response to a JOptionPane showMessageDialog


The Oracle "How to Make a Dialog" tutorial did not help me, nor have any other posts I've seen, as they don't solve the problem of passing values to a showMessageDialog..

I have a Java Swing application that looks like this:

GUI Screenshot

The user enters information into each of the three fields which become incorporated into a MySQL query when the user presses the button, "Fetch Tweets".

After pressing the button, I want to return the the row count to a showMessageDialog, giving the user an option to proceed or not.

Problem: I cannot figure out how to pass the ResultSet value to the showMessageDialog. Do I need to set an Action Listener on the JOptionPane? If so, how do you manage the timing?

My showMessageDialog looks as follows. As you can see, the value of "0" is incorrect.

showMessageDialog Screenshot

Code Snippet of my JButton and Associated Action Listener:

JButton btnFetch = new JButton("Fetch Tweets!");
    btnFetch.setBackground(new Color(255, 153, 51));
    btnFetch.setForeground(new Color(0, 0, 128));
    btnFetch.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            app.Query_Variable = queryText.getText();
            app.Start_Date = startText.getText();
            app.End_Date = endText.getText();

            try {
                app.getTweetCount();
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }

            response = new ResponseOption(app.Tweet_Count);

            /*
            try {
                app.runApplication();

            } catch (InstantiationException | IllegalAccessException
                    | ClassNotFoundException | ParseException
                    | SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }*/

            JOptionPane.showMessageDialog(frame, "Find your file at " + app.Printed_Filename);                  
        }
    });

I created a class for the showMessageDialog called "ResponseOption", thinking this was needed to initialize the dialog. However, the dialog gets displayed without containing the ResultSet value...

public class ResponseOption {       
    int RowCount;       
    Object[] options = {"Yes, Please.", 
                        "No, Thanks."};     
    String question = "There are " + RowCount + " Tweets. Do you want to print them?";      
    int n = JOptionPane.showOptionDialog(frame,
            "There are " + X + " Tweets. Do you want to print them?",
            "Question",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,       
            null,                               // do not use custom icon
            options,                            // titles of buttons
            options[0]);                        // default button title


    public ResponseOption(int Rowcount) {           
        this.RowCount = RowCount;
    }       
}

getTweetCount() Code: --- This Code is fine.

public int getTweetCount() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    // create a mysql database connection
    String myDriver = "com.mysql.jdbc.Driver";
    String myUrl = "jdbc:mysql://localhost:3306/?";
    Class.forName(myDriver).newInstance();
    Connection conn = DriverManager.getConnection(myUrl, User, Password);
    PreparedStatement setNames = conn.prepareStatement("SET NAMES 'utf8mb4'");
    setNames.execute();

    // fetch tweet count
    String CountSQL = "SELECT count(*) "
                    + "FROM test.tweet "
                    + "WHERE text LIKE '%" + Query_Variable + "%' "
                    + "AND created_at BETWEEN '" + Start_Date + "' AND '" + End_Date + "';";

    PreparedStatement CountPS = conn.prepareStatement(CountSQL);
    ResultSet CountRS = CountPS.executeQuery();

    if (CountRS.next()) {           
        Tweet_Count = CountRS.getInt(1);
    }

    System.out.println("Tweet count = " + Tweet_Count);     
    return Tweet_Count;     
}

Solution

  • One possible improvement, change ResponseOption so that the JOptionPane is not called on object creation, but rather in the constructor where the tweet count number is available:

    public ResponseOption(int rowCount, JFrame frame) {
    
        this.rowCount = rowCount;
        String question = "There are " + rowCount + " Tweets. Do you want to print them?";
        n = JOptionPane.showOptionDialog(frame,
                question,
                "Question",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,       
                null,                               
                options,                            
                options[0]); 
        // do something with n here?
    }
    

    Note that previously you call the JOptionPane in the variable declaration section. This gets called when an object is first created and before the constructor is called, and that was messing you up. Myself, I wonder if all this can be wrapped up in a single static method.