Swing 自动锁定 锁屏功能

11年前
.在网上搜集的一些关于Swing锁屏的Java代码.
.记录备用.
.
import java.awt.BorderLayout;  import java.awt.EventQueue;  import java.awt.FlowLayout;  import java.awt.Toolkit;  import javax.swing.*;  import javax.swing.border.EmptyBorder;  import java.awt.Dimension;  import java.awt.Color;  import net.miginfocom.swing.MigLayout;  import java.awt.Font;  import javax.swing.border.EtchedBorder;  import com.gohighsoft.db.DBSet;  import com.pos.LoginDialog;  import com.pos.dao.WorkersDao;  import java.awt.event.KeyAdapter;  import java.awt.event.KeyEvent;    public class LockFrame extends JDialog {   BorderLayout borderLayout1 = new BorderLayout();   JButton jButton2 = new JButton();   boolean isOK = true;   JLabel jlableInfo = null;   private boolean canRunCount = true;   private JPasswordField passwordField;   private JLabel label_3;  public static void main(String[] args){   LockFrame lock = new LockFrame(null, "系统锁屏", true);   lock.setVisible(true);  }   public LockFrame(JFrame jframe, String str, boolean bool) {    super(jframe, str, true);    setSize(300, 130);  //这个方法尤为重要,只要屏蔽了右上角的关闭按钮    setUndecorated(true);  //设置总是将dialog显示在屏幕的最前面    setAlwaysOnTop(true);    setLocation(      (Toolkit.getDefaultToolkit().getScreenSize().width - getWidth()) / 2,      (Toolkit.getDefaultToolkit().getScreenSize().height - getHeight()) / 2);    setPreferredSize(new Dimension(200, 130));    getContentPane().setLayout(new BorderLayout(0, 0));    JPanel rootPanel = new JPanel();    rootPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(0,      255, 255), null));    getContentPane().add(rootPanel, BorderLayout.CENTER);    rootPanel.setLayout(new BorderLayout(0, 0));    JPanel panel = new JPanel();    panel.setPreferredSize(new Dimension(10, 60));    rootPanel.add(panel, BorderLayout.NORTH);    panel.setLayout(new MigLayout("", "[][][][]", "[][]"));    JLabel label = new JLabel(      "\u7CFB\u7EDF\u8FD0\u884C\u6B63\u5E38\uFF0C\u4F46\u5DF2\u9501\u5B9A\u3002");    label.setFont(new Font("宋体", Font.PLAIN, 14));    panel.add(label, "cell 1 0");    JLabel label_1 = new JLabel(      "        请您输入登录的密码解锁! ");    label_1.setFont(new Font("宋体", Font.PLAIN, 14));    panel.add(label_1, "cell 1 1");    JPanel panel_1 = new JPanel();    panel_1.setPreferredSize(new Dimension(10, 5));    rootPanel.add(panel_1, BorderLayout.CENTER);    panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));    JSeparator separator = new JSeparator();    separator.setForeground(new Color(0, 255, 255));    separator.setPreferredSize(new Dimension(280, 2));    panel_1.add(separator);    JPanel panel_2 = new JPanel();    panel_2.setPreferredSize(new Dimension(10, 60));    rootPanel.add(panel_2, BorderLayout.SOUTH);    panel_2.setLayout(null);    JLabel label_2 = new JLabel("\u5BC6\u7801\uFF1A");    label_2.setBounds(26, 10, 36, 15);    panel_2.add(label_2);    passwordField = new JPasswordField();    passwordField.setBounds(66, 7, 210, 21);    passwordField.addKeyListener(new KeyAdapter() {     @Override     public void keyPressed(KeyEvent event) {      System.out.println(event.getKeyCode());      if (event.getKeyCode() == 10) {       String pw = passwordField.getText();       //获取登录的用户密码       if (pw.equals("123456")) {        dispose();       } else {        label_3.setText("对不起,请您输入正确的密码!");        passwordField.setText("");        return;       }      }     }    });    passwordField.setPreferredSize(new Dimension(210, 21));    panel_2.add(passwordField);    label_3 = new JLabel("");    label_3.setBackground(Color.ORANGE);    label_3.setBounds(66, 35, 210, 15);    panel_2.add(label_3);   }  }
.
.
.
public class Demo6 {      public static void main(String[] args) {          JFrame frame = new JFrame("Test");          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);          Listener listener = new Listener();          Toolkit.getDefaultToolkit().addAWTEventListener(listener,                  AWTEvent.MOUSE_EVENT_MASK);          Toolkit.getDefaultToolkit().addAWTEventListener(listener,                  AWTEvent.FOCUS_EVENT_MASK);          Toolkit.getDefaultToolkit().addAWTEventListener(listener,                  AWTEvent.KEY_EVENT_MASK);          frame.setSize(new Dimension(500, 500));          frame.setVisible(true);      }      static class Listener implements AWTEventListener {          public void eventDispatched(AWTEvent event) {              System.out.println("Handle Event: " + event.getClass());          }      }  }
.
.
https://code.google.com/p/sprbus3/source/browse/?repo=sprbus-hdwangyuan
package com.sprbus.swing.hdwangyuan.panel.lockscreen;    import java.awt.BorderLayout;  import java.awt.Color;  import java.awt.FlowLayout;  import java.awt.Toolkit;  import java.awt.event.ActionEvent;  import java.awt.event.ActionListener;    import javax.swing.JButton;  import javax.swing.JFrame;  import javax.swing.JLabel;  import javax.swing.JPanel;  import javax.swing.JPasswordField;    /**   * @author jnzhangyq   * 锁屏功能模块   */  public class LockScreenPanel extends JPanel {     private JFrame mainFrame;   private JPasswordField inputField;   private JLabel inputLabel;   private JButton subButton;   private JLabel msgLabel;   private JButton setHookBtn;     public LockScreenPanel(JFrame mainFrame) {    this.mainFrame = mainFrame;    inputField = new JPasswordField(20);    inputLabel = new JLabel("请输入密码");    subButton = new JButton("解除锁定 提交 ( 测试阶段 密码为 1 )  ");    setHookBtn = new JButton("锁住屏幕");    msgLabel = new JLabel();    init();     }     private void init() {        this.setLayout(new FlowLayout());    this.add(setHookBtn);    this.add(inputField);    this.add(inputLabel);    this.add(subButton);    this.add(msgLabel);    addEventHandle();     // 启动后,立即将程序锁定    setKeyboardHook();     }     /**    * 添加面板中的各个组件的事件处理    */   private void addEventHandle() {      setHookBtn.addActionListener(new ActionListener() {     public void actionPerformed(ActionEvent arg0) {                                  inputField.setText("");      setKeyboardHook();     }    });      subButton.addActionListener(new ActionListener() {     public void actionPerformed(ActionEvent event) {      String pwd = inputField.getText();      if ("1".equals(pwd)) {       unsetKeyboardHook();       msgLabel.setText("");      inputField.setText("");       LockScreenPanel.this.setScreenToNormal();      } else {       msgLabel.setText("对不起,密码错误");       msgLabel.setForeground(Color.red);       inputField.setText("");       }     }    });   }     private void setKeyboardHook() {      setHookBtn.setEnabled(false);    subButton.setEnabled(true);    LockScreenUtil.setKeyboardHook();    this.setScreenToLock();     }     private void unsetKeyboardHook() {    setHookBtn.setEnabled(true);    subButton.setEnabled(false);    LockScreenUtil.unsetKeyboardHook();    this.setScreenToNormal();     }     private void setScreenToLock() {     // 想重新设这大小和 属性,必须先调用 dispose 方法    mainFrame.dispose();    // 设置没有关闭按钮    mainFrame.setUndecorated(true);    // 设置总在最前端    mainFrame.setAlwaysOnTop(true);    // 重新显示    mainFrame.setVisible(true);   }     private void setScreenToNormal() {    // 想重新设这大小和 属性,必须先调用 dispose 方法    mainFrame.dispose();    // 设置没有关闭按钮失效    mainFrame.setUndecorated(false);    // 设置总在最前端失效    mainFrame.setAlwaysOnTop(false);    // 重新显示    mainFrame.setVisible(true);   }     private void showByFrame() {      mainFrame.setSize(      (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth(),       (int) Toolkit.getDefaultToolkit().getScreenSize()      .getHeight());                  mainFrame.setLayout(new BorderLayout());                  mainFrame.add(this,BorderLayout.CENTER);    mainFrame.setLocation(0, 0);    mainFrame.setVisible(true);    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }     public static void main(String[] args) {    JFrame frame = new JFrame();    new LockScreenPanel(frame).showByFrame();   }  }
.
.
package show;          import java.awt.*;     import java.awt.image.ColorModel;     import java.awt.event.*;     import java.io.BufferedReader;     import java.io.File;     import java.io.FileReader;     import java.io.FileWriter;     import java.io.IOException;          import javax.swing.*;     import javax.swing.border.Border;          import com.sun.java.swing.plaf.windows.resources.windows;          public class ShowMian extends JFrame {              JFrame lockjf;// 锁屏界面         boolean isexit = false;         JPanel lockjp = new JPanel();;         JLabel jl_username;         JLabel jl_password;         JButton jb_ensure;// 确定按钮         JButton jb_result;// 撤消按钮         JTextField jtf_username;// 用户名         JPasswordField jtf_password;// 用户密码         // 用来得到屏幕的分辨率         Toolkit toolkit;         // 用来接受屏幕返回的分辨率         int xscreen;// 屏幕的x坐标         int yscreen;// 屏幕的y坐标         // 定义线程让窗体每秒获得一次焦点         Thread thread;              public ShowMian() {             // TODO Auto-generated constructor stu             // 初始化界面             lockjp = new driver();             lockjf = this;             jl_username = new JLabel("用户名:");             jl_password = new JLabel("密  码:");             jtf_username = new JTextField();             jtf_password = new JPasswordField();             jb_ensure = new JButton("确定");             jb_result = new JButton("取消");             // 得到当前的分辨率             toolkit = this.getToolkit();             final Dimension dimension = toolkit.getScreenSize();             xscreen = dimension.width;             yscreen = dimension.height;             // System.out.println(xscreen + ":" + yscreen);             // 设置主窗体的大小                  // 把各个组件注册到jframe             add(lockjp);             lockjp.setLayout(null);             lockjp.add(jl_username);             lockjp.add(jl_password);             lockjp.add(jtf_username);             lockjp.add(jtf_password);             lockjp.add(jb_ensure);             lockjp.add(jb_result);             // 设置各个组件的位置             this.setBounds(0, 0, 1280, 800);             // lable的设置             jl_username.setBounds(xscreen - 270, yscreen - 150, 60, 20);             jl_password.setBounds(jl_username.getX(), jl_username.getY() + 60, 60,                     20);             // textare的设置             jtf_username.setBounds(jl_username.getX() + 60, jl_username.getY(),                     140, 20);             jtf_username.setBorder(null);             jtf_password.setBounds(jl_password.getX() + 60, jl_password.getY(),                     140, 20);             jtf_password.setBorder(null);             // button的设置             jb_ensure.setBounds(jl_username.getX(), jl_username.getY() + 110, 60,                     30);             jb_result.setBounds(jb_ensure.getX() + 140, jb_ensure.getY(), 60, 30);             // 设置按钮事件             jb_ensure.addActionListener(new ActionListener() {                      public void actionPerformed(ActionEvent arg0) {                     // System.out.println(jtf_username.getText().equals("wayking")+":"+jtf_password.getText().equals("2925138"));                     // TODO Auto-generated method stub                     System.out.println(jtf_password.getPassword());                     if (jtf_username.getText().equalsIgnoreCase("wayking")                             && jtf_password.getText().equalsIgnoreCase("2925138")) {                         // System.out.println("11111111111111111111111111");                         System.exit(1);                     } else {                         jtf_username.setText("");                         jtf_password.setText("");                     }                 }                  });             jb_result.addActionListener(new ActionListener() {                      public void actionPerformed(ActionEvent arg0) {                     // TODO Auto-generated method stub                     jtf_username.setText("");                     jtf_password.setText("");                 }             });             // 设置焦点             thread = new Thread(new Runnable() {                      public void run() {                     while (true) {                         toFront();                         try {                             thread.sleep(100);                         } catch (InterruptedException e) {                             // TODO Auto-generated catch block                             e.printStackTrace();                         }                     }                 }             });             // 去掉工具栏             setUndecorated(true);                  // 添加窗口监听             this.addWindowListener(new WindowListener() {                      public void windowActivated(WindowEvent arg0) {                     // TODO Auto-generated method stub                      }                      public void windowClosed(WindowEvent arg0) {                     // TODO Auto-generated method stub                      }                      public void windowClosing(WindowEvent arg0) {                     // DO_NOTHING_ON_CLOSE(在 WindowConstants 中定义):不执行任何操作;要求程序在已注册的                     // WindowListener 对象的 windowClosing 方法中处理该操作。                     // HIDE_ON_CLOSE(在 WindowConstants 中定义):调用任意已注册的 WindowListener                     // 对象后自动隐藏该窗体。                     // DISPOSE_ON_CLOSE(在 WindowConstants 中定义):调用任意已注册                     // WindowListener 的对象后自动隐藏并释放该窗体。                     // EXIT_ON_CLOSE(在 JFrame 中定义):使用 System exit                     // 方法退出应用程序。仅在应用程序中使用。                     // System.out.println("2222222222222");                     setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);// 不执行任何操作;要求程序在已注册的                 }                      public void windowDeactivated(WindowEvent arg0) {                     // TODO Auto-generated method stub                      }                      public void windowDeiconified(WindowEvent arg0) {                     // TODO Auto-generated method stub                      }                      public void windowIconified(WindowEvent arg0) {                     // TODO Auto-generated method stub                 }                      public void windowOpened(WindowEvent arg0) {                     // TODO Auto-generated method stub                      }             });             try {                  //建立FileWriter对象,并实例化fw                   FileWriter fw = new FileWriter("mymusic.txt");                   //将字符串写入文件                   fw.write("mymusic");                   fw.close();             } catch (Exception e) {                 // TODO Auto-generated catch block                 e.printStackTrace();             }             //添加音乐             //读取用户配置的音乐信息             try {                 FileReader reader=new FileReader("mymusic.txt");//实例化读入对象                 BufferedReader readers=new BufferedReader(reader);                 String musicsrc= readers.readLine();//得到音乐路径                 Runtime.getRuntime().exec("cmd /c e://"+musicsrc+".mp3");//调用cmd运行命令                 readers.close();//关闭对象                 reader.close();             } catch (IOException e) {                 // TODO Auto-generated catch block                 System.out.println("没有找到指定音乐");             }             // 开始获取焦点             thread.start();             setVisible(true);         }              // class driwer extends JPanel {         // protected void paintComponents(Graphics g) {         //                   // }         // }         public static void main(String[] args) {             new ShowMian();         }              // 画出面板上的图片         // 如果要画图,必须用一个类继承panel 然后重写其paintcomponent方法         class driver extends JPanel {             @Override             protected void paintComponent(Graphics g) {                 g.setColor(null);                 // g.drawImage(new ImageIcon("2.jpg").getImage(), 0, 0, this                 // .getWidth(), this.getHeight(), this);                 g.drawImage(new ImageIcon("./3.jpg").getImage(), 0, 0, this                         .getWidth(), this.getHeight(), this);                 g.drawRect(960, 600, 320, 200);                 g.drawRect(960, 600, 318, 198);                      // super.paintComponent(arg0);             }         }          }