簡體   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