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 }
}
} );
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With