本文介绍了“父”的调用方法组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况我认为最好在示例程序代码中显示。我有一个Java类,扩展 JPanel 。在这个类中有两个对象,两个是 JPanels 。在 JPanel 对象之一是 JTable 对象。我向这个 JTable 添加了一个侦听器,它会检测到双击。当它检测到双击时,我想在顶级类中激活一个方法。如何在Java中引用此方法?

I have the following situation I think would be best to show in sample program code. I have a Java class that extends JPanel. In this class are two objects which are two more JPanels. In one of the JPanel objects is a JTable object. I added a listener to this JTable that detects a double click. When it detects a double click, I want to fire a method in the top class. How do I reference this method in Java?

public class TopPanel extends JPanel {

  JPanel OnePanel;
  JPanel TwoPanel;

  public void MethodToFire;

}

public class OnePanel extends JPanel {

  JTable TheTable;

}

public class TheTable extends JTable {

  public TheTable {
    this.addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e){
          if (e.getClickCount() == 2){ SYNTAX CALLING THE METHOD IN TopPanel  }
      }
    } );
  }
}


推荐答案

解决这个问题的方法是使用组合而不是继承。您可以将JPanel传递到JTable的子类中。

One way to solve this is to use composition instead of inheritance. You could pass the JPanel into your subclass of the JTable.


public class TopPanel extends JPanel
{
  private TheTable table;

  public TopPanel()
  {
    table = new TheTable(this);
  }

  public void methodToFire() { }
}

public class TheTable extends JTable
{
  private TopPanel panel;

  public TheTable(TopPanel panel)
  {
    this.panel = panel;

    this.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        doThing();
      }
    } );
  }

  private void doThing()
  {
    this.panel.methodToFire();
  }
}

这篇关于“父”的调用方法组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 04:40