将其隐藏在关闭

时间:2018-01-29 20:32:31

标签: java testing software-design

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

我可以正常启动我的应用程序。它创建了主窗口。我也在使用setDefaultCloseOperation(HIDE_ON_CLOSE)我也试过DISPOSE_ON_CLOSE,但它们都有相同的效果。因此,当我关闭它时窗口关闭。但是,当我点击停靠栏中的图标时,窗口将无法打开。

我希望应用程序像Safari一样打开,你可以关闭Safari,但它仍然在后台运行,当你点击破折号中的图标时,如果你没有打开它会打开一个新窗口已经。

2 个答案:

答案 0 :(得分:0)

要最小化而不是关闭,请使用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);
    }
});

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

答案 1 :(得分:0)

如上所述,听起来您需要两个流程,一个用于渲染,另一个用于处理数据

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

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

在同一文件夹中编译并运行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();
            }
        }
    }
}