创建自定义外观的窗体,主要先了解以下步骤:
- 设置窗口完全透明:AWTUtilities.setWindowOpaque(frame, false);
- 设置窗口无边缘:frame.setUndecorated(true);
- 设置窗口的ContentPane为要显示的Pane:frame.setContentPane(myPane);
- 在myPane中放置具体要显示的内容,也可以重载paint方法进行Java2D绘制。这些paint会直接发生在桌面背景上。
1.主窗体文件
package test; import java.awt.Graphics; import javax.swing.*; import com.sun.awt.AWTUtilities; public class TranslucentWindow extends JFrame{ public TranslucentWindow() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setUndecorated(true); AWTUtilities.setWindowOpaque(this, false); setBounds(500, 500, 300, 300); JPanel pane = new JPanel() { @Override public void paint(Graphics g) { super.paint(g); g.drawImage(new ImageIcon("qq.png").getImage(), 0, 0, 348, 265, this); } }; FrameListener moveListener = new FrameListener(this); addMouseListener(moveListener); addMouseMotionListener(moveListener); setSize(348, 265); setContentPane(pane); setVisible(true); } public static void main(String[] args) { new TranslucentWindow(); } }
因为设置了窗口无边缘,所以无法使用鼠标拖动窗体。
下面是实现自定义窗体鼠标拖动。
package test; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class FrameListener extends MouseAdapter { private Point lastPoint = null; private TranslucentWindow window = null; public FrameListener(TranslucentWindow window){ this.window = window; } @Override public void mousePressed(MouseEvent e){ lastPoint = e.getLocationOnScreen(); System.out.println(lastPoint); } @Override public void mouseDragged(MouseEvent e){ System.out.println(e); Point point = e.getLocationOnScreen(); int offsetX = point.x - lastPoint.x; int offsetY = point.y - lastPoint.y; Rectangle bounds = window.getBounds(); bounds.x += offsetX; bounds.y += offsetY; window.setBounds(bounds); lastPoint = point; } }
主要是根据鼠标点击记录坐标,当鼠标拖动结束时再次记录坐标,最后通过setBounds绝对定位窗体。
运行结果截图:
注:窗体上的功能并没有实现,仅仅是窗体的背景图是QQ登录窗口。不过根据这个窗体自定义原理,则可以做出美轮美奂的界面