2013-04-16 53 views
0

我想要面板展開和顯示按鈕和東西,當鼠標懸停時,然後apon鼠標退出面板必須返回頂部的原始大小。 到目前爲止,我只能打印一個消息:如何使用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

爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

+0

'gay3 demo = new gay3();'很高興看到你寫(三)快樂的代碼。 –

+1

您是否嘗試過在'mouseEntered'和'mouseExited'方法中調用e.getSource()? –

回答

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,則不需要。

+0

,但mouse_events可能被JComponent放置在JPanel中 – mKorbel