Text wrap in JOptionPane?

前端 未结 2 692
情歌与酒
情歌与酒 2020-11-22 15:51

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

try {
    ...
} catch (Exception exp) {
    JOptionPane.showMessageDialog(this, ex         


        
相关标签:
2条回答
  • 2020-11-22 16:07

    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.

    error image

    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);
            }
        }
    }));
    
    0 讨论(0)
  • 2020-11-22 16:12

    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.

    0 讨论(0)
提交回复
热议问题