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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Raj Gupta
  • 260
  • 3
  • 6
  • 18

4 Answers4

27

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);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

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

GKFX
  • 1,386
  • 1
  • 11
  • 30
Tobias
  • 9,170
  • 3
  • 24
  • 30
  • The `line.separator` (which might not be `\n` BTW), will only work if the text is put into a multi-line component such as a `JTextArea`. The component used to display a `String` in an option pane is a `JLabel`. – Andrew Thompson Oct 10 '11 at 00:57
1

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:

Community
  • 1
  • 1
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
0

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
);
WoodrowShigeru
  • 1,418
  • 1
  • 18
  • 25