如何使用BufferedReader在JOptionPane中打印多行?

时间:2013-09-14 15:59:43

标签: java swing bufferedreader joptionpane

使用BufferedReader遇到麻烦。我想要的是打印要在我的Java服务器上打印的输入文本(来自我的Android客户端)。使用System.out.println工作正常。但当我把它放在JOptionPane中时,它开始逐个打印在一个对话框上。 (一行=一个对话框,我需要点'确定'以显示不同Joptionpane中的下一行)

我想要的是在一个JOptionPane.showMessageDialog中打印所有行。

这是我的代码:

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

2 个答案:

答案 0 :(得分:1)

如何使用StringBuilder并附加所有消息,然后使用此完整的JOptionPane对象显示StringBuilder

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

 JOptionPane.showMessageDialog(null, s);

答案 1 :(得分:1)

使用StringBuilder(或)StringBuffer逐行追加消息

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