问题描述
我正在开发游戏.在这一部分中,将打开一个新窗口以显示游戏说明.唯一的问题是,当多于20行时,JTextArea仅显示.txt文件的一行.我是这个新手,所以不确定自己缺少什么.谢谢!
I'm working on a game. In this part, a new window opens up to show the game instructions. The only problem is that the JTextArea only shows one line of the .txt file, when there are more than 20 lines. I'm a newbie at this, so I'm not sure what I'm missing. Thanks!
class Instruction extends JFrame
{
private JTextArea read;
private JScrollPane scroll;
Instruction(String x)
{
super(x);
try
{
BufferedReader readers = new BufferedReader (new FileReader("instructions.txt")); //read from file
read = new JTextArea(readers.readLine());
scroll = new JScrollPane(read);
read.setFont(new Font("Comic Sans MS", Font.BOLD, 16)); // change font
read.setEditable(false);
add(read);
}
catch(IOException exception)
{
exception.printStackTrace();
}
}
}
推荐答案
BufferedReader#readLine
仅读取下一行(如果没有更多行要读取,则返回null
)
BufferedReader#readLine
only reads the next line (or returns null
if there are no more lines to be read)
如果仔细看一下JavaDoc,您会发现 JTextArea
从JTextComponent
继承了read(Reader, Object)
,它将解决(大多数)问题
If you take a closer look at the JavaDoc, you will find that JTextArea
inherited read(Reader, Object)
from JTextComponent
, which will solve (most) of your problems
更多类似的东西
read = new JTextArea();
try (Reader reader = new BufferedReader(new FileReader("instructions.txt"))) {
read.read(reader, null);
} catch (IOException exception) {
exception.printStackTrace();
}
scroll = new JScrollPane(read);
read.setFont(new Font("Comic Sans MS", Font.BOLD, 16)); // change font
read.setEditable(false);
add(read);
可能会实现您想要做的事情
might achieve what you're trying to do
此外,您可能需要致电
read.setLineWrap(true);
read.setWrapStyleWord(true);
如果单词超出该区域的可见边界,则允许自动换行.
to allow automatic wrapping of words if they extend beyond the visible boundaries of the area.
这篇关于Java Swing JTextArea无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!