0

Hi everyone I'm new to java. I'm trying to redirect my "Next" JButton to another frame (DriversLicenseApplicant) in another class. The problem is when I click "Next" button it kept on opening the frame which my program is currently executing which is MainInfo. Can you help me with my code? thank you all. :)

    final JButton btnNext = new JButton("Next");
    btnNext.setBounds(824, 623, 89, 51);
    contentPane.add(btnNext);
        btnNext.addActionListener(
                new ActionListener(){


        public void actionPerformed(ActionEvent e) {
            if (btnNext.isSelected()) {
            DriversLicenseApplicant frame = new DriversLicenseApplicant();
            MainInfo objMain = new MainInfo();
                    frame.setVisible(true);
                        objMain.setVisible(false);



        }
        }
    });
Eva
  • 4,397
  • 5
  • 43
  • 65

1 Answers1

0

What is happening

The key lines are here

1  DriversLicenseApplicant frame = new DriversLicenseApplicant();
2  MainInfo objMain = new MainInfo();
3  frame.setVisible(true);
4  objMain.setVisible(false);

Before this block, you have one frame this. (In Java, you refer to the object you're in as this.) this is open.

At line 1, you create a new frame frame, bringing your total frames to two. frame is hidden.

At line 2, you create a third frame objMain. It is in the same class as this but it's a different instance. (Explanations of the difference between Class and Instance can be found on Stack and on Oracle's website). objMain is hidden, but this is open.

At line 3, you open frame. Now both this and frame are open, while objMain is hidden. this keeps focus because of Java's focus rules.

At line 4, you hide objMain. This has no effect because objMain was never open in the first place. You still have 3 frames, both this and frame are open, and this still has focus.

How to fix it

Replacing those lines with

DriversLicenseApplicant frame = new DriversLicenseApplicant();
frame.setVisible(true);
this.setVisible(false);

will open the new frame and hide to current one.

But I think there might be an underlying design issue. Each program should normally have only one frame. You might want to look into using a JDialog for the second window. You could also keep them both in the same frame and switch between them using a CardLayout. Also change your classes to extend JPanel, so you can put them in the content pane of your windows. It adds flexibility, and it's useful for whichever method you choose.

One more thing

I can't help mentioning the absolute positioning of the JButton. Please use layouts. They are your friends.

Community
  • 1
  • 1
Eva
  • 4,397
  • 5
  • 43
  • 65