Разбить сообщение на две или более строки в JOptionPane - PullRequest
8 голосов
/ 08 октября 2011
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 ]

23 голосов
/ 10 октября 2011

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);
    }
}
3 голосов
/ 08 октября 2011

Вы должны использовать \n, чтобы разбить строку на разные строки. Или вы можете:

Еще один способ выполнить эту задачу - создать подкласс JOptionPane. класс и переопределить getMaxCharactersPerLineCount, чтобы он возвращал количество символов, которое вы хотите представить как максимум для одна строка текста.

http://ninopriore.com/2009/07/12/the-java-joptionpane-class/ (недействительная ссылка, см. архивная копия ).

1 голос
/ 23 сентября 2015

Аналогично ответу Эндрю Томсона , следующий код позволяет загрузить файл HTML из корневого каталога проекта и отобразить его в JOptionPane. Обратите внимание, что вам нужно добавить зависимость Maven для Apache Commons IO . Также рекомендуется использовать HTMLCompressor, если вы хотите прочитать отформатированный HTML-код из файла без прерывания рендеринга.

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

Это позволяет вам управлять кодом HTML лучше, чем в строках Java.

Не забудьте создать файл с именем 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.

Результат:

0 голосов
/ 23 февраля 2014

Я устанавливаю ограничение на количество символов, затем ищу последний пробельный символ в этой среде и пишу "\ 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
);
...