Transfer data from one Jframe to another jframe using static class or this reference?

It is a question of “what” you want to achieve that will drive the “how”…

For example…

You could maintain a reference to the second frame within the first frame and when the button is clicked, tell the second frame that a change has occurred…

public class FirstFrame extends JFrame {
    // Reference to the second frame...
    // You will need to ensure that this is assigned correctly...
    private SecondFrame secondFrame;
    // The text field...
    private JTextField textField;

    /*...*/

    // The action handler for the button...
    public class ButtonActionHandler implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            secondFrame.setLabelText(textField.getText());
        }
    }
}

The problem with this is it exposes the SecondFrame to the first, allowing it to do nasty things to it, like remove all the components for example.

A better solution would be to provide a series of interfaces that would allow the two classes to talk with each other…

public interface TextWrangler {
    public void addActionListener(ActionListener listener);
    public void removeActionListener(ActionListener listener);
    public String getText();
}

public class FirstFrame extends JFrame implements TextWrangler {
    private JButton textButton;
    private JTextField textField;

    /*...*/

    public void addActionListener(ActionListener listener) {
        textButton.addActionListener(listener);
    }

    public void removeActionListener(ActionListener listener) {
        textButton.removeActionListener(listener);
    }

    public String getText() {
        return textField.getText();
    }
}

public class SecondFrame extends JFrame {
    private JLabel textLabel;
    private JTextField textField;
    private TextWrangler textWrangler;

    public SecondFrame(TextWrangler wrangler) {
        textWrangler = wrangler;
        wrangler.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                textLabel.setText(textWrangler.getText());
            }
        });
        /*...*/
    }
}

This basically restricts what the SecondFrame can actually gain access to. While it can be argued that the ActionListener in the SecondFrame could use the ActionEvent source to find out more information, by it’s nature, it would be an unreliable mechanism, as the interface makes no mention of how it should be implemented…

This is a basic example of the Observer Pattern

Leave a Comment