2012-05-06 79 views
2

好吧,我有一個帶有GridLayout的JPanel。網格的每個單元格都包含另一個JPanel。swing - 獲取組件點擊JPanel

我想要做的就是在「下面」JPanel上有一個監聽器,然後告訴我哪個「覆蓋」JPanel被點擊 - 所以我可以對它和周圍的人做出反應,沒有使覆蓋JPanels意識到他們的立場(他們改變!!)

有沒有辦法做到這一點 - 類似於Determine clicked JPanel component in the MouseListener. Event handling但我找不到一種方法抓住組件頂部。

我大概可以抓住co-oridnates,並使用該信息解決 - 但我寧願不!

任何幫助/指針/提示,將不勝感激:d

回答

3

做同樣的事情,但源上使用getParent()。或者,您可以搜索最多的層次,如果它是更深層次的,甚至有一些輔助方法爲: javax.swing.SwingUtilities.getAncestorOfClassgetAncestorNamed

3

使用putClientProperty/getClientProperty,沒有什麼簡單的身邊......,你可以把ClientProperty無盡的號碼給一個對象

import java.awt.Color; 
import java.awt.GridLayout; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.border.LineBorder; 

public class MyGridLayout { 

    public MyGridLayout() { 
     JPanel bPanel = new JPanel(); 
     bPanel.setLayout(new GridLayout(10, 10, 2, 2)); 
     for (int row = 0; row < 10; row++) { 
      for (int col = 0; col < 10; col++) { 
       JPanel b = new JPanel(); 
       System.out.println("(" + row + ", " + col + ")"); 
       b.putClientProperty("column", row); 
       b.putClientProperty("row", col); 
       b.addMouseListener(new MouseAdapter() { 

        @Override 
        public void mouseClicked(MouseEvent e) { 
         JPanel btn = (JPanel) e.getSource(); 
         System.out.println("clicked column " + btn.getClientProperty("column") 
           + ", row " + btn.getClientProperty("row")); 
        } 
       }); 
       b.setBorder(new LineBorder(Color.blue, 1)); 
       bPanel.add(b); 
      } 
     } 
     JFrame frame = new JFrame("PutClientProperty Demo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(bPanel); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 

      public void run() { 
       MyGridLayout myGridLayout = new MyGridLayout(); 
      } 
     }); 
    } 
} 
+0

這是偉大的 - 謝謝你:) –