如何捕获在后台运行的java应用程序的已停止事件

时间:2017-03-01 15:30:59

标签: java

我开发了一个java应用程序,它会在加载窗口后系统打开时自动调用。系统用户必须输入有关他的详细信息并访问计算机。该应用程序将消失并在后台运行。现在当他关闭系统时,后台应用程序将停止,在停止时我想捕获事件并更新状态作为我的数据库中的注销。是否有捕获事件的功能。

    package userauth;
    import java.awt.Cursor;
    import java.awt.SystemColor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.URISyntaxException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DocumentFilter;

    class Home
    {
    static JFrame frame,frame1;
    static String facname,stdid;
   Home() throws IOException,URISyntaxException
   {

    frame = new JFrame("Application");
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.setUndecorated(true);

    frame.setAlwaysOnTop(true);
    JPanel contentPane = new JPanel();
    contentPane.setOpaque(true);
    contentPane.setBackground(SystemColor.activeCaption);
    contentPane.setLayout(null);
    java.net.URL url = Home.class.getResource("/fac.png");

    ImageIcon facimage = new ImageIcon(url);
    JLabel faclab = new JLabel(facimage);

    faclab.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    faclab.addMouseListener(new MouseAdapter() {   
        public void mouseClicked(MouseEvent e) {
         if (e.getClickCount() > 0) {
             facframe();
                             }

      }
   });



    java.net.URL url1 = Home.class.getResource("/user.png");
    ImageIcon stuimage = new ImageIcon(url1);
    JLabel stulab = new JLabel(stuimage);

    stulab.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    stulab.addMouseListener(new MouseAdapter() {


        public void mouseClicked(MouseEvent e) {
             if (e.getClickCount() > 0) {
                 studentframe();
                                 }

          }
       });


    JLabel facl=new JLabel("Faculty");
    facl.setHorizontalAlignment(SwingConstants.CENTER);
    JLabel stdl=new JLabel("Student");
    stdl.setHorizontalAlignment(SwingConstants.CENTER);
    faclab.setBounds(450,250, 200, 200);
    stulab.setBounds(800,250, 200, 200);
    facl.setBounds(450, 475, 200, 20);
    stdl.setBounds(800,475,200,20);
    contentPane.add(faclab);
    contentPane.add(stulab);
    contentPane.add(facl);
    contentPane.add(stdl);
   frame.setContentPane(contentPane);
   frame.setSize(1500, 1000);
   frame.setLocationRelativeTo(null);
    frame.setVisible(true);

   }
  protected static void facframe()
  {
    frame1 = new JFrame("Faculty");
    frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame1.setUndecorated(true);
    frame1.setAlwaysOnTop(true);
    JPanel contentPane = new JPanel();
    contentPane.setOpaque(true);
    contentPane.setBackground(SystemColor.activeCaption);
    contentPane.setLayout(null);
    JLabel facnamefieldl=new JLabel("Faculty Name");
    JLabel deptlabel=new JLabel("Department");
    deptlabel.setBounds(400, 380, 140, 25);
    contentPane.add(deptlabel);
    facnamefieldl.setBounds(400, 350, 140, 25);
    contentPane.add(facnamefieldl);
    JTextField facname = new JTextField("");

    facname.setBounds(560, 350,200, 25);
    String depts[]={"Select Dept","Automobile","Mechanical(Btech)","Civil(Btech)","IT","CSE","ECE","EEE","MBA","Training","Mechanical(Poly tech.)","Civil(Poly tech.)","EEE(Poly tech.)"};        
    JComboBox deptnames=new JComboBox(depts);    
    deptnames.setBounds(560,380,150,25);    
    JButton submit=new JButton("Submit");
    JButton back=new JButton("Back");
    submit.setLayout(null);
    back.setBounds(560,445 , 80, 25);
    submit.setBounds(560,415 , 80, 25);

    contentPane.add(deptnames);
    contentPane.add(back);
    contentPane.add(facname);
    contentPane.add(submit);


    frame1.setSize(1500, 1000);
    frame1.setContentPane(contentPane);
    frame1.setLocationRelativeTo(null);
    frame1.setVisible(true);
    frame.setVisible(false);
    back.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {

        frame1.setVisible(false);
        frame.setVisible(true);
      }
    });
    submit.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {

          facins(facname.getText(),deptnames.getSelectedItem().toString());


      }
        });

    }
    protected static void facins(String fname,String dept)
    {
        try
        {
            InetAddress ip=InetAddress.getLocalHost();
            String hostname=ip.getHostName();
            String str=ip.toString();
            facname=fname;

            String ipaddress=str.substring(str.indexOf("/")+1);
            if (fname.equals("")||dept.equals("Select Dept")){
                frame1.setAlwaysOnTop(false);
                JOptionPane.showMessageDialog(null, "please fill all the fields");
                frame1.setAlwaysOnTop(true);

            }
            else
            {

            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/userauth","root","");

            PreparedStatement stmt=conn.prepareStatement("insert into faculty(facname,dept,ipaddress,hostname,date)values(?,?,?,?,NOW())");
            stmt.setString(1, fname);
            stmt.setString(2, dept);
            stmt.setString(3, ipaddress);
            stmt.setString(4,hostname);

            int i=stmt.executeUpdate();
            if(i>0)
            {
                frame1.setAlwaysOnTop(false);
                JOptionPane.showMessageDialog(null, "Sucessfully updated");
                frame1.setVisible(false);
                frame.setVisible(false);




            }
            }

        }
        catch(Exception my)
        {
            System.out.println(my);
        }

     }
    protected static void studentframe()
    {

    frame1 = new JFrame("Student");
    frame1.setUndecorated(true);
    frame1.setAlwaysOnTop(true);
    frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    JPanel contentPane = new JPanel();
    contentPane.setOpaque(true);
    contentPane.setBackground(SystemColor.activeCaption);
    contentPane.setLayout(null);
    JTextField  stname=new JTextField("");
     stname.setBounds(560, 350,200, 25);
     JTextField  stuid = new JTextField("");
    stuid.setBounds(560,380,150,25);
    JLabel namel=new JLabel("Student Name");
    JLabel idl=new JLabel("Student ID");
    namel.setBounds(400, 350, 140, 25);
    idl.setBounds(400, 380, 140, 25);
    JButton submit=new JButton("Submit");
    JButton back=new JButton("Back");
    submit.setLayout(null);
    back.setBounds(560,445 , 80, 25);
    submit.setBounds(560,415 , 80, 25);
    contentPane.add(namel);
    contentPane.add(idl);

    contentPane.add(stname);
    contentPane.add(stuid);
    contentPane.add(submit);
    contentPane.add(back);

    frame1.setSize(1500,700 );
    frame1.setContentPane(contentPane);
    frame1.setLocationRelativeTo(null);
    frame1.setVisible(true);
    frame.setVisible(false);
    DocumentFilter filter = new UppercaseDocumentFilter();
    AbstractDocument firstNameDoc = (AbstractDocument) stuid.getDocument();
    firstNameDoc.setDocumentFilter(filter);

    back.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        // display/center the jdialog when the button is pressed
        frame1.setVisible(false);
        frame.setVisible(true);
      }
    });


    submit.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    try
    {
        Home.studentins(stname.getText(),stuid.getText());

    }
    catch (Exception e2)
    {

    }
    }


    });

    }

    protected static void studentins(String stuname,String id) throws IOException
    {
      InetAddress ip=InetAddress.getLocalHost();

     String hostname=ip.getHostName();
     String str=ip.toString();
     stdid=id;
        String ipaddress=str.substring(str.indexOf("/")+1);
    if(stuname.equals("")||id.equals(""))
    {
        frame1.setAlwaysOnTop(false);
        JOptionPane.showMessageDialog(null, "please fill all the fields");
        frame1.setAlwaysOnTop(true);

    }
    else
    {
        try{


    Class.forName("com.mysql.jdbc.Driver");
    Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/userauth","root","");
    PreparedStatement stmt=conn.prepareStatement("insert into students(stname,stid,hostname,ipaddress,date)values(?,?,?,?,NOW())");
    stmt.setString(1, stuname);
    stmt.setString(2, id);
    stmt.setString(3,hostname);
    stmt.setString(4,ipaddress);

    int i=stmt.executeUpdate();
    if(i>0)
    {
        frame1.setAlwaysOnTop(false);
        JOptionPane.showMessageDialog(null, "Sucessfully updated");
        frame1.setVisible(false);
        frame.setVisible(false);    


        }
        }
        catch(Exception a)
        {
            System.out.println(a);
          }
         }


       }



     public static void main(String args[]) throws IOException, URISyntaxException
   {
    new Home();
       Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/userauth","root","");
                    if(!facname.equals(""))
                    {
                    PreparedStatement stmt=conn.prepareStatement("update faculty set status=? where facname=?");
                    stmt.setString(1, "loggedout");
                    stmt.setString(2,stdid);
                    }
                    else if(!stdid.equals(""))
                    {
                        PreparedStatement stmt=conn.prepareStatement("update students set status=? where stid=?");
                        stmt.setString(1, "loggedout");
                        stmt.setString(2,stdid);

                    }



                } catch (Exception e) {

                    e.printStackTrace();
                }




            }
        });


       }
    }


    class UppercaseDocumentFilter extends DocumentFilter {

       @Override
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
    fb.insertString(offset, text.toUpperCase(), attr);
      }

@Override
     public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
    fb.replace(offset, length, text.toUpperCase(), attrs);
      }

      }

1 个答案:

答案 0 :(得分:2)

您可以在

时注册要运行的Thread
  

当最后一个非守护程序线程退出或时,程序正常退出   当调用exit(等效,System.exit)方法时,或

     

虚拟机终止以响应用户中断,   例如键入^ C或系统范围的事件,例如用户注销或   系统关闭。

请参阅:Runtime.addShutdownHook(Thread)

以下链接中的示例:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { database.close(); }
});

关于它的一些FaQ here