To break a message in two or more lines in JOptionPane

前端 未结 4 1336
礼貌的吻别
礼貌的吻别 2021-01-02 09:48
try {
        Class.forName(\"com.microsoft.sqlserver.jdbc.SQLServerDriver\");
        String connectionUrl = \"jdbc:sqlserver://\"+hostName.getText()+\";\" +
               


        
4条回答
  •  滥情空心
    2021-01-02 10:45

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

提交回复
热议问题