Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么JFrame在一种情况下是空白的,而在另一种情况下不是空白的?(简单的SwingWorker示例)_Java_Swing_Jframe - Fatal编程技术网

Java 为什么JFrame在一种情况下是空白的,而在另一种情况下不是空白的?(简单的SwingWorker示例)

Java 为什么JFrame在一种情况下是空白的,而在另一种情况下不是空白的?(简单的SwingWorker示例),java,swing,jframe,Java,Swing,Jframe,=============================================== 由于评论太长,请在此添加此内容: 我看得出我不清楚。运行MaintTest/main时,JFrame with Test按钮不是问题所在。单击测试按钮时显示的JFrame就是问题所在 注释掉FileUtils.copyrltofile try块会使第二个JFrame显示得如此短暂,以至于不清楚它是否显示了标签和程序条。(带有测试按钮的初始JFrame会正常显示,当我单击测试按钮时,第二个JFrame会

===============================================

由于评论太长,请在此添加此内容:

我看得出我不清楚。运行MaintTest/main时,JFrame with Test按钮不是问题所在。单击测试按钮时显示的JFrame就是问题所在

注释掉FileUtils.copyrltofile try块会使第二个JFrame显示得如此短暂,以至于不清楚它是否显示了标签和程序条。(带有测试按钮的初始JFrame会正常显示,当我单击测试按钮时,第二个JFrame会出现一瞬间并消失。带有测试按钮的JFrame会保持不变,正如预期的那样。我不会连续复制“一个测试按钮6次”。这听起来像是设置错误,可能吧?)

是的,copyURLToFile正在阻塞,但在调用copyURLToFile之前,我启动了第二个JFrame的并发显示,所以它不应该在单独的线程中运行吗?我有理由知道它的作用。在派生此代码的原始应用程序中,有时会根据需要显示第二个JFrame

JFrame显示有时总是说setVisible必须最后调用,但这并不能解决我的情况。这似乎与并发性和Swing有关,我不理解

===============================================

通常我可以通过谷歌找到答案(更多的时候是这样)。我一定是遗漏了什么

我已经把它缩减到了我实际代码的一小部分,但仍然没有得到启发。抱歉,如果它仍然有点大,但很难进一步压缩它

有3个java文件。本文引用了commons-io-2.5.jar。我正在Eclipse Neon中编码/运行

如果我运行
ProgressBar
/
main()
我会看到
JFrame
内容。如果我运行
main测试
/
main()
我不会。以下是3个文件(请原谅一些缩进异常——SO UI和我不同意这些事情):

MainTest
大型机
ProgressBar

感谢@MadProgrammer的评论:


我可以告诉您,您可能看不到ProgressBar框架,因为FileUtils.copyURLToFile将被阻止,直到它完成,在这种情况下,您真的应该使用SwingWorker

我在教程中阅读了关于SwingWorker的内容,随后修改了MainFrame.java模块,如下所示:

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

import org.apache.commons.io.FileUtils;

public class MainFrame extends JFrame implements ActionListener {
JButton jButton = new JButton();
static ProgressBar status;
static URL url;

public MainFrame() {
    // Set up the content pane.
    Container contentPane = this.getContentPane();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    jButton.setAlignmentX(Component.CENTER_ALIGNMENT);
    jButton.setText("Test");
    jButton.setActionCommand("Test");
    jButton.addActionListener(this);
    contentPane.add(jButton);
    setup();
}

private void setup() {
    Toolkit tk;
    Dimension screenDims;
    tk = Toolkit.getDefaultToolkit();
    screenDims = tk.getScreenSize();
    this.setLocation((screenDims.width - this.getWidth()) / 2, (screenDims.height - this.getHeight()) / 2);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setVisible(true);
}

public static void downloadExecutable(String str) {
    url = null;
    try {
        url = new URL("http://pegr-converter.com/download/test.jpg");
    } catch (MalformedURLException exc) {
        JOptionPane.showMessageDialog(null, "Unexpected exception: " + exc.getMessage());
        return;
    }
    if (url != null) {
        String[] options = { "OK", "Change", "Cancel" };
        int response = JOptionPane.NO_OPTION;
        File selectedFolder = new File(getDownloadDir());
        File selectedLocation = new File(selectedFolder, str + ".jpg");
        while (response == JOptionPane.NO_OPTION) {
            selectedLocation = new File(selectedFolder, str + ".jpg");
            String msgStr = str + ".jpg will be downloaded to the following location:\n"
                    + selectedLocation.toPath();
            response = JOptionPane.showOptionDialog(null, msgStr, "Pegr input needed",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
            if (response == JOptionPane.NO_OPTION) {
                // Prompt for file selection.
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fileChooser.setCurrentDirectory(selectedFolder);
                fileChooser.showOpenDialog(null);
                selectedFolder = fileChooser.getSelectedFile();
            }
        }
        if (response == JOptionPane.YES_OPTION) {
            int size = 0;
            URLConnection conn;
            try {
                conn = url.openConnection();
                size = conn.getContentLength();
            } catch (IOException exc) {
                System.out.println(exc.getMessage());
            }
            //System.out.println("javax.swing.SwingUtilities.isEventDispatchThread=" + javax.swing.SwingUtilities.isEventDispatchThread());
            File destination = new File(selectedFolder, str + ".jpg");
            status = new ProgressBar("Downloading " + str + ".jpg", destination, size);
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    try {
                        FileUtils.copyURLToFile(url, destination, 10000, 300000);
                    } catch (IOException exc) {
                        JOptionPane.showMessageDialog(null, "Download failed.");
                    }
                    return null;
                }
                public void done() {
                    status.close();
                }
            };
            worker.execute();
        }
    }
}

public static String getDownloadDir() {
    String home = System.getProperty("user.home");
    File downloadDir = new File(home + "/Downloads/");
    if (downloadDir.exists() && !downloadDir.isDirectory()) {
        return home;
    } else {
        downloadDir = new File(downloadDir + "/");
        if ((downloadDir.exists() && downloadDir.isDirectory()) || downloadDir.mkdirs()) {
            return downloadDir.getPath();
        } else {
            return home;
        }
    }
}

@Override
public void actionPerformed(ActionEvent arg0) {
    downloadExecutable("test");
}

}
导入java.awt.Component;
导入java.awt.Container;
导入java.awt.Dimension;
导入java.awt.Toolkit;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.io.File;
导入java.io.IOException;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.net.URLConnection;
导入javax.swing.BoxLayout;
导入javax.swing.JButton;
导入javax.swing.JFileChooser;
导入javax.swing.JFrame;
导入javax.swing.JOptionPane;
导入javax.swing.SwingWorker;
导入org.apache.commons.io.FileUtils;
公共类大型机扩展JFrame实现ActionListener{
JButton JButton=新JButton();
静态进度条状态;
静态URL;
公共主机(){
//设置内容窗格。
容器contentPane=this.getContentPane();
setLayout(新的BoxLayout(contentPane,BoxLayout.Y_轴));
jButton.setAlignmentX(组件中心对齐);
setText(“测试”);
setActionCommand(“测试”);
addActionListener(这个);
contentPane.add(jButton);
设置();
}
私有无效设置(){
工具包tk;
尺寸屏幕尺寸;
tk=Toolkit.getDefaultToolkit();
screenDims=tk.getScreenSize();
this.setLocation((screenDims.width-this.getWidth())/2,(screenDims.height-this.getHeight())/2);
此.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
这个包();
此.setVisible(true);
}
公共静态void下载可执行文件(字符串str){
url=null;
试一试{
url=新url(“http://pegr-converter.com/download/test.jpg");
}捕获(异常异常异常exc){
showMessageDialog(null,“意外异常:”+exc.getMessage());
返回;
}
如果(url!=null){
字符串[]选项={“确定”、“更改”、“取消”};
int response=JOptionPane.NO_选项;
File selectedFolder=新文件(getDownloadDir());
File selectedLocation=新文件(selectedFolder,str+“.jpg”);
while(response==JOptionPane.NO_选项){
selectedLocation=新文件(selectedFolder,str+“.jpg”);
字符串msgStr=str+“.jpg将下载到以下位置:\n”
+selectedLocation.toPath();
response=JOptionPane.showOptionDialog(null,msgStr,“需要Pegr输入”,
JOptionPane.YES\u NO\u CANCEL\u选项,JOptionPane.QUESTION\u消息,null,options,options[0]);
if(response==JOptionPane.NO_选项){
//提示选择文件。
JFileChooser fileChooser=新的JFileChooser();
fileChooser.setFileSelectionMode(仅限JFileChooser.DIRECTORIES_);
fileChooser.setCurrentDirectory(selectedFolder);
fileChooser.showOpenDialog(null);
selectedFolder=fileChooser.getSelectedFile();
}
}
if(response==JOptionPane.YES\u选项){
int size=0;
连接连接;
试一试{
conn=url.openConnection();
size=conn.getContentLength();
}捕获(IOException){
System.out.println(exc.getMessage());
}
//System.out.println(“javax.swing.SwingUtilities.isEventDispatchThread=“+javax.swing.SwingUtilities.isEventDispatchThread());
文件目的地=新文件(selectedFolder,str+“.jpg”);
状态=新进度条(“D
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.apache.commons.io.FileUtils;

public class MainFrame extends JFrame implements ActionListener {

JButton jButton = new JButton();

public MainFrame() {
    // Set up the content pane.
    Container contentPane = this.getContentPane();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    jButton.setAlignmentX(Component.CENTER_ALIGNMENT);
    jButton.setText("Test");
    jButton.setActionCommand("Test");
    jButton.addActionListener(this);
    contentPane.add(jButton);
    setup();
}

private void setup() {
    Toolkit tk;
    Dimension screenDims;
    tk = Toolkit.getDefaultToolkit();
    screenDims = tk.getScreenSize();
    this.setLocation((screenDims.width - this.getWidth()) / 2, (screenDims.height - this.getHeight()) / 2);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setVisible(true);
}

public static void downloadExecutable(String str) {
    URL url = null;
    try {
        url = new URL("http://pegr-converter.com/download/test.jpg");
    } catch (MalformedURLException exc) {
        JOptionPane.showMessageDialog(null, "Unexpected exception: " + exc.getMessage());
        return;
    }
    if (url != null) {
        String[] options = { "OK", "Change", "Cancel" };
        int response = JOptionPane.NO_OPTION;
        File selectedFolder = new File(getDownloadDir());
        File selectedLocation = new File(selectedFolder, str + ".jpg");
        while (response == JOptionPane.NO_OPTION) {
            selectedLocation = new File(selectedFolder, str + ".jpg");
            String msgStr = str + ".jpg will be downloaded to the following location:\n"
                    + selectedLocation.toPath();
            response = JOptionPane.showOptionDialog(null, msgStr, "Pegr input needed",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
            if (response == JOptionPane.NO_OPTION) {
                // Prompt for file selection.
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fileChooser.setCurrentDirectory(selectedFolder);
                fileChooser.showOpenDialog(null);
                selectedFolder = fileChooser.getSelectedFile();
            }
        }
        if (response == JOptionPane.YES_OPTION) {
            int size = 0;
            URLConnection conn;
            try {
                conn = url.openConnection();
                size = conn.getContentLength();
            } catch (IOException exc) {
                System.out.println(exc.getMessage());
            }
            File destination = new File(selectedFolder, str + ".jpg");
            ProgressBar status = new ProgressBar("Downloading " + str + ".jpg", destination, size);
            try {
                FileUtils.copyURLToFile(url, destination, 10000, 300000);
            } catch (IOException exc) {
                JOptionPane.showMessageDialog(null, "Download failed.");
                return;
            }
            status.close();
        }
    }
}

public static String getDownloadDir() {
    String home = System.getProperty("user.home");
    File downloadDir = new File(home + "/Downloads/");
    if (downloadDir.exists() && !downloadDir.isDirectory()) {
        return home;
    } else {
        downloadDir = new File(downloadDir + "/");
        if ((downloadDir.exists() && downloadDir.isDirectory()) || downloadDir.mkdirs()) {
            return downloadDir.getPath();
        } else {
            return home;
        }
    }
}

@Override
public void actionPerformed(ActionEvent arg0) {
    downloadExecutable("test");
}

}
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;

import org.apache.commons.io.FileUtils;

public class ProgressBar {

private String title;
private File outputFile;
private int size;
private ProgressTimerTask task;

JFrame frame;
JLabel jLabelProgressTitle;
JProgressBar jProgressBarProportion;

public ProgressBar(String title, File output, int size) {
    this.title = title;
    this.outputFile = output;
    this.size = size;
    frame = new JFrame("BoxLayoutDemo");

    jProgressBarProportion = new JProgressBar();
    jProgressBarProportion.setPreferredSize(new Dimension(300, 50));

    jLabelProgressTitle = new JLabel();
    jLabelProgressTitle.setHorizontalAlignment(SwingConstants.CENTER);
    jLabelProgressTitle.setText("Progress");
    jLabelProgressTitle.setPreferredSize(new Dimension(300, 50));

    //Set up the content pane.
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    jLabelProgressTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
    contentPane.add(jLabelProgressTitle);
    jProgressBarProportion.setAlignmentX(Component.CENTER_ALIGNMENT);
    contentPane.add(jProgressBarProportion);

    setup();

    task = new ProgressTimerTask(this, outputFile, size);
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, 0, 500);
}

private void setup() {
    Toolkit tk;
    Dimension screenDims;

    frame.setTitle("Test");

    tk = Toolkit.getDefaultToolkit();
    screenDims = tk.getScreenSize();
    frame.setLocation((screenDims.width - frame.getWidth()) / 2, (screenDims.height - frame.getHeight()) / 2);

    jLabelProgressTitle.setText(title);
    jProgressBarProportion.setVisible(true);
    jProgressBarProportion.setMinimum(0);
    jProgressBarProportion.setMaximum(size);
    jProgressBarProportion.setValue((int) outputFile.length());

    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

public void close() {
    task.cancel();
    frame.dispose();
}

public static void main(String[] args) throws InterruptedException {
    ProgressBar progBar = new ProgressBar("Test Title", new File(MainFrame.getDownloadDir() + "test.jpg"), 30000);
    Thread.sleep(3000);
    progBar.close();
}

}

class ProgressTimerTask extends TimerTask {

ProgressBar frame;
File outputFile;
int size;

public ProgressTimerTask(ProgressBar progressBar, File outputFile, int size) {
    this.frame = progressBar;
    this.outputFile = outputFile;
    this.size = size;
}

public void run() {
    frame.jProgressBarProportion.setValue((int) outputFile.length());
    System.out.println("Running");
}

}
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

import org.apache.commons.io.FileUtils;

public class MainFrame extends JFrame implements ActionListener {
JButton jButton = new JButton();
static ProgressBar status;
static URL url;

public MainFrame() {
    // Set up the content pane.
    Container contentPane = this.getContentPane();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    jButton.setAlignmentX(Component.CENTER_ALIGNMENT);
    jButton.setText("Test");
    jButton.setActionCommand("Test");
    jButton.addActionListener(this);
    contentPane.add(jButton);
    setup();
}

private void setup() {
    Toolkit tk;
    Dimension screenDims;
    tk = Toolkit.getDefaultToolkit();
    screenDims = tk.getScreenSize();
    this.setLocation((screenDims.width - this.getWidth()) / 2, (screenDims.height - this.getHeight()) / 2);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setVisible(true);
}

public static void downloadExecutable(String str) {
    url = null;
    try {
        url = new URL("http://pegr-converter.com/download/test.jpg");
    } catch (MalformedURLException exc) {
        JOptionPane.showMessageDialog(null, "Unexpected exception: " + exc.getMessage());
        return;
    }
    if (url != null) {
        String[] options = { "OK", "Change", "Cancel" };
        int response = JOptionPane.NO_OPTION;
        File selectedFolder = new File(getDownloadDir());
        File selectedLocation = new File(selectedFolder, str + ".jpg");
        while (response == JOptionPane.NO_OPTION) {
            selectedLocation = new File(selectedFolder, str + ".jpg");
            String msgStr = str + ".jpg will be downloaded to the following location:\n"
                    + selectedLocation.toPath();
            response = JOptionPane.showOptionDialog(null, msgStr, "Pegr input needed",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
            if (response == JOptionPane.NO_OPTION) {
                // Prompt for file selection.
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fileChooser.setCurrentDirectory(selectedFolder);
                fileChooser.showOpenDialog(null);
                selectedFolder = fileChooser.getSelectedFile();
            }
        }
        if (response == JOptionPane.YES_OPTION) {
            int size = 0;
            URLConnection conn;
            try {
                conn = url.openConnection();
                size = conn.getContentLength();
            } catch (IOException exc) {
                System.out.println(exc.getMessage());
            }
            //System.out.println("javax.swing.SwingUtilities.isEventDispatchThread=" + javax.swing.SwingUtilities.isEventDispatchThread());
            File destination = new File(selectedFolder, str + ".jpg");
            status = new ProgressBar("Downloading " + str + ".jpg", destination, size);
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    try {
                        FileUtils.copyURLToFile(url, destination, 10000, 300000);
                    } catch (IOException exc) {
                        JOptionPane.showMessageDialog(null, "Download failed.");
                    }
                    return null;
                }
                public void done() {
                    status.close();
                }
            };
            worker.execute();
        }
    }
}

public static String getDownloadDir() {
    String home = System.getProperty("user.home");
    File downloadDir = new File(home + "/Downloads/");
    if (downloadDir.exists() && !downloadDir.isDirectory()) {
        return home;
    } else {
        downloadDir = new File(downloadDir + "/");
        if ((downloadDir.exists() && downloadDir.isDirectory()) || downloadDir.mkdirs()) {
            return downloadDir.getPath();
        } else {
            return home;
        }
    }
}

@Override
public void actionPerformed(ActionEvent arg0) {
    downloadExecutable("test");
}

}