【问题标题】:To break a message in two or more lines in JOptionPane在 JOptionPane 中将消息分成两行或多行
【发布时间】:2011-12-03 12:36:18
【问题描述】:
try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String connectionUrl = "jdbc:sqlserver://"+hostName.getText()+";" +
        "databaseName="+dbName.getText()+";user="+userName.getText()+";password="+password.getText()+";";
        Connection con = DriverManager.getConnection(connectionUrl);
        if(con!=null){JOptionPane.showMessageDialog(this, "Connection Established");}
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, e);
            //System.out.println("SQL Exception: "+ e.toString());
        } catch (ClassNotFoundException cE) {
            //System.out.println("Class Not Found Exception: "+ cE.toString());
             JOptionPane.showMessageDialog(this, cE.toString());
        }

当出现错误时,它会显示一个长于计算机屏幕宽度的 JOptionPane 消息框。如何将 e.toString() 分成两个或多个部分。

【问题讨论】:

    标签: java swing newline joptionpane


    【解决方案1】:

    import javax.swing.*;
    
    class FixedWidthLabel {
    
        public static void main(String[] args) {
            Runnable r = () -> {
                String html = "<html><body width='%1s'><h1>Label Width</h1>"
                    + "<p>Many Swing components support HTML 3.2 &amp; "
                    + "(simple) CSS.  By setting a body width we can cause "
                    + "the component to find the natural height needed to "
                    + "display the component.<br><br>"
                    + "<p>The body width in this text is set to %1s pixels.";
                // change to alter the width 
                int w = 175;
    
                JOptionPane.showMessageDialog(null, String.format(html, w, w));
            };
            SwingUtilities.invokeLater(r);
        }
    }
    

    【讨论】:

    • 你的回答让我有些头疼。谢谢安德鲁。
    【解决方案2】:

    您必须使用\n 将字符串分成不同的行。或者您可以:

    完成此任务的另一种方法是继承 JOptionPane 类并覆盖 getMaxCharactersPerLineCount 使其返回 您要表示为最大值的字符数 一行文字。

    http://ninopriore.com/2009/07/12/the-java-joptionpane-class/(死链接,见archived copy)。

    【讨论】:

    • line.separator(可能不是\n BTW)只有在将文本放入多行组件(例如JTextArea)时才有效。用于在选项窗格中显示String 的组件是JLabel
    【解决方案3】:

    Andrew Thomson 的回答类似,下面的代码让您从项目根目录加载一个HTML 文件并将其显示在JOptionPane 中。请注意,您需要添加一个Maven dependency for Apache Commons IO。此外,如果您想在不破坏渲染的情况下从文件中读取格式化的 HTML 代码,使用 HTMLCompressor 也是一个好主意。

    import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
    import org.apache.commons.io.FileUtils;
    
    import javax.swing.*;
    import java.io.File;
    import java.io.IOException;
    
    public class HTMLRenderingTest
    {
        public static void main(String[] arguments) throws IOException
        {
            String html = FileUtils.readFileToString(new File("document.html"));
            HtmlCompressor compressor = new HtmlCompressor();
            html = compressor.compress(html);
            JOptionPane.showMessageDialog(null, html);
        }
    }
    

    这让您可以比在 Java 字符串中更好地管理 HTML 代码。

    别忘了创建一个名为document.html 的文件,内容如下:

    <html>
    <body width='175'><h1>Label Width</h1>
    
    <p>Many Swing components support HTML 3.2 &amp; (simple) CSS. By setting a body width we can cause the component to find
        the natural height needed to display the component.<br><br>
    
    <p>The body width in this text is set to 175 pixels.
    

    结果:

    【讨论】:

      【解决方案4】:

      我正在设置字符限制,然后在该环境中搜索最后一个空格字符并在那里写一个“\n”。 (或者如果没有空格字符,我会强制使用“\n”)。像这样:

      /** Force-inserts line breaks into an otherwise human-unfriendly long string.
       * */
      private String breakLongString( String input, int charLimit )
      {
          String output = "", rest = input;
          int i = 0;
      
           // validate.
          if ( rest.length() < charLimit ) {
              output = rest;
          }
          else if (  !rest.equals("")  &&  (rest != null)  )  // safety precaution
          {
              do
              {    // search the next index of interest.
                  i = rest.lastIndexOf(" ", charLimit) +1;
                  if ( i == -1 )
                      i = charLimit;
                  if ( i > rest.length() )
                      i = rest.length();
      
                   // break!
                  output += rest.substring(0,i) +"\n";
                  rest = rest.substring(i);
              }
              while (  (rest.length() > charLimit)  );
              output += rest;
          }
      
          return output;
      }
      

      我在 (try)-catch 括号中这样称呼它:

      JOptionPane.showMessageDialog(
          null, 
          "Could not create table 't_rennwagen'.\n\n"
          + breakLongString( stmt.getWarnings().toString(), 100 ), 
          "SQL Error", 
          JOptionPane.ERROR_MESSAGE
      );
      

      【讨论】:

        猜你喜欢
        • 2017-10-03
        • 2015-12-17
        • 1970-01-01
        • 2013-02-12
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        相关资源
        最近更新 更多