简体   繁体   English

Java Swing JTextArea无法正常工作

[英]Java Swing JTextArea not working

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. 唯一的问题是,当多于20行时,JTextArea仅显示.txt文件的一行。 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 only reads the next line (or returns null if there are no more lines to be read) BufferedReader#readLine仅读取下一行(如果没有更多行要读取,则返回null

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 如果仔细看一下JavaDoc,您会发现JTextArea继承了JTextComponent read(Reader, Object) ,它将解决(大多数)问题

Something more along the lines of 更像是

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 可能会实现您想要做的事情

Also, you might need to call 另外,您可能需要致电

read.setLineWrap(true);
read.setWrapStyleWord(true);

to allow automatic wrapping of words if they extend beyond the visible boundaries of the area. 如果单词超出了该区域的可见边界,则可以自动换行。

You are reading only one line from a file. 您仅从文件读取一行。 Try using this instead to load entire file. 尝试使用它代替加载整个文件。

List<String> lines;
try {
    lines = Files.readAllLines();
} catch (IOException ex) {
    ex.printStackTrace();
}

StringBuilder text = new StringBuilder();
for (String line : lines) {
    text.append(line);
}

read = new JTextArea(text.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM