2011-01-19 68 views
2

我試圖做一個JButton單擊事件修改JFrame的按鈕。問題是類本身就是JFrame(從它擴展),所以我不能從處理事件的內部類調用'this'。我找到了一個可行的解決方案,但我認爲這可能會導致其他問題,所以我試圖找到另一種方法。代碼如下:如何使JButton事件修改JFrame(this)

public class ClassX extends JFrame { 

... 

    this.setTitle("Title1"); //works fine 

    jButton1 = new JButton(); 
    jButton1.addActionListener(new java.awt.event.ActionListener() {  
      public void actionPerformed(java.awt.event.ActionEvent e) { 

       //this.setTitle("Title1"); //calling 'this' won't work inside an inner class 

       //Ugly Solution 
       JButton btn = (JButton) e.getSource();  
       JFrame frme = (JFrame) btn.getParent().getParent().getParent().getParent(); 
       frme.setTitle("Title2"); 
      } 
    }); 

... 

} 

我試圖避免多個getParent調用,但找不到另一個解決方案。有任何想法嗎?有沒有辦法將「this」或其他參數傳遞給動作監聽器方法?

謝謝。

回答

2

當然可以:

ClassX.this.setTitle("Title1"); 

將做的工作(和Jon Skeet同意我的看法)。

+0

非常感謝。 – Endo 2011-01-19 14:48:51

+0

這是在計時器上,嘿。 – Endo 2011-01-19 14:57:03

0

而不是有一個內部的ActionListener類爲什麼不實現ActionListener接口?

import javax.swing.*; 
    import java.awt.*; 
    import java.awt.event.*; 


    public class ClassX extends JFrame implements ActionListener 
    { 

    JButton jButton1; 

    public ClassX() 
    { 
     jButton1 = new JButton(); 
     jButton.addActionListener(this); 
     this.add(jButton); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
    this.setTitle("Button Clicked!") 
    } 

    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
      ClassX frame1 = new ClassX(); 
       frame1.setVisible(true); 
      } 
      }); 
    } 
}