gpt4 book ai didi

java - 使 JTextPane 的文本横向移动而不是换行

转载 作者:行者123 更新时间:2023-11-30 04:32:14 28 4
gpt4 key购买 nike

我正在使用 JTextPane,并尝试使文本横向移动,而不是像 JTextField 那样使用换行符。我尝试过搜索和查看 JTextPane 的 API,但没有找到任何有用的东西。有人可以向我展示某种可以帮助我的方法或过程(可以在主类中使用)吗?谢谢你!

附注我知道使用 JScrollPane,但我想避免这种情况,因为我希望 JTextPane 看起来尽可能像 JTextField。

最佳答案

JTextPane textPane = new JTextPane();
JPanel noWrapPanel = new JPanel( new BorderLayout() );
noWrapPanel.add( textPane );
JScrollPane scrollPane = new JScrollPane( noWrapPanel );

Solution Source

加上:

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);
}
}

关于java - 使 JTextPane 的文本横向移动而不是换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368151/

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