【问题标题】:How to make JButton event modify JFrame (this)如何让 JButton 事件修改 JFrame (this)
【发布时间】:2011-06-11 19:25:33
【问题描述】:

我正在尝试使 JButton 单击事件修改按钮所在的 JFrame。问题是类本身是 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”或任何其他参数传递给动作监听器方法?

谢谢。

【问题讨论】:

    标签: java swing inner-classes


    【解决方案1】:

    当然可以:

    ClassX.this.setTitle("Title1");
    

    会做这项工作(Jon Skeet 同意我的观点)。

    【讨论】:

      【解决方案2】:
      ClassX.this.setTitle("Title2");
      

      【讨论】:

      • 无论如何我的更正确,因为 Riduidel 说“Title1”,当你想要“Title2”时
      【解决方案3】:

      为什么不实现 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);
                  }
                 } );
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        • 2014-12-22
        • 1970-01-01
        • 2022-01-05
        • 2023-03-08
        • 1970-01-01
        相关资源
        最近更新 更多