Search code examples
javaswingbufferedreaderjoptionpane

How to print multiple lines in JOptionPane using BufferedReader?


Having a trouble here using BufferedReader. What I want is to print the input text (From my android client) that is to be printed on my Java Server. Using System.out.println works fine. But when I put it in JOptionPane, it started to print on a dialog box one by one. (One line = one dialog box, I need to hit 'ok' to show the next line in a different Joptionpane)

What I want to happen is to print all the lines in just one JOptionPane.showMessageDialog.

Here is my code:

try
            {
                clientSocket = serverSocket.accept(); // accept the client connection
                inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader); // get the client message
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Calendar cal = Calendar.getInstance();

                while ((message = bufferedReader.readLine()) != null) {

                JOptionPane.showMessageDialog(null, message);

                }

                inputStreamReader.close();
                clientSocket.close();

            } catch (IOException ex)
            {
                System.out.println("Problem in message reading");
            }

Solution

  • How about using a StringBuilder and append to it all messages then display JOptionPane with this complete StringBuilder object

     StringBuilder s = new StringBuilder();
     while ((message = bufferedReader.readLine()) != null) {
         s.append(message+"\n");
     }
    
     JOptionPane.showMessageDialog(null, s);