show a new jframe on another jframe close event - java

I have 2 jframes(assume A and B) and when I close a one jframe(A) I need to show other jframe(B) I have a clue that I need to override defaultClosingOperation but I have no idea how to do that.any help would be appreciated .. thank you all.

You can add a Windows Listener to your frame.
WindowListener myExitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
int confirmation = JOptionPane.showOptionDialog(jframe1, "Open frame2", "Open frame2", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirmation == 0) {
//open jframe2 here
}
}
};
jframe1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
jframe1.addWindowListener(myExitListener);

Related

Java: Dispose Gui Form

I'm making a GUI using IntelliJ, and I have selected the option New -> Gui Form. I have made it as a login screen, but I cannot dispose the window at successful login. I have tried to extend the class with extends JFrame and then call dispose(), but it does not seem to be working. What do I do wrong?
In advance, thank you.
UPDATE with code:
public LoginFrame() {
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
char[] pass = password.getPassword();
StringBuilder passwordBuilder = new StringBuilder();
for (char p : pass)
{
passwordBuilder.append(p);
}
String password = passwordBuilder.toString();
//Login.
if(DatabaseHandler.login(username.getText(), password))
{
dispose(); //THIS WINDOW.
}
else
{
JOptionPane.showMessageDialog( null, "Wrong username or password!", "Login failed!", JOptionPane.ERROR_MESSAGE);
}
}
});
}
You can try following:
if(DatabaseHandler.login(username.getText(), password))
{
Component button = (Component) e.getSource();
SwingUtilities.getWindowAncestor(button).dispose();
}
When it does not help, please provide a MCVE so we can understand what's wrong in your code.
if you have your class extending JFrame you just use your class name to dispose the JFrame as per the below
windowClassName.super.dispose();

Swing - Closing a Frame (Window) or not depending on popup choice

I'm trying that when a user tries to close a window in the normal way (clicking on the X) a popup shows up saying "Are you sure you want to close this window?" and then if he chooses "No", I want the window not to close, which is closing wether he chooses Yes or No.
My current code for this listener is:
frmContactarEspecialista.addWindowListener(new FrameWindowListener());
private class FrameWindowListener extends WindowAdapter {
#Override
public void windowClosing(WindowEvent arg0) {
int salir = JOptionPane.showOptionDialog(frmContactarEspecialista, "Si cierra esta ventana se descartará el email, ¿continuar?", "Salir",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if (salir != 0){
}
}
}
After marking my post as duplicate, I alredy tried that with:
private class FrameWindowListener extends WindowAdapter {
#Override
public void windowClosing(WindowEvent arg0) {
int salir = JOptionPane.showConfirmDialog(frmContactarEspecialista, "Si cierra esta ventana se descartará el email, ¿continuar?", "Salir",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (salir == JOptionPane.NO_OPTION) {
System.out.println("do nothing");
}
}
}
And it prints "do nothing" but still closes the window.
what should I change or put into the if so it doesn't close the window?
Thanks
I found the answer!
First you have to add something to your frame.
nameofyourframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
So, when you press X, the window won't close at all.
Now let's go to your listener.
if(salir != 0){
nameofyourframe.dispose();
}
So, if the answer is yes, it will close your program and window, if no nothing will happen!

How to close a JDialog through JButtons

I am making a method that gives the user three choices and returns the one they click, right now the method kinda works I click one of the options and if I click the close button it returns the last clicked. I want to to make it so that the dialog closes when you click one of the options
public E drawThreeForDecision()
{
ArrayList<E> c = new ArrayList<E>();
Component[] options = new Component[3];
for (int iii = 0; iii < 3; iii++)
{
final int loop = iii;
c.add((E) drawCard());
JButton button = new JButton(new ImageIcon(((GameEntity) c.get(iii)).getEntityImage()));
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
}
});
options[iii] = button;
}
JOptionPane pane = new JOptionPane("Please select a card", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
JDialog dialog = pane.createDialog(null, "DECISION TIME!");
dialog.setVisible(true);;
if (pane.getValue() instanceof Integer)
return (E) pane.getValue();
return c.get(0);
}
If anyone can help me with this or suggest a better solution it would be greatly appreciated!
Try these:
dialog.setModal(true);
dialog.setVisible(true);
use dialog.dispose(); inside the actionPerformed() method.

Some problems to inconify a JFrame window when the user click on the X button in this specific case, some ideas?

I have the following problem: I am working on a Java Swing application that show me a JFrame. What I have to do is that when the user click on the X button the window have to be iconified and not close (it is a requirement requested by the client)
My architecture is pretty complicated and it work in this way:
I have a class named GUI that is something like this:
public class GUI extends SingleFrameApplication implements PropertyChangeListener {
private MainFrame mainFrame = null;
#Override
public void propertyChange(PropertyChangeEvent arg0) {
showMainFrame();
}
private void showMainFrame() {
mainFrame = new MainFrame(settings, tasksSettings, logAppender);
// I add a PropertyChangeListener to the created MainFrame object:
mainFrame.addPropertyChangeListener(this);
//mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
logger.info("Minimize the MainFrameWindows instead close it");
((MainFrame)e.getSource()).setState(MainFrame.ICONIFIED);
logger.info("EVENTO ICONIZZAZIONE: " + e.getSource().toString());
}
});
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.out.println("GUI SingleFrameApplication --> windowClosing");
mainFrame.OnWindowClose();
shutdown();
// mainFrame.setVisible(false);
/*int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}*/
}
};
mainFrame.addWindowListener(exitListener);
mainFrame.setVisible(true);
}
#Override
protected void shutdown() {
System.out.println("Entered into GUI ---> shutdown()");
logger.debug("Termino l'applicazione.");
ulogger.info(com.techub.crystalice.utils.Constants.APP_TITLE + "|Arresto " + com.techub.crystalice.utils.Constants.APP_TITLE);
// FileUtils.saveGeneralLogFile(logAppender.getLogInFile());
logAppender.saveGeneralLogFile();
EventBusService.unsubscribe(this);
if (mainFrame != null)
mainFrame.setVisible(false);
}
}
So in the previous code I have declared the showMainFrame() method and in this method I add a window listener that have to iconize my MainFrame JFrame, in this way
mainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
logger.info("Minimize the MainFrameWindows instead close it");
((MainFrame)e.getSource()).setState(MainFrame.ICONIFIED);
logger.info("EVENTO ICONIZZAZIONE: " + e.getSource().toString());
}
});
Then I have my MainFrame windows that extends a classic JFrame, something like this:
public class MainFrame extends JFrame {
private final ConfigHelper settings;
private final TasksSettings tasksSettings;
public MainFrame(ConfigHelper settings, TasksSettings tasksSettings, LogAppender logAppender) {
super();
this.settings = settings;
this.tasksSettings = tasksSettings;
.......................................................
.......................................................
.......................................................
DO SOME STUFF
.......................................................
.......................................................
.......................................................
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
The problem is that when I click on the X button of my MainFrane window it will be close and not iconified.
Can you help me to solve this situation and in such a way that the MainFrame window is iconified and not closed?
I think that the problem is that at the end of execution it execute the shutDown() method that execute this operation:
if (mainFrame != null)
mainFrame.setVisible(false);
so the windows is not iconified but closed\made it invisible
Some idea?
Tnx
Andrea
If I have understood correctly, you need to show an icon for the app in system tray when you hit the X button, is it true?
In this case, you have enough with the default behavior for close event (the default is hide on close, as stated in documentation).
http://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
In order to manage a system tray icon, you have some hints here:
http://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html
In the system tray, you would have the necessary code to hide or show the main window (I don't know, but maybe you don't even need a window listener at all in your JFrame)

Set default close operation on PApplet (Processing)

There´s any methods to set the default close operation on PApplet?
I tried to embed the PApplet in a JFrame, but it wont init correctly, i need to set the window to dont close at exit, in JFrame i can just set it to DO_NOTHING_ON_CLOSE, dont know how to do in a PApplet. I'm implementing a confirm exit dialog, and i just want to close only when i confirm.
PApplet already have a frame, but it's not a JFrame, so i can´t just call setDefaultCloseOpreation.
I´ve added an window listener to get the window closing action:
//frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
int confirm = JOptionPane.showOptionDialog(frame,
"Want to save all unsaved data?",
"Exit confirmation", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
switch(confirm) {
case JOptionPane.YES_OPTION:
System.out.println("Data saved, closing...");
break;
case JOptionPane.NO_OPTION:
System.out.println("Data lost, closing...");
break;
case JOptionPane.CANCEL_OPTION:
System.out.println("Close canceled.");
break;
}
}
});
In the cancel option i want to close this dialog and keep open the application, this way without "do nothing on close" every option i choose close the application.
The API documentation of PApplet at http://processing.org/reference/javadoc/core/processing/core/PApplet.html shows how a PApplet may be embedded into a Frame, and explicitly states that "...there's nothing to prevent you from embedding a PApplet into a JFrame". When you use a pattern according to the ExampleFrame shown there (but extending JFrame), you should be able to set the desired default close operation and attach your listener.
A while back I ran into this same problem. I'm not sure that this code solved it, but I think it helped? There are some window listeners already there, this code removes them. I also dimly recall having to run it after a few frames because they hadn't been initialized or something immediately after the program starts or something. You can give it a shot, anyway:
WindowListener[] wls = frame.getWindowListeners();
println("Removing " + wls.length + " window listeners.");
for (int i = 0; i < wls.length; i++) {
frame.removeWindowListener(wls[i]);
}
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
checkExit();
}
}
);
Solved this problem embedding the PApplet on JFrame, but as the example show in the processing documentation is very simple, it don´t work as expected.
Here´s the code working:
public class Application extends PApplet {
public void setup() {
size(600, 480, JAVA2D);
}
public void draw() {
background(255);
}
public void closeApplication() {
exit();
}
public static void main(String _args[]) {
final JFrame frame = new JFrame("Embbed Applet");
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
JPanel panel = new JPanel();
final Application applet = new Application();
applet.init();
panel.add(applet);
frame.add(panel);
frame.setSize(600, 510);
frame.setResizable(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
int confirm = JOptionPane.showOptionDialog(frame,
"Want to save all unsaved data?",
"Exit confirmation", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
switch(confirm) {
case JOptionPane.YES_OPTION:
// Save data
applet.closeApplication();
System.exit(0);
break;
case JOptionPane.NO_OPTION:
applet.closeApplication();
System.exit(0);
break;
case JOptionPane.CANCEL_OPTION:
// Do nothing
break;
}
}
});
frame.setVisible(true);
}

Categories

Resources