Java:使Jframe不水平滚动,以及JTextArea
我有一个名为“Console”的类,具有以下结构:
public Console(Game game) {
super(new GridBagLayout());
m_game = game;
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(20, 75);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
add(textField, c);
}
然后是我的 Game 类中的一个方法:
public void createAndShowGUI() {
JFrame frame = new JFrame("My game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(newConsole);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
}
我遇到的问题是我不希望滚动窗格能够水平滚动,只能垂直滚动。当我向文本区域添加太大而无法容纳在窗口中的内容时,会出现水平滚动条。有没有办法可以防止水平滚动,而只是让文本区域打印出太大而无法容纳下一行的内容?
示例:(
示例文本区域在需要允许水平滚动之前只能容纳 20 个字符)
而不是
Hello, my name is Bob.
出现此
Hello, my name is B
ob.
I have a class called "Console", with the following structure:
public Console(Game game) {
super(new GridBagLayout());
m_game = game;
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(20, 75);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
add(textField, c);
}
And then a method in my Game class:
public void createAndShowGUI() {
JFrame frame = new JFrame("My game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(newConsole);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
}
The problem I'm having, is I don't want the Scroll Pane to be able to scroll horizontally, only vertically. The horizontal scrollbar appears when I append something to the Text Area that's too large to fit in the window. Is there a way I can prevent horizontal scrolling, and instead just have the Text Area print out whatever's too large to fit on the next line?
Example:
(The example Text Area can only fit 20 characters before it needs to allow horizontal scrolling)
Instead of
Hello, my name is Bob.
This would appear
Hello, my name is B
ob.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以设置 JScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) 以确保永远不会出现水平滚动。此外,您的textArea将需要
JTextArea.setWrapStyleWord(true)
和JTextArea.setLineWrap(true)
;You can set
JScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
to ensure there is never a horizontal scroll. In addition, your textArea will needJTextArea.setWrapStyleWord(true)
andJTextArea.setLineWrap(true)
;