Java: How do I close a JFrame while opening another one? - java

My program starts with a picture with a textfield in a JFrame. I want when the user types start it closes the picture JFrame and opens another JFrame with the main program. I've tried
processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
on the Image frame but it closes all the windows.

The method JFrame.setVisible can be used to hide or display the JFrame based on the arguments, while JFrame.dispose will actually "destroy" the frame, by closing it and freeing up resources that it used. Here, you would call setVisible(false) on the picture frame if you intend to reopen it, or call dispose() on the picture frame if you will not be opening it again, so your program can free some memory. Then you would call setVisible(true) on the main frame to make it visible.

you also can use this code
for example
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

Maybe if you set the picture JFrame's default close operation to something besides EXIT_ON_CLOSE, perhaps DISPOSE_ON_CLOSE, you can prevent your application from closing before the second JFrame appears.

This post is a bit old but nevertheless.
If you initialize the form like that:
JFrame firstForm = new JFrame();
firstForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
firstForm.setSize(800, 600);
firstForm.setLocationRelativeTo(null);
firstForm.setVisible(true);
And for instance create or open another form by a button:
JFrame secondForm = new JFrame();
secondForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondForm.setSize(800, 600);
secondForm.setLocationRelativeTo(null);
secondForm.setVisible(true);
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
This will dispose and destroy the first window without exiting the program.
The key is to set setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE).
It also raises the events (I've tested it with the WindowClosing event).

Here is my solution to this problem:
public void actionPerformed(ActionEvent e) {
String userName = textField.getText();
String password = textField_1.getText();
if(userName.equals("mgm") && password.equals("12345")) {
secondFrame nF = new secondFrame();
nF.setVisible(false);
dispose();
}
else
{
JOptionPane.showMessageDialog(null, " Wrong password ");
}
}

you also can use this :
opens_frame frameOld= new opens_frame();
frameOld.setVisible(true);
Closing_Frame.setVisible(false);
Closing_Frame.dispose();

private void closeTheCurrentFrameAndOpenNew(java.awt.event.ActionEvent evt){
dispose();//To close the current window
YourClassName closeCurrentWindow = new YourClassName();
closeCurrentWindow.setVisible(true);//Open the new window
}

I was searching for the same thing and found that using "this" is the best and easiest option.
you can Use the following code:
this.dispose();

For netbeans use the reference of the current Object and setVisible(false);
for example
private void submitActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
this.setVisible(false);//Closing the Current frame
new login().setVisible(true);// Opening a new frame
}

First call it
new Window().nextjframe.setVisible(true);
thisjframe.setVisible(false);

if(username.equals("gaffar")&&password.equals("12345"))
{
label.setText("Be ready to continue");
//Start of 2nd jframe
NewJFrame1 n=new NewJFrame1();
n.setVisible(true);
//Stop code for ist jframe
NewJFrame m=new NewJFrame();
m.setVisible(false);
dispose();
}

This is what i came up for opening a new jframe while closing the other one:
JFrame CreateAccountGUI = new JFrame();
CreateAccountGUI.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
CreateAccountGUI.setSize(800, 600);
CreateAccountGUI.setLocationRelativeTo(null);
CreateAccountGUI.setVisible(true);
this.setVisible(false);

Related

Input Form in Swing GUI is run after main [duplicate]

I have a program with a GUI that needs to open a separate window and wait for the user to select and option, then continue. I figure I should be doing this with the wait() and notify() methods, but I'm still trying to figure out exactly how to use those. A complicating factor is that things seem to work differently when the second window is created in an actionPerformed() method, which it needs to be.
Here's how I think it should be done here, apparently it is not quite right...
This should create a window with a button, when the button is pressed, another window with a button should be created, and when that button is pressed, the program should print "End".
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WtfExample {
public static void main(String[] args) {
JFrame jf = new JFrame();
JButton butt = new JButton("Button");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
WtfExample we = new WtfExample();
we.display();
}
});
jf.getContentPane().add(butt);
jf.setSize(new Dimension(1000, 500));
jf.setVisible(true);
System.out.println("End");
}
public synchronized void display() {
JFrame jf = new JFrame();
JButton butt = new JButton("Button");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(WtfExample.this) {
WtfExample.this.notifyAll();
}
}
});
jf.getContentPane().add(butt);
jf.setSize(new Dimension(1000, 500));
jf.setVisible(true);
while(true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
edit- I wasn't clear enough in one thing- the second window that's opened is blank, like its components were never added to it. That's the case whether it's a frame or dialog, but that only happens if the window is created from the actionPerformed method.
No, you should just be using a JDialog.
You need a modal dialog window. Here's a tutorial on dialogs. It is easier to use JOptionPane for the simple cases.
A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the program.
As the other two answers suggest you need a modal JDialog. You do not need to deal with any Thread classes. The JDialog window will deal with the giving you control back once the user input is handled. There are a few ways you can set the dialog box modal. Here are two examples.
new JDialog(Dialog owner, boolean modal)
or
new JDialog(Dialog owner, String title, boolean modal)
You could also do something like this:
JDialog dialog = new JDialog(owner);
dialog.setModal(true);
I think this is a pretty good article about modality in JAVA.

Closing a JFrame Opened in Another JFrame

I am building an application which I need to open a JFrame in another JFrame while the first JFrame is disabled.
The problem is when I want to close the second JFrame I need to enable the first JFrame.
I have tried in several ways, but it is not working properly and I was not able to reach one goal in each of them. I need to reach both goals:
Disabling the first Frame when the second Frame is opened
Enabling it when the second Frame is closed.
Here is part of my code:
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
PaymentJFrame pjf = new PaymentJFrame();
//setEnableValue(false);
//enableFrame();
this.setEnabled(false);
pjf.setVisible(true);
if (!pjf.isActive()){
this.setEnabled(true);
}
}
This code dose not enable the First Frame at all.
I have tried to use it in another way by adding an enable when the second Frame is closed but it is not working:
//Class in first Frame
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
PaymentJFrame pjf = new PaymentJFrame();
//setEnableValue(false);
//enableFrame();
this.setEnabled(false);
pjf.setVisible(true);
}
//Class in second Frame
private void formWindowClosed(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
FinancialDocumentsJFrame.setEnableValue(true);
}
Dose any one know how can I reach these goals?
The first Frame is the main frame and the second frame is a class that I make the frame object from it in order to show and get more information from users.
I ma using netBeans IDE designer.
First of all, a Swing application should only have one JFrame, other windows can be JDialog or somethign else. As for your question, use this code as an example. It uses a listener to detect the closing event of the second window. The following code should be in the (first) JFrame (it looks like you have a button there)
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
JDialog paymentDialog = new JDialog();
MyFirstFrame.this.setEnabled(false);
paymentDialog.setVisible(true);
paymentDialog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
MyFirstFrame.this.setEnabled(true);
}
});
}
You can create your own dialog by extending JDialog as you did with the frames, and use the custom dialog in this code. Also instead of setting the JFrame enabled or disabled, you could consider using a modal JDialog that blocks actions to the JFrame while the dialog is active.
And further still, there is the setAlwaysOnTop(boolean) for Swing windows.
use this.dispose()method JFrame has dispose() method for JFrame Close
I decided to use jDialog as it was recommended by many people on the net.
I used a jDialog and copied all the objects I had used in the second jFrame.
It worked the way I wanted it to do.
My only problem is that why java hasn't prepared a different way to answer this need.
I'm using an action listener in the first jFrame to open the second Frame which I have used jDialog for it.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
ActivityJDialog ajdf = new ActivityJDialog(this,true);
ajdf.setVisible(true);
}
And I have copied everything I wanted to have into this jDialog.
public class ActivityJDialog extends java.awt.Dialog {
//Document Attributes
int documentStatus = -1;
int documentType = -1;
/**
* Creates new form AcrivityJDialog
* #param parent
* #param modal
*/
public ActivityJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
/*if(false) // Full screen mode
{
// Disables decorations for this frame.
//this.setUndecorated(true);
// Puts the frame to full screen.
this.setExtendedState(this.MAXIMIZED_BOTH);
}
else // Window mode
{*/
// Size of the frame.
this.setSize(1000, 700);
// Puts frame to center of the screen.
this.setLocationRelativeTo(null);
// So that frame cannot be resizable by the user.
this.setResizable(false);
//}
}
Thank you all for helping.

How do i find if a window is opened on swing

I have a problem with my application where the user will open more than one window at a time. And i have added dispose() method to call on closing the window. Now i should keep at-least one window open all the time so that the application does not hides without closed fully. If you don't understand read the following scenario:
I have window A and window B opened at the same time. Now i can close either window A or Window B but not both. In other words window B should be allowed to close only if window A is opened and vice versa. How do i do this in swing ??
A simple kind-of windowManger is not really tricky, all you need is
WindowListener which keeps tracks of the Windows it's listening to
a defined place to create the windows and register the the listener
make the windows do-nothing-on-close and make the listener responsible for the decision of whether to close or not (will do so for all except the last)
Some snippet:
// the listener (aka: WindowManager)
WindowListener l = new WindowAdapter() {
List<Window> windows = new ArrayList<Window>();
#Override
public void windowOpened(WindowEvent e) {
windows.add(e.getWindow());
}
#Override
public void windowClosing(WindowEvent e) {
if (windows.size() > 1) {
windows.remove(e.getWindow());
e.getWindow().dispose();
}
}
};
// create the first frame
JFrame frame = createFrame(l);
frame.setVisible(true);
// a method to create a new window, config and add the listener
int counter = 0;
private JFrame createFrame(final WindowListener l) {
Action action = new AbstractAction("open new frame: " + counter) {
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = createFrame(l);
frame.setVisible(true);
}
};
JFrame frame = new JFrame("someFrame " + counter++);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.add(new JButton(action));
frame.addWindowListener(l);
frame.pack();
frame.setLocation(counter * 20, counter * 10);
return frame;
}
Just a possible approach...
Create a class, call it WindowManager, that manages creation and disposal of windows.
It could for example retain the count of the windows currently open, and allow a dispose operation only if there are more than one windows "alive", otherwise show a confirm message with JOptionPane telling the user "Really close? That would terminate the application." or something like that.
The "tricky" part is that you have to do this kind of window-related operations throughout the WindowManager, otherwise everything would screw up.
Dunno if Swing has something like this built-in, I've never seen such a scenario.
simply check if the other window is open before closing with window.isVisible();

Problem with setVisible(boolean)

I have a JFrame with some component on it. I want that the frame disappears when i click on a special button for example exit button.
I wrote this code in exit button
this.setvisible(false);
but it only hides the component on it and frame doesn't disappear.
What can I do that when I click on exit button the frame disappears?
Here's an example of a button that hides the frame:
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
final JButton hideButton = new JButton("hide frame");
frame.add(hideButton);
hideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
frame.setVisible(true);
frame.pack();
In your call this.setVisible(false), this probably refers to the button and not the frame.
You need to call setVisible() on the Frame not the Button.
Also make sure you are calling dispose() on the frame to clean up all resources.
Additionally you should also use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
during creation of the frame, to make sure the windows is properly closed and disposed when the user clicks the "standard" close button in the upper right corner (on Windows).
This tutorial might also help you understand what's going on better:
http://download.oracle.com/javase/tutorial/uiswing/components/frame.html
call it on JFrame object.
example:
// when exit is pressed
fr.setVisible(false); // fr is a reference to object of type JFrame `

How to pause execution of a program until a button is clicked in Java Swing

I have a program with a GUI that needs to open a separate window and wait for the user to select and option, then continue. I figure I should be doing this with the wait() and notify() methods, but I'm still trying to figure out exactly how to use those. A complicating factor is that things seem to work differently when the second window is created in an actionPerformed() method, which it needs to be.
Here's how I think it should be done here, apparently it is not quite right...
This should create a window with a button, when the button is pressed, another window with a button should be created, and when that button is pressed, the program should print "End".
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WtfExample {
public static void main(String[] args) {
JFrame jf = new JFrame();
JButton butt = new JButton("Button");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
WtfExample we = new WtfExample();
we.display();
}
});
jf.getContentPane().add(butt);
jf.setSize(new Dimension(1000, 500));
jf.setVisible(true);
System.out.println("End");
}
public synchronized void display() {
JFrame jf = new JFrame();
JButton butt = new JButton("Button");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(WtfExample.this) {
WtfExample.this.notifyAll();
}
}
});
jf.getContentPane().add(butt);
jf.setSize(new Dimension(1000, 500));
jf.setVisible(true);
while(true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
edit- I wasn't clear enough in one thing- the second window that's opened is blank, like its components were never added to it. That's the case whether it's a frame or dialog, but that only happens if the window is created from the actionPerformed method.
No, you should just be using a JDialog.
You need a modal dialog window. Here's a tutorial on dialogs. It is easier to use JOptionPane for the simple cases.
A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the program.
As the other two answers suggest you need a modal JDialog. You do not need to deal with any Thread classes. The JDialog window will deal with the giving you control back once the user input is handled. There are a few ways you can set the dialog box modal. Here are two examples.
new JDialog(Dialog owner, boolean modal)
or
new JDialog(Dialog owner, String title, boolean modal)
You could also do something like this:
JDialog dialog = new JDialog(owner);
dialog.setModal(true);
I think this is a pretty good article about modality in JAVA.

Categories

Resources