Im developing a project in which I have "Class1", "Class2", and "Class3". Class2 and Class3 both create JFrame's, each containing various JButton's, JLabel's, and other swing components. How do i make so in Class1 I can reffrence the JButton from Class2 and use an action listener to set the Class2's visibilty to false and Class3's visibilty to true.
I Tried This: Setting Class2 to visbile in my main method was no issue, but once i started to implement Class3 things didint work.
Summary: Having Issues initiating a jbutton from an other class and using an action listener that refrences that jbutton.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Class1 extends JFrame implements ActionListener
{
public static void main(String[] args) {
Class2 frameFromclass2 = new Class2();
frameFromclass2.setVisible(true);
}
Class2 buttonMovetoclass3 = new Class2();
public void actionPerformed(ActionEvent e) {
if (buttonMovetoclass3 == e.getSource()) {
Class2 frameFromclass2 = new Class2();
frameFromclass2.setVisible(false);
Class3 frameFromclass3 = new Class3();
frameFromclass3.setVisible(true);
}
}
}
Part of your problem is caused by a lack of understanding in terms of variable scope. The other part of your problem is just in approaching this the wrong way.
We aren't able to see what your other classes have in their constructors, so I can't say whether or not there's also a problem happening there. I can, however, offer better alternatives.
Generally you want to keep 1
JFrame, even if you have popup windows or multiple "pages" that can be used. Consider using multipleJPanels, one per layout. Alternatively you can use aJTabbedPane, and have different information on each tab. For login purposes, a common option is theJOptionPaneor aJDialog. If you insist on using multipleJFramesand you want to move components between them, variables within your class (not a method) should be used to store information, then use public methods to access those variables from the other classes. Once a window is done being used, however, you should destroy it instead of hide it. Here's a great resource on various ways to do that.