首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Swing 開發利器:SwingUtilities 核心工具方法全覽

     編輯:Java 相關知識

SwingUtilities 簡介

javax.swing.SwingUtilities 封裝了大量 Swing 內部使用的實用靜態方法,涵蓋坐標轉換、幾何計算、鼠標判斷、焦點查找、繪製佈局等,開發者可直接調用。

1. 坐標轉換

  • convertMouseEvent(source, e, destination):組件間鼠標事件轉發。
  • convertPoint(source, x, y, dest) / convertPoint(source, Point, dest):點坐標跨組件轉換。
  • convertPointFromScreen(Point, Component) / convertPointToScreen(Point, Component):屏幕坐標與組件坐標互轉。
  • convertRectangle(source, Rectangle, dest):矩形區域跨組件轉換。

2. 幾何計算

  • computeDifference(Rectangle, Rectangle):兩矩形差集(返回矩形數組)。
  • computeIntersection(x, y, w, h, dest):交集。
  • computeUnion(x, y, w, h, dest):並集。
  • computeStringWidth(FontMetrics, String):字符串像素寬度。
  • isRectangleContainingRectangle(a, b):判斷 a 是否包含 b。

3. 鼠標按鍵判斷

  • isLeftMouseButton(MouseEvent)
  • isMiddleMouseButton(MouseEvent)
  • isRightMouseButton(MouseEvent)

4. 訪問控制與層級查找

  • findFocusOwner(Component):獲取焦點擁有者。
  • getRoot(Component):獲取根組件(Window/Applet)。
  • getRootPane(Component):獲取 JRootPane。
  • windowForComponent(Component):獲取所屬 Window。

5. 組件繪製與標籤佈局

  • layoutCompoundLabel(...):計算標籤/按鈕中文本、圖標的佈局矩形(兩個重載:基礎版 / JComponent 版)。
  • paintComponent(Graphics, Component, Container, x, y, w, h) / paintComponent(Graphics, Component, Container, Rectangle):在任意 Graphics 上繪製組件外觀。

典型應用場景

  • 自定義組件開發:坐標轉換、繪製邏輯復用。
  • 拖拽框架:屏幕/組件坐標互轉。
  • 彈出菜單定位:convertPointToScreen 計算屏幕位置。
  • 碰撞檢測:computeIntersection 判斷區域重疊。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved