How to programmatically close a JFrame
If you want the GUI to behave as if you clicked the X
close button then you need to dispatch a window closing event to the Window
. The ExitAction
from Closing An Application allows you to add this functionality to a menu item or any component that uses Action
s easily.
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
How to close current JFrame?
The problem is the following action (and not only this):
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
new Windows().getCreateFrame().setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
});
here you create a new Windows
object and call getCreateFrame()
which creates a new JFrame
and then you call setDefaultCloseOperation()
on it.
So you work with different Windows
/ JFrame
instances.
Instead you should create your JFrame
in the constructor of Windows
and call setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
of this JFrame
in the constructor as well.
Afterwards you can use setVisible(false)
in your action - but for this JFrame
and not for a new created one.
BTW. getCancelButton()
should most probably not create a new button every time it is called.
Closing jFrame after clicking JButton
Assuming your button has an actionListener, after clicking the "rules button" put in:
JFrame1.dispose(); //Remove JFrame 1
JFrame2.setVisible(true) //Show other frame
And then reverese them for the opposite reaction
How to close a JFrame from a class outside the one it was declared in
You can use SwingUtilities.getWindowAncestor
function from javax.swing.SwingUtilities
to get the top frame of the panel.
Here is the working code:
@Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == 27) { // 27 is ascii code for esc button
JFrame frame = (JFrame)SwingUtilities.getWindowAncestor(this);
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
}
Put this code in the GamePanel
's KeyPressed
function.
Need to close a jframe while showing another one
Your basic idea is generally not recommended. You can have a look at The Use of Multiple JFrames: Good or Bad Practice? for the long winded discussion.
Generally it's recommended to use a CardLayout
for these type of operations, see How to use CardLayout for more details
What you want to try and do is decouple of the navigation decision making from the views themselves - there's no reason why the first and second view should ever care about each other OR be backing decisions about how the user should navigate.
How do you close a JFrame window without closing another one?
You duplicated the JFrame, created a JFrame field f
inside the JFrame.
Do not use static components like the button.
public class Frame1 extends JFrame implements ActionListener {
private final JButton login = new JButton("Login");
Frame1() {
setTitle("Login");
setSize(1000, 750);
setLocation(750, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
login.setBounds(250, 350, 150, 30);
add(login);
login.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == login) {
Frame2.frame2windown();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Frame1 login1 = new Frame1();
}
}
}
Use the swing/awt event queue (invokeLater
) as on this thread window events are handled and dispatched further.
And Frame2:
public class Frame2 extends JFrame implements ActionListener {
private JButton logout = new JButton("Logout");
private JLabel jb1 = new JLabel("Hello And Welcome");
Frame2() {
setTitle("Logout");
setSize(1000, 750);
setLocation(750, 250);
setLayout(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jb1.setBounds(250, 150, 350, 30);
logout.setBounds(250, 350, 150, 30);
add(logout);
add(jb1);
logout.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent a) {
if (a.getSource() == logout) {
setVisible(false); // <--- ALL
}
}
public static void frame2windown() {
Frame2 f2 = new Frame2();
}
}
JFrame.setVisible
does it all. Especially setVisible(true)
should maybe even done after the constructor is called, so it always is last.
Another remark, dive into layout managers fast. Absolute layouts (null) are a PITA.
How to make a JFrame close itself after 10 seconds?
You could use javax.swing.Timer like this:
new Timer(10_000, (e) -> { frame.setVisible(false); frame.dispose(); }).start();
The advantage of using the javax.swing.Timer option is that it doesn't violate Swing threading rules.
As the Javadocs say:
The javax.swing.Timer has two features that can make it a little
easier to use with GUIs. First, its event handling metaphor is
familiar to GUI programmers and can make dealing with the
event-dispatching thread a bit simpler. Second, its automatic thread
sharing means that you don't have to take special steps to avoid
spawning too many threads. Instead, your timer uses the same thread
used to make cursors blink, tool tips appear, and so on.
Related Topics
What Is the 'Instanceof' Operator Used For in Java
What's the Difference Between ".Equals" and "=="
How to Convert Byte Array to String and Vice Versa
Javac Is Not Recognized as an Internal or External Command, Operable Program or Batch File
Getresourceasstream Returns Null
String Is Immutable. What Exactly Is the Meaning
Java: Date from Unix Timestamp
How to Do a Deep Copy of a 2D Array in Java
Fastest Way to Determine If an Integer'S Square Root Is an Integer
Java 8 List≪V≫ into Map≪K, V≫
Java Serializable Object to Byte Array
How to Use Wait and Notify in Java Without Illegalmonitorstateexception
Org.Xml.Sax.Saxparseexception: Content Is Not Allowed in Prolog
Difference Between Statement and Preparedstatement
When Does Static Class Initialization Happen