Java JFrame GUI冻结+幻影

Java JFrame GUI冻结+幻影,java,swing,user-interface,jframe,Java,Swing,User Interface,Jframe,好吧,我明白我不应该有这个循环 while (pidInfo.contains(<processname>)){ pidInfo =""; check<processname> =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe"); input = new BufferedReader(new InputStreamReader(che

好吧,我明白我不应该有这个循环

while (pidInfo.contains(<processname>)){
    pidInfo ="";
    check<processname> =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
    input =  new BufferedReader(new InputStreamReader(check<processname>.getInputStream()));

    while ((line = input.readLine()) != null) {
        pidInfo+=line; 
    }

    input.close();

    if (pidInfo.contains(<processname>)){
        System.out.println("<processname> RUNNING");
    }
    else if (closeReason == 2){
        System.out.println("<processname> STOPPED VIA PROG & USER");
        status = "Not Running";
        int ll = JOptionPane.showOptionDialog(null, "<processname>", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
        if (ll == JOptionPane.OK_OPTION){
            //frame.setAlwaysOnTop(true);
            frame.dispose();
        }
    }
    // TODO: Other exit
} 
第2帧命名为second.java

/* StackOverflow - 2nd
* By Rabbitmcv
* If one runs this one sans the first program it shows non-frozen... but if you run it from menu.java it will freeze... probably something with threads.
*/
package main;

// Import
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.awt.*;
import javax.swing.*;
// This file has been renamed to 2.java
public class second implements ActionListener{
    // Frame
    JFrame frame= new JFrame();
    // Panel
    JPanel panel = new JPanel();
    // Int
    // closeReason: 0 = user, 1 = program, 2 = user init via prog (non-error)
    int closeReason = 0;
    // String
    String status = "Running";
    public second(){
        // Set Settings
        frame.setResizable(false);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        frame.setAlwaysOnTop(true);
        // Crap

        frame.setTitle("StackOverflow- Running");
        // Settings
        // Add J...
        JLabel label = new JLabel("Game "+status);
        JButton closeGameButton = new JButton("Click here to close game");
        // Adds the J... to a Jpanel (IN ORDER FROM TOP TO BOTTOM)
        panel.add(label);
        panel.add(closeGameButton);
        // Button Func.
        closeGameButton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0){
                try {
                    System.out.println("CloseGameButton Pressed");
                    Process killGame = Runtime.getRuntime().exec("taskkill /F /IM explorer.exe"); // My process has been changed to explorer.exe !!!! THIS WILL STOP WINDOWS EXPLORER. Feel free to change it to another process
                    closeReason = 2;
                    int exitCode = killGame.waitFor();
                    if (exitCode != 0){
                        throw new IOException("Failed to kill game; game not running");
                    }
                    frame.setTitle("StackOverflow - Not Running - Closed by user");
                    frame.setAlwaysOnTop(false);
                    int a = JOptionPane.showOptionDialog(null, "game has been closed", "game Closed", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
                    if (a == JOptionPane.OK_OPTION){
                        frame.setAlwaysOnTop(true);
                        frame.setTitle("StackOverflow - Not Running - Closed by user");
                    }
                } catch (Exception e) {
                    frame.setAlwaysOnTop(false);
                    System.out.println("Failed to kill game");
                    int a = JOptionPane.showOptionDialog(null, "game is not running", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                    if (a == JOptionPane.OK_OPTION){
                        frame.setAlwaysOnTop(true);
                    }
                    e.printStackTrace();
                }
            }
        });
        // END BUTTON FUNC
        // Set layouts
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 30, 10));
        panel.setLayout(new GridLayout(0, 1));
        // Center Labels
        label.setHorizontalAlignment(JLabel.CENTER);
        // Add the JPanel to the JFrame
        frame.add(panel);
        // end
        frame.revalidate();
        System.out.println("far");
        frame.setVisible(true);

        try{
            String line;
            String pidInfo ="";

            Process checkcs =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");

            BufferedReader input =  new BufferedReader(new InputStreamReader(checkcs.getInputStream()));

            while ((line = input.readLine()) != null) {
                pidInfo+=line; 
            }

            input.close();

            if (pidInfo.contains("explorer.exe")){ // Changed to explorer.exe
                System.out.println("game running - pid");
                status = "Running";
                while (pidInfo.contains("explorer.exe")){ // Changed to explorer.exe
                    pidInfo ="";
                    checkcs =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
                    input =  new BufferedReader(new InputStreamReader(checkcs.getInputStream()));

                    while ((line = input.readLine()) != null) {
                        pidInfo+=line; 
                    }

                    input.close();

                    if (pidInfo.contains("explorer.exe")){ // This checks if the process is still going on... changed to explorer.exe
                        System.out.println("game RUNNING");
                    }
                    else if (closeReason == 2){
                        System.out.println("game STOPPED VIA PROG & USER");
                        status = "Not Running";
                        int ll = JOptionPane.showOptionDialog(null, "game has stopped running", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                        if (ll == JOptionPane.OK_OPTION){
                            //frame.setAlwaysOnTop(true);
                            frame.dispose();
                        }
                    }
                    // TODO: Other exit
                }
            }
        }
        catch(Exception e){
            System.out.println("Failed to check process");
            e.printStackTrace();
        }
    }
    public static void main (String args[]){
        new second(); //StackOverflow
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
}
如果你不喜欢,你可以下载所有文件的.zip文件


正如我在评论中所说,当

public static void main (String args[]){
    new second(); //StackOverflow
}
被JVM称为ie,因为您已经从命令行执行了该类,它正在JVM的主线程中运行

这意味着构造函数中的代码没有在事件调度线程的上下文中执行,因此不会阻塞UI

调用frame.setVisible时,底层API将创建事件调度线程,所有基于UI的代码将在单独的线程上执行,将在构造函数中启动的代码留在主线程的上下文中执行

当调用closeGameButton的ActionListener时,无论代码是如何启动的,都会阻止事件调度线程,直到killGame完成

你可以用同样的方法换第二幕

public static void main (String args[]){
    new second(); //StackOverflow
}

这是启动所有Swing应用程序的方式


我建议你先看一看,如果没有一些可以运行的例子来证明你的问题,你就不可能给出任何答案。我的猜测是,当您独立启动第二个帧时,循环是在主线程中创建的,而不是在EDT中创建的,当您从第一个帧启动循环时,它是在EDT的上下文中创建的。我将很快添加一些上下文。我现在不想发布整个代码,但我将很快发布一个粘贴库。但请记住,有些东西已被重命名。您可能需要将其重命名为通用名称才能运行。我会这样做。[填充物]酷。我将尝试一下代码,并阅读有关worker/concurrency的内容。谢谢你的帮助!
public static void main (String args[]){
    new second(); //StackOverflow
}
public static void main (String args[]){
    new second(); //StackOverflow
}
public static void main (String args[]){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new second(); //StackOverflow
        }
    });
}