在一个应用程序中,我使用不可编辑的 JEditorPanes 作为一种通用的 UI 小部件,它可以显示一些复杂的内容(HTML 可以解决问题)、换行和捕捉鼠标点击。不确定 JEditorPane 是否是一个不错的选择,因此请随意提出替代方案。
以下示例代码运行良好:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class Main {
private static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
for (int i = 0; i < 3; i++) {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
editorPane.setContentType("text/html");
String text =
"This is <b>item #" + i + "</b>." +
" It's got text on it that should be wrapped."
;
editorPane.setText(text);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = i;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weightx = 1.0;
constraints.insets.bottom = 5;
panel.add(editorPane, constraints);
}
return panel;
}
public static void main(String[] args) {
JPanel panel = createPanel();
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setLocation(200, 200);
// Change this to switch between examples
boolean useScrollPane = false;
if (useScrollPane) {
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setViewportView(panel);
frame.add(scrollPane);
}
else {
frame.add(panel);
}
frame.setVisible(true);
}
}
并产生以下内容:
但是,我可能有大量这些并且可以使用垂直滚动条。
所以我把整个东西放在一个 JScrollPane 中(将useScrollPane
变量更改true
为示例代码中的以查看此版本)。
如果我缩小窗口高度,这会给我一个垂直滚动条,但问题是现在文本不再被包装:
所以问题是:如何同时获得文本换行和垂直滚动条?
如您所见,我禁用了水平滚动条,但并没有太大帮助。
PS。我对 Swing 没有太多经验,所以如果你在这段代码中看到一些初学者 WTF,请指出:)