简体   繁体   中英

How do I change a panel with mouselistener?

I'm wanting the panel to expand and display buttons and stuff when the mouse is hovered over, then apon mouse exiting the panel must return top original size. So far I can only print a message:

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();
}

You could do this inside the mouseEntered and mouseExited methods:

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

If searchPanel isn't the only component that uses this MouseListener , you may first have to check if the source really is an instance of JPanel :

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

This isn't necessary if you know the source is a JPanel .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM