To break a message in two or more lines in JOption

2019-02-09 07:58发布

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

When there is an error it shows a long JOptionPane message box that is longer than the width of the computer screen. How can I break e.toString() into two or more parts.

4条回答
叼着烟拽天下
2楼-- · 2019-02-09 08:27

I'm setting a character limit, then search for the last space character in that environment and write an "\n" there. (Or I force the "\n" if there is no space character). Like this:

/** 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;
}

And I call it like this in the (try)-catch bracket:

JOptionPane.showMessageDialog(
    null, 
    "Could not create table 't_rennwagen'.\n\n"
    + breakLongString( stmt.getWarnings().toString(), 100 ), 
    "SQL Error", 
    JOptionPane.ERROR_MESSAGE
);
查看更多
唯我独甜
3楼-- · 2019-02-09 08:35

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);
    }
}
查看更多
成全新的幸福
4楼-- · 2019-02-09 08:45

You have to use \n to break the string in different lines. Or you can:

Another way to accomplish this task is to subclass the JOptionPane class and override the getMaxCharactersPerLineCount so that it returns the number of characters that you want to represent as the maximum for one line of text.

http://ninopriore.com/2009/07/12/the-java-joptionpane-class/ (dead link, see archived copy).

查看更多
smile是对你的礼貌
5楼-- · 2019-02-09 08:51

Similar to Andrew Thomson's answer, the following code let's you load an HTML file from the project root directory and display it in a JOptionPane. Note that you need to add a Maven dependency for Apache Commons IO. Also the use of HTMLCompressor is a good idea if you want to read formatted HTML code from a file without breaking the rendering.

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

This let's you manage the HTML code better than in Java Strings.

Don't forget to create a file named document.html with the following content:

<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.

Result:

查看更多
登录 后发表回答