user3252306
user3252306

Reputation: 1

how to access one JFrame to another class JFrame

I have a problem.

I am creating two JFrames in different classes in the same package in eclipse. In the first JFrame class I have different JButtons for different uses.

In the first JButton, the name is "View user profile" after clicking this button some event is performed. the event occurs when the button is pressed that is another JFrame visible and this JFrame shows all user information which user is login. but this JFrame not show all the user details present in the database.

Because this showing an error for accessing another class (JFrame) variable like JButton, JLabel, etc.

Please help me. How can I access different class variables in another class.

Upvotes: 0

Views: 1261

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208964

"please help me how can i accesss different class varible in another class."

First See The Use of Multiple JFrames, Good/Bad Practice?

I would instead use a modal JDialog. See How to make Dialogs.

To access the components in the GUI class, you can just pass it as reference to the JDialog class, with getters for the components you want to access.

Here's an example of what I mean. You can see the JLabel from the GUI class is accessed through the getJLabel method from the GUI class.

public class GUI {
    private JLabel label;
    private MyDialog dialog;
    private JFrame frame;

    public GUI() {
        JButtton button = new JButton("Button");
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                dialog = new JDialog(frame, true, GUI.this);
            }
        });
    }

    @Override
    public JLabel getJLabel() {
        return label;
    }
}

public class MyDialog extends JDialog {
    private GUI gui;

    public MyDialog(final JFrame frame, boolean modal, GUI gui) {
        super(frame, modal);
        this.gui = gui; 

        JButton button = new JButton("Button");
        button.addActionListener(MyListener());
    }

    private MyListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JLabel label = gui.getJLabel();
            label.setText("Hello");
        }
    }
}

Upvotes: 1

Related Questions