在JOptionPane中断两行或多行中的消息

时间:2011-10-08 10:59:20

标签: java swing newline joptionpane

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()分成两个或多个部分。

4 个答案:

答案 0 :(得分:23)

enter image description here

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

答案 1 :(得分:3)

您必须使用\n来打破不同行中的字符串。或者你可以:

  

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

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

答案 2 :(得分:1)

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 Strings更好地管理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.

结果:

答案 3 :(得分:0)

我正在设置字符限制,然后在该环境中搜索最后一个空格字符并在那里写一个“\ 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
);