调整具有固定宽度的长句的对话框消息(JOptionPane)

我正在尝试使用超链接调整长句的对话框( JOptionPane )的高度。

我的代码是……

 public class DialogTest { public static void main(String[] args) throws Exception { JTextPane jtp = new JTextPane(); Document doc = jtp.getDocument(); for (int i = 0; i < 50; i++) { doc.insertString(doc.getLength(), " Hello Java World ", new SimpleAttributeSet()); if ((3 == i) || (7 == i) || (15 == i)) { doc.insertString(doc.getLength(), " Hello Java World ", new SimpleAttributeSet()); SimpleAttributeSet attrs = new SimpleAttributeSet(); StyleConstants.setUnderline(attrs, true); StyleConstants.setForeground(attrs, Color.BLUE); String text = "www.google.com"; URL url = new URL("http://" + text); attrs.addAttribute(HTML.Attribute.HREF, url.toString()); doc.insertString(doc.getLength(), text, attrs); } } JScrollPane jsp = new JScrollPane(jtp); jsp.setPreferredSize(new Dimension(480, 150)); jsp.setBorder(null); JOptionPane.showMessageDialog(null, jsp, "Title", JOptionPane.INFORMATION_MESSAGE); }} 

如果我没有设置首选大小,那么该对话框将会很长,并且它不可读。 所以,我想将宽度修正为480。

而且,我想调整高度取决于文本的长度。

如果我运行此代码,我会看到垂直滚动条。 但我不想显示滚动条并调整对话框的高度。

要修复宽度并调整高度,我个人使用这个技巧:使用setSize修复任意高度和目标宽度,然后使用getPreferredSize()获得预期高度:

 jtp.setSize(new Dimension(480, 10)); jtp.setPreferredSize(new Dimension(480, jtp.getPreferredSize().height)); 

完整的代码是:

 public class DialogTest { public static void main(String[] args) throws Exception { JTextPane jtp = new JTextPane(); Document doc = jtp.getDocument(); for (int i = 0; i < 50; i++) { doc.insertString(doc.getLength(), " Hello Java World ", new SimpleAttributeSet()); if ((3 == i) || (7 == i) || (15 == i)) { doc.insertString(doc.getLength(), " Hello Java World ", new SimpleAttributeSet()); SimpleAttributeSet attrs = new SimpleAttributeSet(); StyleConstants.setUnderline(attrs, true); StyleConstants.setForeground(attrs, Color.BLUE); String text = "www.google.com"; URL url = new URL("http://" + text); attrs.addAttribute(HTML.Attribute.HREF, url.toString()); doc.insertString(doc.getLength(), text, attrs); } } //JScrollPane jsp = new JScrollPane(jtp); //jsp.setPreferredSize(new Dimension(480, 150)); //jsp.setBorder(null); jtp.setSize(new Dimension(480, 10)); jtp.setPreferredSize(new Dimension(480, jtp.getPreferredSize().height)); //JOptionPane.showMessageDialog(null, jsp, "Title", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, jtp, "Title", JOptionPane.INFORMATION_MESSAGE); }} 

要调整JOptionPane的大小,请使用以下URL中显示的重写类: –

ModifiableJOptionPane