2012-01-26 66 views
2

我有java swing swing應用程序。遊標具有自定義視圖 - 矩形,大小適合整個單元格。我需要光標只在整個單元格上移動。不在一個單元格的範圍內。這個問題是否有一些典型的解決方案?或者,也許有可能使用標準java功能設置步進式光標移動?擺動步進式光標移動

enter image description here

回答

6

我不會實施某種 「步進」 光標。相反,我會完全隱藏光標並以編程方式突出顯示當前單元格。


低於「產出」完整的示例這張截圖的paintComponent方法:

screenshot

public class StepComponent extends JComponent implements MouseMotionListener { 
    private Point point = new Point(0, 0); 

    public StepComponent() { 
     setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
       new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB), 
       new Point(0, 0), "blank cursor")); 
     addMouseMotionListener(this); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     int x = 0, y = 0; 
     while (x < getWidth()) { g.drawLine(x, 0, x, getHeight()); x += 10; } 
     while (y < getHeight()) { g.drawLine(0, y, getWidth(), y); y += 10; } 
     if (point != null) 
      g.fillRect(point.x, point.y, 10, 10); 
    } 
    @Override public void mouseDragged(MouseEvent e) { update(e.getPoint()); } 
    @Override public void mouseMoved(MouseEvent e) { update(e.getPoint()); } 

    private void update(Point p) { 
     Point point = new Point(10 * (p.x/10), 10 * (p.y/10)); 
     if (!this.point.equals(point)) { 
      Rectangle changed = new Rectangle(this.point,new Dimension(10,10)); 
      this.point = point; 
      changed.add(new Rectangle(this.point, new Dimension(10, 10))); 
      repaint(changed); 
     } 
    } 
} 

還有一些測試代碼:

public static void main(String[] args) { 

    JFrame frame = new JFrame("Test"); 

    frame.add(new StepComponent()); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(400, 300); 
    frame.setVisible(true); 
} 
+0

此評論redactor會殺了我...輸入作品只是「完美」 – fland

+0

檢查我的更新答案一個完整的例子! – dacwe

+0

是的,謝謝。我嘗試過這種解決方案之前,甚至使用玻璃面板 - 我認爲重新繪製大多數空板會更快,然後用棋盤重新繪製面板。主要問題是 - 性能。重繪方法需要大量資源。而鼠標移動,特別是當應用程序最大化時,佔用了我所有的處理器時間。 所以這就是爲什麼我決定嘗試使用自定義鼠標光標。 – fland