当前位置: 首页 > 面试题库 >

Windows关闭时的Java退出

佘茂才
2023-03-14
问题内容

我有这个代码。如果检测到计算机正在关闭,我想退出Java应用程序。我有这个问题,如果在Windows上单击“关闭”,我的Java应用程序会与Android应用程序连接断开连接。我想显示Java应用程序已断开连接,否则将退出。

//  Copyright 2012
//  Android Remote Desktop Server Ver. 1.0


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.Random;

public class ServerWindow implements ActionListener{

    private RemoteDataServer server;

    private Thread sThread; //server thread

    private static final int WINDOW_HEIGHT = 200;
    private static final int WINDOW_WIDTH = 350;

    private String ipAddress;

    private JFrame window = new JFrame("Remote Control for Android");

    private JLabel addressLabel = new JLabel("");
    private JLabel portLabel = new JLabel("Android Remote Control Port: ");
    private JTextArea[] buffers = new JTextArea[3];
    private JTextField portTxt = new JTextField(5);
    private JLabel serverMessages = new JLabel("Not Connected");

    private JButton connectButton = new JButton("Start Server");
    private JButton disconnectButton = new JButton("Stop Server");

    public boolean connected = false;




    //@SuppressWarnings("deprecation")
    public ServerWindow(){
        server = new RemoteDataServer();

        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        connectButton.addActionListener(this);
        disconnectButton.addActionListener(this);

        Container c = window.getContentPane();
        c.setLayout(new FlowLayout());

        try{
            InetAddress ip = InetAddress.getLocalHost();
            ipAddress = ip.getHostAddress();
            addressLabel.setText("Android Remote Control Server IP Address: "+ipAddress);
        }
        catch(Exception e){addressLabel.setText("IP Address Could Not be Resolved");}

        int x;
        for(x = 0; x < 3; x++){
            buffers[x] = new JTextArea("", 1, 30);
            buffers[x].setEditable(false);
            buffers[x].setBackground(window.getBackground());
        }

        portTxt.setEditable(false);
        Random portRandom = new Random();
        for (int i = 0; i < 10; i++) {

          int port = portRandom.nextInt(4998) + 1;
          int portNum = 5000+port;
          String portString = Integer.toString(portNum);
          portTxt.setText(portString);
          }

        c.add(addressLabel);
        c.add(buffers[0]);
        c.add(portLabel);
        //portTxt.setText("5444");
        c.add(portTxt);
        c.add(buffers[1]);
        c.add(connectButton);
        c.add(disconnectButton);
        c.add(buffers[2]);
        c.add(serverMessages);

        window.setLocationRelativeTo(null);
        window.setVisible(true);
        window.setResizable(false);

    }


    public void actionPerformed(ActionEvent e){
        Object src = e.getSource();

        if(src instanceof JButton){
            if((JButton)src == connectButton){
                int port = Integer.parseInt(portTxt.getText());
                runServer(port);
            }

            else if((JButton)src == disconnectButton){
                closeServer();
            }
        }
    }

    public void runServer(int port){
        if(port <= 9999){
            server.setPort(port);
            sThread = new Thread(server);
            sThread.start();
        }
        else{
            serverMessages.setText("The port Number must be less than 10000");
        }
    }

    public void closeServer(){
        serverMessages.setText("Disconnected");
        server.shutdown();
        connectButton.setEnabled(true);
    }

    public static void main(String[] args){
        new ServerWindow();
    }

    public class RemoteDataServer implements Runnable{
        int PORT;
        private DatagramSocket server;
        private byte[] buf;
        private DatagramPacket dgp;

        private String message;
        private AutoBot bot;

        public RemoteDataServer(int port){
            PORT = port;
            buf = new byte[1000];
            dgp = new DatagramPacket(buf, buf.length);
            bot = new AutoBot();
            serverMessages.setText("Not Connected");
        }

        public RemoteDataServer(){
            buf = new byte[1000];
            dgp = new DatagramPacket(buf, buf.length);
            bot = new AutoBot();
            serverMessages.setText("Not Connected");
        }

        public String getIpAddress(){
            String returnStr;
            try{
                    InetAddress ip = InetAddress.getLocalHost();
                    returnStr = ip.getCanonicalHostName();
            }
            catch(Exception e){ returnStr = new String("Could Not be Resolve Ip Address");}
            return returnStr;
        }

        public void setPort(int port){
            PORT = port;
        }

        public void shutdown(){
            try{server.close();
                serverMessages.setText("Disconnected");}
            catch(Exception e){}
        }
        public void run(){
            //boolean connected = false;
            try {InetAddress ip = InetAddress.getLocalHost(); 
                serverMessages.setText("Waiting for connection on " + ip.getCanonicalHostName());

                server = new DatagramSocket(PORT, ip);

                connected = true;
                connectButton.setEnabled(false);
            }
            catch(BindException e){ serverMessages.setText("Port "+PORT+" is already in use. Use a different Port"); }
            catch(Exception e){serverMessages.setText("Unable to connect");}

            while(connected){
                //Runtime.getRuntime().exit(0);
                // get message from sender
                try{ server.receive(dgp);

                    // translate and use the message to automate the desktop
                    message = new String(dgp.getData(), 0, dgp.getLength());
                    if (message.equals("Connectivity")){
                        //send response to confirm connectivity
                        serverMessages.setText("Trying to Connect");
                        server.send(dgp); //echo the message back
                    }else if(message.equals("Connected")){
                        server.send(dgp); //echo the message back
                    }else if(message.equals("Close")){
                        serverMessages.setText("Controller has Disconnected. Trying to reconnect."); //echo the message back
                    }else{
                        serverMessages.setText("Android Phone Connected to ARD Server");
                        bot.handleMessage(message);
                    }
                }catch(Exception e){
                    serverMessages.setText("Disconnected");
                    connected = false;}
            }

        }
    }
}

问题答案:

假设您要问的问题是“如何检测何时关闭Windows”,请执行以下操作:

您需要一个所谓的“系统关闭挂钩”,它实质上是一个只要Java虚拟机关闭就执行run()方法的线程。程序终止或由于系统范围的事件(例如用户注销或关闭)而发生。

您需要做的就是将这段代码放在程序的启动过程中的某个位置:

Runtime.getRuntime().addShutdownHook(
    new Thread(new Runnable() {
        @Override
        public void run() {
            // this is executed on shut-down. put whatever.
        }
    }));

我希望这回答了你的问题。



 类似资料:
  • 问题内容: 我不知道如何使用此代码: 使用x按钮关闭程序。 问题答案: 你需要线 因为按下X按钮时JFrame的默认行为等效于 因此,几乎所有时候,创建JFrame时都需要手动添加该行 我目前指的是like 中的常量,而不是像先前那样直接声明的常量更能反映意图。

  • 我在Java中使用来自动化。当我的程序退出时,内存中会留下一个实例。我知道我可以使用来关闭当前实例。但是,如果应用程序在任何时候被杀死(例如在调试会话期间),这种清理当然永远不会执行。 我正在寻找一种制作chromedriver的解决方案。exe是Java进程的子进程,因此当Java进程退出时,子进程也会自动终止。解决方案,如运行时。getRuntime()。exec(“taskkill/F/IM

  • 问题内容: 我有使用NetBeans GUI生成器创建的单个帧时,我认为在框架属性的第一选项是默认关闭操作中列出的选项之一:,,及我明白中间的两个,但最新的区别和?我已经尝试过对两者进行测试,但是对我来说它们对我做同样的事情 问题答案: 将终止程序。 将调用该框架,这将使其消失并删除其使用的资源。您无法将其带回去,与隐藏它不同。 参见asloJFrame.dispose()与System.exit

  • 本文向大家介绍Android实现退出时关闭所有Activity的方法,包括了Android实现退出时关闭所有Activity的方法的使用技巧和注意事项,需要的朋友参考一下 本文示例实现了Android退出时关闭所有Activity的功能,分享给大家供大家参考之用。具体方法如下: 一般来说,在Android退出时,有的Activity可能没有被关闭。为了在Android退出时关闭所有的Activit

  • 我有一个带有searchView图标的操作栏。我点击searchView图标,出现softInputMode键盘,我的ListView出现用于搜索。但是,当您关闭searchView时,searchView会关闭,但我无法让ListView在searchView关闭时也关闭。 下面是我在activity_maps中的ListView代码。xml 地图ctivity.java 所以最初当MapsAc

  • 我读了一个关于docker的很好的问题--答案概述了docker的实现细节。我想知道在Windows平台上是否可以做类似的事情。 Docker的Windows替代方案是否存在? 理论上是否可以使用其他(基于Windows的)组件来构建它? 更新1: 稍微相关的问题(沙箱):Windows平台是否有轻量级、可编程的沙箱API? 更新2:: 有关如何在windows上安装docker的信息(无关)-官