swing創建自定義窗體界面
創建自定義外觀的窗體,主要先了解以下步驟:
- 設置窗口完全透明:AWTUtilities.setWindowOpaque(frame, false);
- 設置窗口無邊緣:frame.setUndecorated(true);
- 設置窗口的ContentPane為要顯示的Pane:frame.setContentPane(myPane);
- 在myPane中放置具體要顯示的內容,也可以重載paint方法進行Java2D繪制。這些paint會直接發生在桌面背景上。 </ul>
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登錄窗口。不過根據這個窗體自定義原理,則可以做出美輪美奐的界面
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!