java JOptionPane 中的文本换行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14011492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Text wrap in JOptionPane?
提问by laksys
I'm using following code to display error message in my swing application
我正在使用以下代码在我的 Swing 应用程序中显示错误消息
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?
错误对话框的宽度根据消息而变长。有没有办法包装错误信息?
回答by Andrew Thompson
A JOptionPane
will use a JLabel
to display text by default. A label will format HTML. Set the maximum width in CSS.
AJOptionPane
将JLabel
默认使用 a来显示文本。标签将格式化 HTML。在 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
.
更一般地说,请参阅如何在 Swing 组件中使用 HTML,以及在JLabel
.
回答by trashgod
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 Panesand How to Make Dialogsfor examples.
添加您的邮件文本组件可以包装,例如JEditorPane
,然后指定编辑窗格为message
您JOptionPane
。有关示例,请参阅如何使用编辑器窗格和文本窗格以及如何制作对话框。
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);
}
}
}));