Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods of "parent" component in 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  }
      }
    } );
  }
}
like image 610
Mel Avatar asked Dec 06 '22 07:12

Mel


1 Answers

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(); 
  }
}
like image 121
David Koelle Avatar answered Dec 11 '22 11:12

David Koelle