Search code examples
javasqljoptionpane

Sql query that outputs to ONE Joptionpane


String sql = "SELECT TOP 10 id, Trailer, Block, Location, Day, SetTime, Comment FROM TrailerLocation" + " ORDER BY id DESC";

   rs = st.executeQuery(sql);

   while(rs.next()){
        //Retrieve by column name
            int id  = rs.getInt("id");
        String trailer = rs.getString("Trailer");
        String block = rs.getString("Block");
        String location = rs.getString("Location");
        String date = rs.getString("Day");
        String comment = rs.getString("Comment");

        //Display values
        JOptionPane.showMessageDialog(null,
              "ID: " + id
            + ", Trailer: " + trailer 
            + ", Block: " + block 
            + ", Location: " + location 
            + ", Date & Time: " + date 
            + ", Comment: " + comment);


    }

I want the Joptionpane to only display once with all the data not ten times.


Solution

  • You could move the JOptionPane.showMessageDialog(null, ... ) after the while loop. And, in the while loop, add the informations you want in one unique string which you will display in you JOptionPane.

    rs = st.executeQuery(sql);
    StringBuilder str = new StringBuilder();
    while(rs.next()){
    
        //Retrieve by column name
    
        str.append("ID: " + rs.getInt("id"));
        str.append(", Trailer: " + rs.getString("Trailer"));
        str.append(", Block: " + rs.getString("Block"));
        str.append(", Location: " + rs.getString("Location"));
        str.append(", Date: " + rs.getString("Day"));
        str.append(", Comment: " + rs.getString("Comment"));
    
        //new line
        str.append("\n");
    }
    
    JOptionPane.showMessageDialog(null,str.toString());