Text wrap in JOptionPane?

时光毁灭记忆、已成空白 提交于 2019-11-26 00:29:15

问题


I\'m using following code to display error message in my swing application

try {
    ...
} catch (Exception exp) {
    JOptionPane.showMessageDialog(this, exp.getMessage(), \"Error\", JOptionPane.ERROR_MESSAGE);
}

The width of the error dialog goes lengthy depending on the message. Is there any way to wrap the error message?


回答1:


A JOptionPane will use a JLabel to display text by default. A label will format HTML. Set the maximum width in CSS.

JOptionPane.showMessageDialog(
    this, 
    "<html><body><p style='width: 200px;'>"+exp.getMessage()+"</p></body></html>", 
    "Error", 
    JOptionPane.ERROR_MESSAGE);

More generally, see How to Use HTML in Swing Components, as well as this simple example of using HTML in JLabel.




回答2:


Add your message to a text component that can wrap, such as JEditorPane, then specify the editor pane as the message to your JOptionPane. See How to Use Editor Panes and Text Panes and How to Make Dialogs for examples.

Addendum: As an alternative to wrapping, consider a line-oriented-approach in a scroll pane, as shown below.

f.add(new JButton(new AbstractAction("Oh noes!") {
    @Override
    public void actionPerformed(ActionEvent action) {
        try {
            throw new UnsupportedOperationException("Not supported yet.");
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder("Error: ");
            sb.append(e.getMessage());
            sb.append("\n");
            for (StackTraceElement ste : e.getStackTrace()) {
                sb.append(ste.toString());
                sb.append("\n");
            }
            JTextArea jta = new JTextArea(sb.toString());
            JScrollPane jsp = new JScrollPane(jta){
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(480, 320);
                }
            };
            JOptionPane.showMessageDialog(
                null, jsp, "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}));


来源:https://stackoverflow.com/questions/14011492/text-wrap-in-joptionpane

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