2012-05-09 27 views
5

我有一個JPanel,我想響應鼠標單擊,然後打開JDialog。構造函數JDialog需要JFrame的實例,而不是JPanel - 我該如何解決這個問題?從JPanel實例化JDialog

+2

你有沒有考慮過使用JOptionPane? – ChadNC

回答

1

有不需要參數的構造:

JDialog dialog = new JDialog(); 

如果你想要的是使對話模式,也許你可以得到你主JFrame的靜態參考,喜歡的東西:

JDialog dialog = new JDialog(MyMainJFrame.getInstance()); 
3

使用參數自由構造函數將使對話框無所有者。我認爲最好的做法是讓擁有Panel的Frame成爲對話框的所有者。因此,我的意思是你應該使用你的JPanel中的getParent()來找到它的所有者,然後發送這個對象作爲你的JFrame的所有者。

爲粗碼是

java.awt.Container c = myPanel.getParent(); 
while (!(c instanceof javax.swing.JFrame) && (c!=null)) { 
     c = c.getParent(); 
} 
if (c!=null) { 
    JFrame owner=(javax.swing.JFrame) c; 
    JDialog myDialog=new JDialog(owner); 
} 

我沒有測試此代碼,但它是好到足夠讓你瞭解的想法。

2

如果您決定使用JOptionPane,可以使用mouseAdapter內部類將MouseListener添加到JPanel以處理mouseClicked事件。您將不得不宣佈面板最後才能從內部類訪問面板。

final JPanel testPanel = new JPanel(); 

testPanel.addMouseListener(new MouseAdapter(){ 
    public void mouseClicked(MouseEvent e) 
    {   
     JOptionPane.showMessageDialog(testPanel,"Title","InformationMessage",JOptionPane.INFORMATION_MESSAGE); 

    }});//end of mouseClicked method 
7

你確實應該嘗試到的JDialog附加到父對話框或框架,特別是如果你想了模式(通過傳遞父窗口,對話框將被連接到您的窗口,並把家長會帶來兒童對話)。否則,用戶體驗才能真正出了問題:丟失的對話框,阻斷的窗口,沒有看到模態對話框,等等

要找到您的JPanel的父窗口,所有你需要的是這樣的代碼:

JPanel panel = new JPanel(); 
Window parentWindow = SwingUtilities.windowForComponent(panel); 
// or pass 'this' if you are inside the panel 
Frame parentFrame = null; 
if (parentWindow instanceof Frame) { 
    parentFrame = (Frame)parentWindow; 
} 
JDialog dialog = new JDialog(parentFrame); 
... 

如果您不知道您是否在框架或對話框中,請爲這兩個類進行「instanceof」測試。