当鼠标位于2个面板的交叉区域上时,更改光标

时间:2012-04-19 01:43:37

标签: java swing panel

我在JFrame上有2个Jpanel(左侧面板和右侧面板)。当鼠标悬停在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));
        };

但它没有用..

2 个答案:

答案 0 :(得分: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));
                  };
            }

        });
    }

答案 1 :(得分:0)

正如Jeffey的建议,我应该使用JSlitPane来处理。