Re: Communicating from event handler to container
"Michael Dunn" <m_odunn@yahoo.com> wrote in message
news:1172464061.584984.63560@j27g2000cwj.googlegroups.com...
On Feb 26, 1:32 pm, "eastside" <easts...@spamarrest.com> wrote:
I have a class, let's call it AC, which extends JPanel. Each instance of
AC
also contains a JTextField. The actionlistener for the text field is also
in
the class definition of AC. If a certain condition is detected by the
actionlistener, the object needs to tell the parent object that contains
AC
to inform all other instances of AC that they need to be updated. How is
this communication back to the parent object usually accomplished in
Java?
Thanks!
maybe(??) this might do what you want
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Testing
{
public void buildGUI()
{
JPanel p = new JPanel(new GridLayout(5,1));
for(int x = 0; x < 5; x++) p.add(new AC());
JFrame f = new JFrame();
f.getContentPane().add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
});
}
}
class AC extends JPanel
{
static java.util.List acPanels = new java.util.ArrayList();
JTextField tf = new JTextField(5);
public AC()
{
acPanels.add(this);
add(tf);
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
for(int x = 0, y = acPanels.size(); x < y; x++)
{
AC acPanel = (AC)acPanels.get(x);
acPanel.tf.setText(acPanel.tf.getText()+x);
}
}
});
}
}
First of all, thanks for going to all that effort to provide a solution!
However, there is a real need for the object to communicate back to the
parent object. My thought was something like this:
class Testing {
MainObj parentObj; // ref to parent object
public void buildGUI() {
JPanel p = new JPanel(new GridLayout(5,1));
for(int x = 0; x < 5; x++) p.add(new AC());
JFrame f = new JFrame();
f.getContentPane().add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
}
);
}
}
class AC extends JPanel {
static java.util.List acPanels = new java.util.ArrayList();
public AC(MainObj MO) { // constructor requires parent object reference
parentObj = MO; // save reference
acPanels.add(this);
add(tf);
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
....do some stuff
parentObj.callBack(...) // call the parent object to notify that update
must occur
}
});
}
}
My thought there already must be a mechanism in place to do this.