如何使用mouselistener更改面板?

时间:2013-04-16 13:00:46

标签: java swing jpanel awt mouselistener

我希望面板在鼠标悬停时展开并显示按钮和内容,然后退出面板的鼠标必须返回原始大小。 到目前为止,我只能打印一条消息:

public JPanel GUI()
{
     final JPanel totalGUI = new JPanel();
     totalGUI.setBackground(Color.blue);
     totalGUI.setLayout(null);


    //+++++++++++++++
    //  -   -   -   -   -   -   PANEL 1!
    //+++++++++++++++       

    JPanel SearchPanel = new JPanel();  //Create new grid bag layout
    SearchPanel.setLocation(5, 5);
    SearchPanel.setSize(420, 120);
    totalGUI.add(SearchPanel);

    SearchPanel.addMouseListener(this);


    return totalGUI;
}

public void mouseEntered(MouseEvent e) {
       System.out.print("Mouse entered");
    }
public void mouseExited(MouseEvent e) {
        System.out.print("Mouse exited");
    }

private static void createAndShowGUI()
{
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("RWB");

    gay3 demo = new gay3();
    frame.setContentPane(demo.GUI());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setSize(650, 500);    
    frame.setVisible(true);

}

public static void main(String[] args)
{
    createAndShowGUI();
}

1 个答案:

答案 0 :(得分:0)

您可以在mouseEnteredmouseExited方法中执行此操作:

JPanel source = (JPanel)e.getSource();
//Edit the searchPanel here

如果searchPanel不是唯一使用此MouseListener的组件,您可能首先要检查源是否真的是JPanel的实例:

Object o = e.getSource();
if(o instanceof JPanel) {
    JPanel source = (JPanel)o;
    //Edit the searchPanel here
}

如果您知道来源为JPanel,则无需这样做。