我正在使用 Java Swing。最初我想读取一个文件(相当大)。因此,该框架会在文件完成后显示。而我希望首先加载(显示)框架,然后读取文件。
class Passwd {
JFrame jfrm;
// other elements
Passwd() {
start();
// Display frame.
jfrm.setVisible(true);
}
public void start() {
// Create a new JFrame container.
jfrm = new JFrame("Password Predictability & Strength Measure");
// Specify FlowLayout for the layout manager.
//jfrm.setLayout(new FlowLayout());
jfrm.setLayout(null);
// Give the frame an initial size.
jfrm.setSize(450, 300);
// align window to center of screen
jfrm.setLocationRelativeTo(null);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// some elements
File file = new File("file.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// operation
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Passwd();
}
});
}
}
框架显示后如何读取文件?
最佳答案
JFrame 应该立即显示,所以这不是问题。问题是您正在 Swing 事件线程上读取文件,这会阻止其显示 JFrame 的能力。解决方案是不这样做,而是在后台线程中读取文件,例如通过 SwingWorker。这样JFrame就可以畅通无阻的显示,文件的读取也不会干扰Swing的功能。
因此,如果文件读取不会改变 Swing 组件的状态,请使用简单的后台线程:
new Thread(() -> {
File file = new File("file.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// operation
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
如果读取发生时会改变 GUI 的状态,请再次使用 SwingWorker。
附带问题:避免使用空布局,因为它们会反过来咬你。
关于java - 如何在JFrame显示后才读取Java中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44785560/