Hello everyone
I am frantically trying to learn Java and have now found myself wondering if I am passing variables back from a temporary child dialog back to the caller correctly. If somebody would be so good, I would appreciate it if you could look at my example classes and tell me if I am doing it correctly. If not, why not!
For this example, in C++ I would probably pass in a pointer and have the caller updated that way but of course Java doesn't support primitive type pointers.
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JTextField; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Example extends JFrame { //Instantiate the container object Container c = new Container(); public static void main(String[] args) { Example w = new Example(); w.initGUI(); } private void initGUI(){ this.setDefaultCloseOperation(EXIT_ON_CLOSE); // SETUP BASIC GUI COMPONENTS JPanel p = new JPanel(); JButton b = new JButton("CLICK ME"); final JTextField tf = new JTextField(); // SETUP ACTION LISTENER b.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ DialogHarvester dialog = new DialogHarvester(c); dialog.setModal(true); dialog.setVisible(true); tf.setText(c.userParameter); return; } }); // SIZE THEM AND ADD TO THE FORM tf.setPreferredSize(new Dimension(100,25)); tf.setEditable(false); p.add(b); p.add(tf); this.add(p); this.setSize(200, 100); this.setVisible(true); return; } }
AND
import java.awt.Dimension; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class DialogHarvester extends JDialog{ Container c; JTextField t; DialogHarvester(Container con){ setDefaultCloseOperation(DISPOSE_ON_CLOSE); c = con; this.initGUI(); } private void initGUI(){ // SETUP BASIC GUI COMPONENTS JPanel p = new JPanel(); JButton b = new JButton("OK"); t = new JTextField(); // SETUP ACTION LISTENER b.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ exitForm(); } }); // SIZE THEM AND ADD TO THE FORM t.setPreferredSize(new Dimension(100,25)); p.add(t); p.add(b); this.add(p); this.setSize(100,100); } private void exitForm(){ c.userParameter = t.getText(); this.dispose(); } }
AND
public class Container { Container(){} public String userParameter; }
Many thanks for reading and I thank people in advance for helping me yet again.
Regards
Nikki