我正在使用 JTextPane 并试图让文本横向移动,而不是像 JTextField 这样的换行符。我尝试过搜索和查看 JTextPane 的 API,但没有发现任何有用的东西。有人可以告诉我某种可以帮助我的方法或过程(可以在主类中使用)吗?谢谢!
PS 我知道使用 JScrollPane,但我想避免这种情况,因为我希望 JTextPane 尽可能看起来像 JTextField。
我正在使用 JTextPane 并试图让文本横向移动,而不是像 JTextField 这样的换行符。我尝试过搜索和查看 JTextPane 的 API,但没有发现任何有用的东西。有人可以告诉我某种可以帮助我的方法或过程(可以在主类中使用)吗?谢谢!
PS 我知道使用 JScrollPane,但我想避免这种情况,因为我希望 JTextPane 尽可能看起来像 JTextField。
JTextPane textPane = new JTextPane();
JPanel noWrapPanel = new JPanel( new BorderLayout() );
noWrapPanel.add( textPane );
JScrollPane scrollPane = new JScrollPane( noWrapPanel );
加:
JScrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);
JScrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
编辑:
没有解决方案 JScrollPane
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.plaf.ComponentUI;
import javax.swing.text.StyledDocument;
public class NonWrappingTextPane extends JTextPane {
public NonWrappingTextPane() {
super();
}
public NonWrappingTextPane(StyledDocument doc) {
super(doc);
}
// Override getScrollableTracksViewportWidth
// to preserve the full width of the text
@Override
public boolean getScrollableTracksViewportWidth() {
Component parent = getParent();
ComponentUI ui = this.getUI();
return parent != null ? (ui.getPreferredSize(this).width <= parent.getSize().width) : true;
}
// Test method
public static void main(String[] args) {
String content = "The plaque on the Apollo 11 Lunar Module\n"
+ "\"Eagle\" reads:\n\n"
+ "\"Here men from the planet Earth first\n"
+ "set foot upon the Moon, July, 1969 AD\n"
+ "We came in peace for all mankind.\"\n\n"
+ "It is signed by the astronauts and the\n"
+ "President of the United States.";
JFrame f = new JFrame("Non-wrapping Text Pane Example");
JPanel p = new JPanel();
NonWrappingTextPane nwtp = new NonWrappingTextPane();
nwtp.setText(content);
p.add(nwtp);
f.getContentPane().setLayout(new GridLayout(2, 1));
f.getContentPane().add(p);
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}