繁体   English   中英

关闭时隐藏后重新打开 Java window

[英]Reopen Java window after hiding it on close

我正在构建一个应用程序,我遇到的最大问题是重新打开该应用程序。

我可以很好地启动我的应用程序。 它创建了主要的 window。我也在使用setDefaultCloseOperation(HIDE_ON_CLOSE)我也尝试过DISPOSE_ON_CLOSE但它们都具有相同的效果。 因此,当我关闭它时,window 将关闭。 但是,当我单击停靠栏中的图标时,window 不会重新打开。

我希望应用程序像 Safari 那样打开,您可以关闭 safari,但它仍在后台运行,当您单击破折号中的图标时,如果您还没有打开,它会生成一个新的 window。

要最小化而不是关闭,请使用JFrame.DO_NOTHING_ON_CLOSE并处理关闭请求

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter()
{
    public void windowClosing(WindowEvent e)
    {
        frame.setExtendedState(JFrame.ICONIFIED);
    }
});

这将最小化框架,然后用户可以单击任务栏上的图标进行还原

如前所述,听起来您将需要两个进程,一个进程渲染,另一个进程处理数据。

  • 客户 (渲染)
    • 需要连接到服务器
      • 如果服务器未运行,请启动服务器并连接
        • 服务器应作为服务,后台进程启动,或者可以在另一台机器上运行(在示例中,我将其作为后台进程运行)
    • 显示从服务器接收的数据
    • 将命令从用户发送到服务器
  • 服务器 (进程)
    • 除非有指示,否则不会关闭
    • 接受来自客户的连接
      • 如果一次只允许一个客户端,则拒绝新连接,直到客户端断开连接
      • 如果在客户端本地运行,则该端口应仅接受本地连接
    • 发送数据到客户端进行显示
    • 从客户端接收命令

为了证明这一点,我整理了一些示例代码

都在同一个文件夹中编译并运行TestClient

TestClient.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class TestClient
{
    public static void main(String[] args) throws Exception
    {
        Socket socket = null;
        try
        {
            System.out.println("Connecting to backend");
            socket = new Socket("localhost", 28000); //check if backend is running
        }
        catch(IOException e) //backend isn't running
        {
            System.out.println("Backend isn't running");
            System.out.println("Starting backend");
            Runtime.getRuntime().exec("cmd /c java TestServer"); //start the backend
            for(int i = 0; i < 10; i++) //attempt to connect
            {
                Thread.sleep(500);
                System.out.println("Attempting connection " + i);
                try
                {
                    socket = new Socket("localhost", 28000);
                    break;
                }
                catch(IOException ex){}
            }
        }

        if(socket == null)
        {
            System.err.println("Could not start/connect to the backend");
            System.exit(1);
        }

        System.out.println("Connected");
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

        String line = reader.readLine();
        System.out.println("read " + line);
        if(line.equals("refused")) //already a client connected
        {
            System.err.println("Already a client connected to the backend");
            System.exit(1);
        }

        //set up the GUI
        JFrame frame = new JFrame("TestClient");
        frame.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        JLabel label = new JLabel(line);
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 4;
        frame.add(label, c);

        String[] buttonLabels = {"A", "B", "Quit"};
        ActionListener listener = new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println(e.getActionCommand());
                try
                {
                    switch(e.getActionCommand())
                    {
                        case "A":
                            writer.write("A");
                            writer.newLine();
                            writer.flush();
                            break;
                        case "B":
                            writer.write("B");
                            writer.newLine();
                            writer.flush();
                            break;
                        case "Quit":
                            writer.write("Quit");
                            writer.newLine();
                            writer.flush();
                            System.exit(0);
                            break;
                    }
                }
                catch(IOException ex)
                {
                    ex.printStackTrace();
                    System.exit(1);
                }
            }
        };

        c.gridy = 1;
        c.gridx = GridBagConstraints.RELATIVE;
        c.gridwidth = 1;
        for(String s : buttonLabels)
        {
            JButton button = new JButton(s);
            button.addActionListener(listener);
            frame.add(button, c);
        }

        //start a thread to listen to the server
        new Thread(new Runnable()
        {
            public void run()
            {
                try
                {
                    for(String line = reader.readLine(); line != null; line = reader.readLine())
                        label.setText(line);
                }
                catch(IOException e)
                {
                    System.out.println("Lost connection with server (probably server closed)");
                    e.printStackTrace();
                    System.exit(0);
                }
            }
        }).start();

        //display the gui
        System.out.println("Displaying");
        frame.pack();
        frame.setResizable(false);
        frame.setLocationByPlatform(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

TestServer.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TestServer
{
    private static boolean multipleClients = true;
    private static List<Client> clients = new ArrayList<Client>();

    public static void main(String[] args) throws Exception
    {
        System.out.println("did the thing");
        ServerSocket ss = new ServerSocket(28000, 0, InetAddress.getByName(null));
        int[] index = {0}; //array so threads can access
        char[] data = {'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'};

        //start accepting connections
        new Thread(new Runnable()
        {
            public void run()
            {
                while(true)
                {
                    try
                    {
                        Client c = new Client(ss.accept());
                        if(multipleClients || clients.isEmpty())
                        {
                            System.out.println("writing " + new String(data));
                            c.write(displayData(data, index[0])); //write initial data
                            synchronized(clients)
                            {
                                clients.add(c);
                            }
                        }
                        else
                            c.write("refused");
                    }
                    catch(IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        //read and write to clients
        String msg = null;
        while(true)
        {
            //read changes
            synchronized(clients)
            {
                for(Client c : clients)
                    if((msg = c.read()) != null)
                    {
                        switch(msg)
                        {
                            case "A":
                                data[index[0]++] = 'A';
                                break;
                            case "B":
                                data[index[0]++] = 'B';
                                break;
                            case "Quit":
                                System.exit(0);
                                break;
                        }
                        index[0] %= data.length;
                        for(Client C : clients)
                            C.write(displayData(data, index[0]));
                    }
            }
            Thread.sleep(50);
        }
    }

    private static String displayData(char[] data, int i)
    {
        return "<html>" + new String(data, 0, i) + "<u>" + data[i] + "</u>" + new String(data, i + 1, data.length - i - 1) + "</html>";
    }

    private static class Client
    {
        private BufferedReader reader;
        private BufferedWriter writer;
        private Queue<String> readBuffer;
        private Client me;

        public Client(Socket s) throws IOException
        {
            reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            readBuffer = new LinkedList<String>();
            me = this;

            new Thread(new Runnable()
            {
                public void run()
                {
                    try
                    {
                        for(String line = reader.readLine(); line != null; line = reader.readLine())
                            readBuffer.add(line);
                    }
                    catch(IOException e)
                    {
                        System.out.println("Client disconnected");
                        e.printStackTrace();
                        synchronized(clients)
                        {
                            clients.remove(me); //remove(this) attempts to remove runnable from clients
                        }
                        System.out.println("removed " + clients.isEmpty());
                    }
                }
            }).start();
        }

        public String read()
        {
            return readBuffer.poll();
        }

        public void write(String s)
        {
            try
            {
                writer.write(s);
                writer.newLine();
                writer.flush();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
  1. 当您单击 window 中的“X”按钮时,您可以将框架设置为 HIDE_ON_CLOSE

  2. 您需要创建类似这样的代码:

  3. 检查我们是否有 2 个具有不同操作的按钮(其中一个是在关闭框架后将其设置为可见)尝试 {

     Main_view frame = new Main_view(); frame.setVisible(true); if (SystemTray.isSupported()) { SystemTray tray = SystemTray.getSystemTray(); TrayIcon trayIcon = null; //Listener for exit button ActionListener ExitListener = new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }; //Listener for display button ActionListener DisplayListener = new ActionListener() { public void actionPerformed(ActionEvent e) { frame.setVisible(true); } }; //Menu when you right click the icon PopupMenu popup = new PopupMenu(); //Buttons to show MenuItem displayButton = new MenuItem("Display"); MenuItem exitButton = new MenuItem("Exit"); //add the previous actions made it exitButton.addActionListener(ExitListener); displayButton.addActionListener(DisplayListener); //add to the popup popup.add(displayButton); popup.add(exitButton); // URL: MyProject/src/MyGUI/check.png // Small icon on secondary taskbar Image image= ImageIO.read(getClass().getResource("/MyGUI/check.png")); trayIcon = new TrayIcon(image, "App name", popup); trayIcon.setImageAutoSize(true); trayIcon.addActionListener(DisplayListener); trayIcon.addActionListener(ExitListener); try { tray.add(trayIcon); } catch (AWTException e) { System.err.println(e); } //... } else { // disable tray option in your application or // perform other actions }

结果

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM