I have 2 JFrame
s f1
and f2
both having buttons b1
and b2
respectively.
The buttons b1
and b2
switch frames, i.e. if b1
is clicked it opens f2
and if b2
is clicked it opens f1
.
I want my program to close previous JFrame
when attempting to open a new JFrame, i.e. if b1 is clicked it should close/hide f1
and open f2
and vice versa.
I have tried setVisible(false)
but it doesn't seem to work.
I'd appreciate any help or suggestions.
Here is my code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class m extends JFrame implements ActionListener
{
static JFrame f1,f2;
static JButton b1,b2;
public m()
{
f1();
}
public void f1()
{
JFrame f1=new JFrame("frame 1");
JButton b1=new JButton("frame 2");
JLabel l1=new JLabel("FRAME 1");
f1.setSize(600,600);
b1.setBounds(300,300,100,100);
l1.setBounds(300,150,100,100);
b1.addActionListener(this);
f1.add(b1);
f1.add(l1);
f1.setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void f2()
{
JFrame f2=new JFrame("frame 2");
JButton b2=new JButton("frame 1");
JLabel l2=new JLabel("FRAME 2");
f2.setSize(600,600);
b2.setBounds(300,300,100,100);
l2.setBounds(300,150,100,100);
b2.addActionListener(this);
f2.add(b2);
f2.add(l2);
f2.setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String args[])
{
new m();
}
public void actionPerformed(ActionEvent e)
{
String bt=String.valueOf(e.getActionCommand());
if(bt=="frame 2")
{
f1.setVisible(false);
f2();
}
else if(bt=="frame 1")
{
f2.setVisible(false);
f1();
}
}
}