Kencru
Kencru

Reputation: 11

How to set JLabel value from TextFile?

I have a file named easyscore.txt

Text is written in the notepad once the player enters his name in this program.

Here's my code:

JOptionPane.showMessageDialog(this, "You win the easy difficulty :D", "Congrats", JOptionPane.INFORMATION_MESSAGE, null);
JFrame frame = new JFrame();
String easyname=JOptionPane.showInputDialog(frame, "Enter player name"); 
try {
      FileWriter easyscore = new FileWriter("easyscore.txt");
      PrintWriter peasyscore = new PrintWriter(easyscore); 
      peasyscore.println(easyname);
      peasyscore.close();
}
catch(IOException e) {
    out.println("ERROR!");
}  
MinesweeperXHighscore MinesweeperXHighscore = new MinesweeperXHighscore();
MinesweeperXHighscore.setVisible(true);

The other java class MinesweeperXHighscore contains labels.

From the start the labels will be empty (no text) and the name will be added to the label once the player entered it at the end of my game.

MinesweeperXHighscore Code:

private void Easyscorer() {
    String n1;
    try {
        FileReader feasy = new FileReader("easyscore.txt");
        BufferedReader breasy = new BufferedReader(feasy);
        n1 = breasy.readLine();
        while (n1 != null) {
            INVILABELEASY.setText(n1);
        }
        breasy.close();
    }
    catch(IOException e) {
        out.println("ERROR!");
    }
}

where INVILABELEASY is the JLabel that I tested.

I input a username while testing, but the label is still empty.

When I check my text file the name that I entered was there so the problem is that the JLabel is still empty and does not read from the text file well.

Upvotes: 1

Views: 645

Answers (1)

Jad Chahine
Jad Chahine

Reputation: 7149

You just have to change this peace of code:

while(n1!= null)
       {
        INVILABELEASY.setText(n1);
       }

to :

if(n1!= null)
           {
            INVILABELEASY.setText(n1);
           }

Your code is in a infinite loop because n1 is always not null


Here is the easyscore.txt file

enter image description here

And here is the MinesweeperXHighscore java frame

enter image description here

Upvotes: 2

Related Questions