To break a message in two or more lines in JOptionPane

∥☆過路亽.° 提交于 2019-11-29 18:56:46

问题


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.


回答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:


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




回答3:


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:




回答4:


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


来源:https://stackoverflow.com/questions/7696347/to-break-a-message-in-two-or-more-lines-in-joptionpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!