Kerv
Kerv

Reputation: 179

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

Upvotes: 0

Views: 1760

Answers (2)

fujy
fujy

Reputation: 5264

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

Upvotes: 1

Nambi
Nambi

Reputation: 12042

use the StringBuilder(or) StringBufferto append message by line by line

{      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();
      StringBuilder str =new StringBuilder();

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

             str.append(message+"\n");
            }
            JOptionPane.showMessageDialog(null, str);

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

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

Upvotes: 1

Related Questions