我有一个名为“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);
}
我遇到的问题是,我不希望滚动 Pane 能够水平滚动,只能垂直滚动。当我将某些内容附加到太大而无法容纳在窗口中的文本区域时,会出现水平滚动条。有没有一种方法可以防止水平滚动,而只是让文本区域打印出太大而无法放在下一行的内容?
例子:
(示例文本区域只能容纳 20 个字符,然后才需要允许水平滚动)
代替
Hello, my name is Bob.
这会出现
Hello, my name is B
ob.
最佳答案
您可以设置 JScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
以确保永远不会出现水平滚动。此外,您的 textArea 将需要 JTextArea.setWrapStyleWord(true)
和 JTextArea.setLineWrap(true)
;
关于Java:使 Jframe 不水平滚动,和 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8363261/