gpt4 book ai didi

java - 为固定宽度的长句调整对话框消息 (JOptionPane) 的大小

转载 作者:搜寻专家 更新时间:2023-10-31 20:20:29 26 4
gpt4 key购买 nike

我正在尝试为带有超链接的长句调整对话框 (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);
}}

关于java - 为固定宽度的长句调整对话框消息 (JOptionPane) 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22072975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com