在JPanel Child上检测鼠标

时间:2014-05-08 23:16:53

标签: java swing jpanel awt mouselistener

我已经使用MouseAdapter来检测鼠标是否进入或退出JPanel并且它有效有点,因为它无法检测鼠标是否悬停在JPanel上

public class SearchResultPanel extends JPanel{

  private class mousePanelListener extends MouseAdapter{ 
    @Override
    public void mouseEntered(MouseEvent e){
        setHighlightBorder(); //"highlight" the panel
    }
    @Override
    public void mouseExited(MouseEvent e){
        setDefaultBorder(); //"unhighlight" the panel
    }
  }
  private final Border highlightBorder;
  private final Border defaultBorder;

  //ctor
  SearchResultPanel(String data){
        super();
        setLayout(new GridLayout(1,1));

        JTextArea textArea = new JTextArea(data);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setOpaque(false);
        add(textArea);

        addMouseListener(new mouseMotionPanelListener());
        setFocusable(true);

        highlightBorder = BorderFactory.createLineBorder(Color.RED, 5);
        defaultBorder = BorderFactory.createLineBorder(Color.BLACK, 1);
  }


   private void setHighlightBorder(){
    setBorder(highlightBorder);
   }

   private void setDefaultBorder(){
    setBorder(defaultBorder);
   }
}

仅当鼠标位于面板的边缘(轮廓)时,SearchResultPanel才会突出显示。如果它们位于面板内部或外部,它们将返回默认边框。 如何检测鼠标是否在JPanel上,以便JPanel设置其突出显示的边框?

1 个答案:

答案 0 :(得分:1)

请尝试使用addMouseMotionListener方法。