2012-04-19 38 views
0

我在JFrame上有2個Jpanel(左側面板和右側面板)。當鼠標移動到2個面板的交叉區域上時,如何更改光標?當鼠標移動到2個面板的交叉區域上時更改光標

enter image description here

到目前爲止,我想:

... 
public void mouseMoved(MouseEvent e) { 
      if (leftpanel.contains(e.getPoint()) && rightpanel.contains(e.getPoint())){ 

       frame.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); 

      } 
      else{ frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); 
     }; 

,但它不工作..

+3

根據您嘗試調整的大小,可以考慮使用['JSplitPane'](http://docs.oracle.com/javase/7/docs/api/javax/swing/JSplitPane.html)爲你處理這件事。 – Jeffrey 2012-04-19 01:49:35

+2

如果'leftpanel'和'rightpanel'不相交,第一個謂詞怎麼會是真的? – trashgod 2012-04-19 02:20:57

回答

7

你的問題是如何檢測兩個面板的交叉和改變光標。


    public static void overlapTest() { 
     final JPanel p1 = new JPanel(); 
     final JPanel p2 = new JPanel(); 
     p1.setBackground(Color.RED); 
     p2.setBackground(Color.BLUE); 
     final JPanel container = new JPanel(); 
     container.setLayout(null); 
     container.add(p1); 
     container.add(p2); 
     p1.setBounds(0,0,120,100); 
     p2.setBounds(80,0,120,100); 
     Dimension size = new Dimension(200,100); 
     container.setPreferredSize(size); 
     container.addMouseMotionListener(new MouseMotionListener() { 

      @Override 
      public void mouseDragged(MouseEvent arg0) { 
      } 

      @Override 
      public void mouseMoved(MouseEvent e) { 
       Point pt1 = e.getPoint(); 
       pt1.translate(-p1.getX(), -p1.getY()); 
       Point pt2 = e.getPoint(); 
       pt2.translate(-p2.getX(), -p2.getY()); 
       if (p1.contains(pt1) && p2.contains(pt2)) { 
         System.out.println("both contain: " + e.getPoint()); 
         container.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); 
        } 
        else{ 
         container.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); 
        }; 
      } 

     }); 
    } 
+2

看來我已經回答了被問到的問題,但並不是所期望的...... – ControlAltDel 2012-04-19 02:08:31

0

由於Jeffey的建議,我應該使用JSlitPane來處理。

相關問題