I have made a game using CardLayout and have one JPanel for the leaderboard. In leaderboard, I read two files (one with names, one with times), sort them and draw the top 5 fastest times like this:
private void setBoard(){
reset();
try{
br = new BufferedReader (new FileReader("username.txt"));
accounts = ""+br.readLine().trim();
arrNames = accounts.split(" ");
br.close();
br = new BufferedReader (new FileReader("time.txt"));
allTimes = ""+br.readLine().trim();
arrTimesTemp = allTimes.split(" ");
arrTime = new double [arrTimesTemp.length];
br.close();
} catch (Exception er){
System.out.print("Error" + er);
}
for (int i=0;i<arrTime.length;i++)
arrTime[i]=Double.parseDouble(arrTimesTemp[i]);;
scores = new Score[arrTime.length];
for (int i=0;i<arrTime.length;i++)
scores[i] = new Score (arrNames[i],arrTime[i]);
Arrays.sort(scores, new MyComparator());
System.out.println("\n\n\n");
for (int i=0;i<arrTime.length;i++)
System.out.println(arrTime[i]+" "+arrNames[i]);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(title, getWidth()/2-title.getWidth()/2+10, 125, this);
g.drawImage(txt, getWidth()/2-txt.getWidth()/2+10, 250, this);
setBoard();
g.setFont(new Font("Serif", Font.PLAIN, 25));
g.setColor(Color.white);
for (int i=0;i<5;i++){
g.drawString((i+1)+"-", numX, lineY);
g.drawString(scores[i].getName(), nameX, lineY);
g.drawString(""+scores[i].getTime(), timeX, lineY);
g.drawString("s", 515, lineY);
lineY+=40;
}
}
There is no problem the first time I open the leaderboard. However, if I return to the menu and then come back to the leaderboard, the strings to not draw, but the images do. I also so not get any errors. I can't figure out why this is happening.
How I return to menu:
public void actionPerformed(ActionEvent e) {
if (e.getSource()==back)
RunGame.card.first(RunGame.c);
}
How I go to leaderboard from menu:
else if (e.getSource()==d) //d is a JButton
RunGame.card.show(RunGame.c,"Leaderboard");