我正在尝试将JLabel的文本设置为应用程序编译中的某些内容,程序编译正常,我检查我的数组以查看值是否存在,但JLabel不会更新。确保初始化JLabel。
FileHandling Class
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.Arrays;
import java.util.List;
public class FileHandling {
private final String getWorkingDirectory = System.getProperty("user.dir"));
private final String filePath = "/src/files/", fileName = "gameStats.json";
private final String fullPath = getWorkingDirectory + filePath + fileName;
private DieIntGUI dieIntGUI = new DieIntGUI("");
private List<String> score;
public void isCreated() throws IOException {
if (!Files.exists(Paths.get(fullPath))) {
Files.createFile(Paths.get(fullPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(fullPath));
bw.write("0|0");
bw.close();
} else {
System.out.printf("File %s already exists\n", fileName);
readFromFile();
}
}
private void readFromFile() {
try {
score = Arrays.asList(Files.readAllLines(Paths.get(fullPath), Charset.defaultCharset()).get(0).split("\\|"));
System.out.println(score);
dieIntGUI.playerWins.setText("Player wins: " + score.get(0).toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
DieIntGUI班
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
public class DieIntGUI extends JFrame {
public DieIntGUI(String title) {
super(title);
setSize(700, 700);
getContentPane().setBackground(Color.white);
setLayout(new BorderLayout());
initComponents();
add(panel);
add(errorMessages, BorderLayout.SOUTH);
setLocationRelativeTo(null);
}
public static void main(String[] args) throws IOException {
DieIntGUI frame = new DieIntGUI("Dice Game");
frame.setVisible(true);
FileHandling handle = new FileHandling();
handle.isCreated();
}
private void initComponents() {
panel = new JPanel();
errorMessages = new JLabel();
playerWins = new JLabel("");
computerWins = new JLabel("");
drawComponents();
}
private void drawComponents() {
GridBagConstraints gbc = new GridBagConstraints();
panel.setLayout(new GridBagLayout());
panel.setSize(700, 700);
panel.setBackground(Color.white);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.insets = new Insets(10,10,10,10);
gbc.anchor = GridBagConstraints.EAST;
panel.add(playerWins, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.EAST;
panel.add(computerWins, gbc);
}
private JPanel panel;
private JLabel errorMessages;
public JLabel playerWins, computerWins;
}