简体   繁体   中英

How Read from Text File to JLabel or JTextArea?

I'm trying to create a popup window that goes something like this:

Number of Games Played: 2
Total Score: 10
Average Score: 5

I have the numbers 2, 10, and 5 stored inside of a text file. I just want to be able to read the numbers from the text file into a (and this is where I get confused) a JLabel or a JTextArea? I also want to be able to clear the scores and reset them all to 0. Which I don't think should be too hard, but I could be wrong. Should I be storing the numbers into an ArrayList when I read them in?

Here is the code I have so far:

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;

public class HistoryPopUp {

    JFrame history;
    JPanel panel;
    JLabel numGames, totalScore, avgScore;
    JTextArea games,score,aScore;
    JButton clearHistory;

    HistoryPopUp(){
        history = new JFrame();
        panel = new JPanel(new GridLayout(3, 1));
        numGames = new JLabel("Number of Games Played: ");
        totalScore = new JLabel("Total Score: ");
        avgScore = new JLabel("Average Score: ");
        games = new JTextArea();
        score = new JTextArea();
        aScore = new JTextArea();


        clearHistory = new JButton();

        try {
            String textLine;
            FileReader fr = new FileReader("history.txt");
            BufferedReader reader = new BufferedReader(fr);
            while((textLine=reader.readLine()) != null){
                textLine = reader.readLine();
                games.read(reader,"Something");
                score.read(reader, "seomthing");
                aScore.read(reader,"balh");
            }

            reader.close();

        }catch(IOException ex){
                System.out.println("ABORT! YOU KILLED IT!!");
            }

        history.pack();
        history.setVisible(true);

        panel.add(games);
        panel.add(score);
        panel.add(aScore);

        JOptionPane.showMessageDialog(null, panel, "History of Games Played", JOptionPane.PLAIN_MESSAGE);

    }
}

EDIT: Formatting

The problem you're having is you have 4 pieces of code all trying to read from the same pool of data, it's unlikely that score or aScore will have any data in the reader to read once games has finished

If you just want to use JLabel s you could do something like this...

String[] headers = {"Number of Games Played:", "Total Score:", "Average Score:"};
JLabel[] labels = new JLabel[3];
for (int index = 0; index < labels.length; index++) {
    labels[index] = new JLabel();
    // Add label to screen
}

try (BufferedReader br = new BufferedReader(new FileReader(new File("history.txt")))) {
    String text = null;
    int lineCount = 0;
    while ((text = br.readLine()) != null && lineCount < 3) {
        System.out.println(text);
        labels[lineCount].setText(headers[lineCount] + " " + text);
        lineCount++;
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

If you want to use a JTextArea , you could do something like this...

String[] headers = {"Number of Games Played:", "Total Score:", "Average Score:"};
JTextArea textArea = new JTextArea(3, 20);
// Add text area to container

try (BufferedReader br = new BufferedReader(new FileReader(new File("history.txt")))) {
    String text = null;
    int lineCount = 0;
    while ((text = br.readLine()) != null && lineCount < 3) {
        System.out.println(text);
        textArea.append(headers[lineCount] + " " + text + "\n");
        lineCount++;
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

You could also use an array of JTextField s in a similar way

Don't do that.

Do not mix "persistence" (information is saved in a file) with "presentation".

Instead; read about Swing document models; or using the "model view controller" approach.

But well, from the code you have written ... it seems that you are still having problems with very basic elements of Swing UI. The point is: there is javadoc; and excellent tutorials from Oracle. Don't expect other people to explain to you how to use them in detail. What I am saying is: first learn how to use the various UI elements; one by one; to understand how you get data into them; and how that information will then look like.

Then, when you understand the UI elements; think about a reasonable way to unpersist your data; and get it into your UI elements (and as said: doing all of that in the same piece of code is bad design; which should be avoided).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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