java:无边框窗口测试

以下代码演示一个focused时有边框,离开后没边框的Java窗口。

test_borderless_undecorated_java_window

import java.awt.AWTEvent;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Test
{
  private static final Timer timer = new Timer();


  public static void main(String[] args)
  {
    final JFrame frmMain = new JFrame("无边窗口测试");
    frmMain.setAlwaysOnTop(true);
    frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JLabel lbl = new JLabel("窗户内", JLabel.CENTER);
    lbl.setPreferredSize(new Dimension(200, 200));
    frmMain.getContentPane().add(lbl);
    frmMain.addWindowFocusListener(new WindowAdapter()
    {
      @Override
      public void windowLostFocus(WindowEvent e)
      {
        if (!frmMain.isUndecorated())
        {
          timer.schedule(new TimerTask()
          {
            @Override
            public void run()
            {
              if (!frmMain.isFocused() && !frmMain.isUndecorated())
              {
                frmMain.dispose();
                lbl.setText("窗户外");
                frmMain.setUndecorated(true);
                frmMain.setVisible(true);
              }
            }
          }, 100);
        }
      }
    });
    final long eventMask = AWTEvent.MOUSE_EVENT_MASK;
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener()
    {
      public void eventDispatched(AWTEvent e)
      {
        if (e.getID() == MouseEvent.MOUSE_PRESSED)
        {
          if (frmMain.isUndecorated())
          {
            timer.schedule(new TimerTask()
            {
              @Override
              public void run()
              {
                if (frmMain.isFocused() && frmMain.isUndecorated())
                {
                  frmMain.dispose();
                  lbl.setText("窗户内");
                  frmMain.setUndecorated(false);
                  frmMain.setVisible(true);
                }
              }
            }, 100);
          }
        }
      }
    }, eventMask);
    frmMain.pack();
    frmMain.setVisible(true);
  }
}