Java Swing JTextArea not working

2019-09-20 00:44发布

问题:

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

回答1:

BufferedReader#readLine only reads the next line (or returns null if there are no more lines to be read)

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

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.



回答2:

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