2011-10-08 32 views
6
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()); 
     } 

Cuando hay un error, muestra un cuadro de mensaje JOptionPane largo que es más largo que el ancho de la pantalla de la computadora. ¿Cómo puedo dividir e.toString() en dos o más partes?Para romper un mensaje en dos o más líneas en JOptionPane

+1

Put nueva línea (\ n). – adatapost

Respuesta

21

enter image description here

import java.awt.*; 
import javax.swing.*; 

class FixedWidthLabel { 

    public static void main(String[] args) { 

     Runnable r = new Runnable() { 
      public void run() { 
       String pt1 = "<html><body width='"; 
       String pt2 = 
        "'><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 " + 
        ""; 
       String pt3 = " pixels."; 

       JPanel p = new JPanel(new BorderLayout()); 

       int width = 175; 
       String s = pt1 + width + pt2 + width + pt3 ; 

       JOptionPane.showMessageDialog(null, s); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 
3

Tienes que usar \n para romper la cadena en diferentes líneas. O usted puede:

Otra forma de realizar esta tarea es una subclase de la clase JOptionPane y anular la getMaxCharactersPerLineCount para que vuelva el número de caracteres que se desea representar como máximo para una línea de texto .

http://ninopriore.com/2009/07/12/the-java-joptionpane-class/ (enlace muerto, consulte archived copy).

+0

El 'line.separator' (que podría no ser' \ n' BTW), solo funcionará si el texto se coloca en un componente de varias líneas, como 'JTextArea'. El componente utilizado para mostrar una "Cadena" en un panel de opciones es un 'JLabel'. –

0

Estoy fijando un límite de caracteres, a continuación, busque el último carácter de espacio en ese ambiente y escribir un "\ n" allí. (O fuerzo "\ n" si no hay carácter de espacio). De esta manera:

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

Y la llamo así en el (intento) Soporte de -catch:

JOptionPane.showMessageDialog(
    null, 
    "Could not create table 't_rennwagen'.\n\n" 
    + breakLongString(stmt.getWarnings().toString(), 100), 
    "SQL Error", 
    JOptionPane.ERROR_MESSAGE 
); 
1

similares a Andrew Thomson 's respuesta, la siguiente nos dejó código se carga un archivo HTML de la directorio raíz del proyecto y mostrarlo en un JOptionPane. Tenga en cuenta que debe agregar un Maven dependency for Apache Commons IO. También el uso de HTMLCompressor es una buena idea si desea leer el código HTML formateado de un archivo sin romper la representación.

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

de este modo que gestione el código HTML mejor que en Strings Java.

No se olvide de crear un archivo llamado document.html con el siguiente contenido:

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

Resultado:

Cuestiones relacionadas