'How do you call a class's function from it's child button's callback (i.e. click method)?
I have a panel, in which there are a few buttons. Just for simplicity I'll just use one button in this example. I need each of the button's callback (i.e. click event) to be able to call a common function (in this case here in my code it's testFunction).
No matter what I try I keep getting errors. Here is my code:
private class ConnectionPanel extends JPanel {
JButton m_b3 = new JButton("5%");
public void testFunction()
{
System.out.println("inside testFunction");
}
m_b3.addActionListener(new java.awt.event.ActionListener()
{
@Override public void actionPerformed(java.awt.event.ActionEvent evt)
{
getParent().testFunction(); // this give me "Cannot find symbol"
getRoot.testFunction(); // same, gives me "Cannot find symbol"
parent.testFunction(); // gives me "Parent is not public in component"
Solution 1:[1]
The answer is to pass the reference to the parent class, so the callback would look like this:
// Take fast 5%
m_b3.addActionListener(new java.awt.event.ActionListener()
{
@Override public void actionPerformed(java.awt.event.ActionEvent evt)
{
m_connectionPanel.testFunction();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Brent Heigold |