Java JFrame在第一次调用后显示为空
当应用程序运行时,我第一次调用这个JFrame时,它工作得非常好。但当我试图打开一个新文件时,进度条将返回屏幕。查看屏幕抓取以查看其应如何查看其之后的外观Java JFrame在第一次调用后显示为空,java,swing,jframe,jpanel,Java,Swing,Jframe,Jpanel,当应用程序运行时,我第一次调用这个JFrame时,它工作得非常好。但当我试图打开一个新文件时,进度条将返回屏幕。查看屏幕抓取以查看其应如何查看其之后的外观 public ArrayList<Data> handleData(File fileToOpen) throws FileNotFoundException { ArrayList<Data> handle = new ArrayList<Data>(); //clear the
public ArrayList<Data> handleData(File fileToOpen) throws FileNotFoundException {
ArrayList<Data> handle = new ArrayList<Data>();
//clear the arraylist the second time round
handle.clear();
BufferedReader reader = new BufferedReader(new FileReader(fileToOpen));
//buffer used for scanner
int lines = 0;
//find out the value of lines here
JFrame loader = new JFrame();
JPanel loadPanel = new JPanel();
JProgressBar progressBar = new JProgressBar(0, lines);
JLabel label = new JLabel();
loader.setDefaultCloseOperation(EXIT_ON_CLOSE);
label.setText("Loading Data...");
loadPanel.add(label);
loadPanel.add(progressBar);
loader.add(loadPanel);
loader.pack();
loader.setVisible(true);
//Do a load of stuff which increments the progress bar
loader.setVisible(false);
return handle;
}
public ArrayList handleData(File fileToOpen)抛出FileNotFoundException{
ArrayList句柄=新的ArrayList();
//第二轮清除arraylist
handle.clear();
BufferedReader reader=new BufferedReader(new FileReader(fileToOpen));
//用于扫描仪的缓冲区
int行=0;
//在这里找出行的值
JFrame loader=新JFrame();
JPanel loadPanel=新的JPanel();
JProgressBar progressBar=新的JProgressBar(0,行);
JLabel标签=新的JLabel();
loader.setDefaultCloseOperation(关闭时退出);
label.setText(“加载数据…”);
加载面板。添加(标签);
加载面板。添加(进度条);
添加(加载面板);
loader.pack();
loader.setVisible(true);
//执行一系列增加进度条的操作
loader.setVisible(false);
返回手柄;
}
以下是进度条和JFrame的外观:
这是进度条第二次的外观:
所有代码:
package Default;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class ReadIn extends JFrame {
public File openFile() {
File fileToOpen = null;
JFileChooser fileChooser = new JFileChooser();
int modalToComponent = fileChooser.showOpenDialog(this);
if (modalToComponent == JFileChooser.APPROVE_OPTION) {
fileToOpen = fileChooser.getSelectedFile();
} else if (modalToComponent == JFileChooser.CANCEL_OPTION) {
System.exit(1);
}
return fileToOpen;
}
public ArrayList<Data> handleData(File fileToOpen) throws FileNotFoundException {
ArrayList<Data> handle = new ArrayList<Data>();
handle.clear();
BufferedReader reader = new BufferedReader(new FileReader(fileToOpen));
int lines = 0;
try {
while (reader.readLine() != null)
lines++;
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Scanner sc = new Scanner(fileToOpen);
System.out.println(sc.nextLine());
System.out.println(sc.nextLine());
System.out.println("Reading Data...");
sc.nextLine();
String split = sc.nextLine();
Scanner splitter = new Scanner(split);
JDialog loader = new JDialog();
JPanel loadPanel = new JPanel();
JProgressBar progressBar = new JProgressBar(0, lines);
JLabel label = new JLabel();
loader.setDefaultCloseOperation(HIDE_ON_CLOSE);
label.setText("Loading Data...");
loadPanel.add(label);
loadPanel.add(progressBar);
loader.add(loadPanel);
loader.pack();
loader.setVisible(true);
while (splitter.hasNext()) {
String peek = splitter.next();
if (peek.equals("Timestamp")) {
peek = peek + splitter.next();
}
Data temp = new Data();
temp.setHeading(peek);
handle.add(temp);
}
while (sc.hasNextDouble()) {
progressBar.setValue(progressBar.getValue() + 1);
for (int i = 0; i < handle.size(); i++) {
handle.get(i).getValues().add(sc.nextDouble());
}
}
System.out.println("Data Loaded");
splitter.close();
sc.close();
loader.setVisible(false);
System.out.println("On EDT?: " + SwingUtilities.isEventDispatchThread());
return handle;
}
包默认值;
导入java.awt.event.WindowEvent;
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileReader;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.Scanner;
导入javax.swing.JDialog;
导入javax.swing.JFileChooser;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
导入javax.swing.JProgressBar;
导入javax.swing.SwingUtilities;
@抑制警告(“串行”)
公共类ReadIn扩展了JFrame{
公共文件openFile(){
文件fileToOpen=null;
JFileChooser fileChooser=新的JFileChooser();
int modalToComponent=fileChooser.showOpenDialog(此);
if(modalToComponent==JFileChooser.APPROVE\u选项){
fileToOpen=fileChooser.getSelectedFile();
}else if(modalToComponent==JFileChooser.CANCEL\u选项){
系统出口(1);
}
返回文件打开;
}
公共ArrayList handleData(文件fileToOpen)引发FileNotFoundException{
ArrayList句柄=新的ArrayList();
handle.clear();
BufferedReader reader=new BufferedReader(new FileReader(fileToOpen));
int行=0;
试一试{
while(reader.readLine()!=null)
行++;
reader.close();
}捕获(IOE异常){
e、 printStackTrace();
}
扫描仪sc=新扫描仪(fileToOpen);
System.out.println(sc.nextLine());
System.out.println(sc.nextLine());
System.out.println(“读取数据…”);
sc.nextLine();
字符串拆分=sc.nextLine();
扫描仪拆分器=新扫描仪(拆分);
JDialog loader=newjdialog();
JPanel loadPanel=新的JPanel();
JProgressBar progressBar=新的JProgressBar(0,行);
JLabel标签=新的JLabel();
loader.setDefaultCloseOperation(在关闭时隐藏);
label.setText(“加载数据…”);
加载面板。添加(标签);
加载面板。添加(进度条);
添加(加载面板);
loader.pack();
loader.setVisible(true);
while(splitter.hasNext()){
字符串peek=splitter.next();
if(peek.equals(“时间戳”)){
peek=peek+splitter.next();
}
数据温度=新数据();
温度设定值(peek);
句柄。添加(临时);
}
while(sc.hasNextDouble()){
progressBar.setValue(progressBar.getValue()+1);
对于(int i=0;i
}如果您没有发布有效的,我们就不可能绝对肯定地知道问题的原因,图像表明这是一个Swing线程问题,您有长期运行的代码,可能在这里:
//Do a load of stuff which increments the progress bar
这会阻塞Swing事件线程,并导致Swing GUI无法自行绘制
如果是这样,解决方案是改进代码,使其尊重Swing事件线程,从而使长时间运行的代码在后台线程(如通过SwingWorker)中运行
其他问题:您显示的窗口看起来是“依赖”窗口,而不是主应用程序窗口。如果是这样,则不应将其创建为JFrame,而应创建为JDialog,可以是模态的,也可以是非模态的,具体取决于您的需要
还有,为什么它第一次起作用?很可能第一次,上面的代码没有在Swing事件线程EDT上运行,而第二次调用该代码时,它实际上是在EDT上运行的。您可以通过调用SwingUtilities.isEventDispatchThread()
并打印结果来测试这一点。e、 g
System.out.println("On EDT?: " + SwingUtilities.isEventDispatchThread());
例如:
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
public class UpdateDataEg extends JPanel {
protected static final int MAX_LINES = 200;
public UpdateDataEg() {
setPreferredSize(new Dimension(500, 400));
add(new JButton(new UpdateDataAction("Update Data", KeyEvent.VK_U)));
}
// this must be a void method as you'll get the result from a callback, not
// from this method
public void handleData(final File fileToOpen) {
int lines = 0;
// find out the value of lines here
Window window = SwingUtilities.getWindowAncestor(UpdateDataEg.this);
JDialog loader = new JDialog(window, "Progress", ModalityType.APPLICATION_MODAL);
JPanel loadPanel = new JPanel(new BorderLayout());
final JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setStringPainted(true);
JLabel label = new JLabel();
label.setText("Loading Data...");
loadPanel.add(label, BorderLayout.PAGE_START);
loadPanel.add(progressBar);
loader.add(loadPanel);
loader.pack();
loader.setLocationRelativeTo(window);
final SwingWorker<ArrayList<Data>, Void> myWorker = new SwingWorker<ArrayList<Data>, Void>() {
@Override
protected ArrayList<Data> doInBackground() throws Exception {
ArrayList<Data> handle = new ArrayList<Data>();
// clear the arraylist the second time round
handle.clear();
int lines = 0;
// !! BufferedReader reader = new BufferedReader(new FileReader(fileToOpen));
// !! long code here to do calculations and place into ArrayList<Data>
// emulated by Thread.sleep
// !! set progress property here so that listener can update
while (lines < MAX_LINES) {
lines += (int) (10 * Math.random());
int myProgress = (int) ((lines * 100) / MAX_LINES);
myProgress = Math.min(100, myProgress);
setProgress(myProgress);
Thread.sleep(200);
}
return handle;
}
};
// our callback
myWorker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getPropertyName().equals("progress")) {
int progress = myWorker.getProgress();
progressBar.setValue(progress);
} else if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
// if the worker has finished
loader.setVisible(false);
try {
ArrayList<Data> data = myWorker.get();
// use data here
} catch (InterruptedException | ExecutionException e) {
// TODO handle the exceptions
e.printStackTrace();
}
}
}
});
myWorker.execute();
// if the dialog is modal, this must be last
loader.setVisible(true);
// delete this call as this would be done from the callback
// loader.setVisible(false);
// delete this as this is obtained in the callback
// return handle;
}
private class UpdateDataAction extends AbstractAction {
public UpdateDataAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
@Override
public void actionPerformed(ActionEvent e) {
handleData(new File("Foobar.txt"));
}
}
private static void createAndShowGui() {
UpdateDataEg mainPanel = new UpdateDataEg();
JFrame frame = new JFrame("UpdateDataEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Data {
}
导入java.awt.BorderLayout;
导入java.awt.Dialog.ModalityType;
导入java.awt.Dimension;
导入java.awt.Window;
导入java.awt.event.ActionEvent;
导入java.awt.event.KeyEvent;
导入java.beans.PropertyChangeEvent;
导入java.beans.PropertyChangeListener;
导入java.io.File;
导入java.util.ArrayList;
导入java.util.concurrent.ExecutionException;
导入javax.swing.*;
公共类UpdateDatag扩展了JPanel{
受保护的静态最终整数最大线=200;
public updatedatag(){
setPreferredSize(新尺寸(500400));
添加(newjbutton(newupdatedataaction(“updatedata”,KeyEvent.VK_));
}
//这必须是一个void方法,因为您将从回调中获得结果,而不是
//从这个方法
public void handleData(最终文件fileToOpen){
int行=0;
//在这里找出行的值
Window Window=SwingUtilities.getWindow祖先(U