Java Swing JTextArea not working

前端 未结 2 1449
后悔当初
后悔当初 2021-01-29 09:18

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 ther

相关标签:
2条回答
  • 2021-01-29 09:48

    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.

    0 讨论(0)
  • 2021-01-29 09:49

    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());
    
    0 讨论(0)
提交回复
热议问题