Set default close operation on PApplet (Processing) - java

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);
}

Related

Close window after checking

I'm having a slight issue, and I can't figure it out.
I want for my code to check if the email and password matches and then close the window. This the action:
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean status = Email_Verification.email_validation(email_text.getText().toString().trim());
if (status) {
lbl_inco_email.setText(null);
} else {
lbl_inco_email.setText("Please enter a valid email");
}
boolean stat = Password_Verification.password_validation(password_Field.getPassword().toString());
if (stat) {
lbl_inco_pwd.setText(null);
} else {
lbl_inco_pwd.setText("Please enter a valid Password");
}
/* Exit and redirect to the main application if the email/pwd matches the database */
/** MAIN__WINDOW __EXIT__ONCLICK__ = new MAIN__WINDOW();
__EXIT__ONCLICK__.setVisible(true); */
}
});
I am going to assume you have an issue with opening a new frame and disposing of the login frame, because if you have an issue with user validation there isn't enough information for any of us to actually help.
Also, please read this concerning the use of multiple JFrames. The Use of Multiple JFrames: Good or Bad Practice?
Now for the code section...
Once user validation is done, you need to create an instance of your main window and make it visible. After that you can close the first JFrame.
Your actionPerformed would look something like this:
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Let's assume you have a boolean variable that handles user validation
//for simplicity...
if(userVerified) {
// In this example let's call the main application window MainFrame
MainFrame mF = new MainFrame();
// Set it to visible
mF.setVisible(true);
mF.setLocationRelativeTo(null);
// Now you can close the first JFrame
this.dispose();
}
}
});

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)

Java - Message when closing JFrame Window

I have a Java Program containing a class Application inheriting from JFrame.
I want to display a message which asks the user if he wants to exit the program upon clicking the X button at the top right of the window.
This is my code so far:
I got this code from a tutorial I found online. I coded the WindowClosing event handler myself. However, I have trouble registering the window listener (addWindowListener). It is telling me that WindowAdapter is abstract and cannot be instantiated.
How can I solve this problem please?
Basically, you got it almost correct. There are a few things not put together correctly and a typo.
First remove your WindowClosing method (it's window, not Window)
Then replace your addWindowListener(new WindowAdapter()); with the code below
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the program?", "Exit Program Message Box",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
dispose();
}
}
});
i got this in two minutes coding....
First is set the j frame default closing event in Exit_on_close. Second create a class called "Window Closing Event Handler" and then call it in the i nit stage.
private void WindowClosingEventHandler(){ addWindowListener(new WindowAdapter() { #Override public void windowClosing(WindowEvent e) { int confirmed = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit this application?", "Exit Program Message Box",JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
try{
String login=txtuserid.getText();
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/repair", "root", "");
Statement st = conn.createStatement();
String update = "UPDATE user set User_Status=0 where UserID='"+ login +"'";
st.executeUpdate(update);
dispose();
Login2 dialog = new Login2(new javax.swing.JFrame(), true);
dialog.setVisible(true);
}catch(SQLException | HeadlessException q){
JOptionPane.showMessageDialog(null, q);
}
System.exit(0);
}
else{
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
});
}
Ok trying again.
You cannot create a new WindowAdapter because WindowAdapter is abstract. Abstract classes cannot be instantiated. You would need to create a subclass of WindowAdapter and implement its abstract methods as public.
http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html

JoptionPane ShowConfirmDialog

I have a Java program. When I run the program, it will give me a GUI which as I attached.
When I want to close it, it will prompt out a confirm dialog. If I press the Yes button, it will quit the program using System.exit().
public static void main(String args[])
{
ButtonTest app = new ButtonTest( );
app.addWindowListener(
new WindowAdapter( )
{
public void windowClosing (WindowEvent e)
{
String message = " Really Quit ? ";
String title = "Quit";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
);
}
If I don't want to quit the program, what can I do? System.continued() ?
You Don't need the else in this case
Try setting this,
app.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)
[Edited]
So, your code will become something like this,
public static void main(String args[]) {
ButtonTest app = new ButtonTest();
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int reply = JOptionPane.showConfirmDialog(null,
"Really Quit ?", "Quit", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
System.exit(0);
}
});
app.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
app.setSize(640, 480);
app.setVisible(true);
}
[Explanation]
You might be thinking that why it is like that. The behaviour of windows close button for JFrame, unlike Frame,is to hide the window. Therefore, it will hide/close the window anyway. But when you specify that it must also exit the program, when the user click yes. Then, besides closing the window, it also exits the program. And when user clicks no, it does nothing but closes the window anyway. Hence, you must tell it explicitly that DO_NOTHING_ON_CLOSE.
[Docs]
Unlike a Frame, a JFrame has some notion of how to respond when the
user attempts to close the window. The default behavior is to simply
hide the JFrame when the user closes the window. To change the default
behavior, you invoke the method setDefaultCloseOperation(int). To make
the JFrame behave the same as a Frame instance, use
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE).
Ref: JFrame docs
If you will ask me, I will go with, on YES SELECTION instead of abruptly closing my Application with System.exit(0), I will choose the gracious way of closing my Application, by using frameObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) and on NO SELECTION , I will go for frameObject.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE). Here is one sample program for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ApplicationCloseExample
{
private void displayGUI()
{
final JFrame frame = new JFrame("Application Close Example");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
int result = JOptionPane.showConfirmDialog(
frame, "Do you want to Exit ?"
, "Exit Confirmation : ", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else if (result == JOptionPane.NO_OPTION)
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
});
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationCloseExample().displayGUI();
}
});
}
}
If you want the program to continue when you press NO, place the rest of your code in else block or call the function where you have placed the rest of your code.
Removing else block is also an option if you don't want to place any action on the NO button because the JOptionPane.showConfirmDialog() will close anyways. You can continue with rest of your code after the if statement.
FYI- There is no System.continue(). The program pretty much does that on it's own.
You can add an else block. if you want to run the main method again (which I assume you do) it should look like this. You should have some method which you run if the user chooses no, whether it is the main method main(null) or another method.
public static void main(String args[])
{
ButtonTest app = new ButtonTest( );
app.addWindowListener(
new WindowAdapter( )
{
public void windowClosing (WindowEvent e)
{
String message = " Really Quit ? ";
String title = "Quit";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
else
{
//whatever you plan on running instead here, instead of quitting,
//main(null) to run the main method, or put another method if you want
}
}
}
);
}

Java - how do I prevent WindowClosing from actually closing the window

I seem to have the reverse problem to most people. I have the following pretty standard code to see if the user wants to do some saves before closing the window:
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
boolean close = true;
// check some files, asking if the user wants to save
// YES and NO handle OK, but if the user hits Cancel on any file,
// I want to abort the close process
// So if any of them hit Cancel, I set "close" to false
if (close) {
frame.dispose();
System.exit(0);
}
}
});
No matter what I try, the window always closes when I come out of windowClosing. Changing WindowAdapter to WindowListener doesn't make any difference. What is weird is that the documentation explicitly says "If the program does not explicitly hide or dispose the window while processing this event, the window close operation will be cancelled," but it doesn't work that way for me. Is there some other way of handling the x on the frame? TIA
I've just tried this minimal test case:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
//frame.dispose();
}
});
frame.setVisible(true);
}
}
If I keep the dispose call commented, and hit the close button, the window doesn't exit. Uncomment that and hit the close button, window closes.
I'd have to guess that something is wrong in your logic to set your "close" variable. Try double checking that.
This is the key, methinks: frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); Makes the difference in the test case I cooked up.
not sure where is your problem,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private JFrame frame = new JFrame();
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
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);
}
}
};
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
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);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ClosingFrame cf = new ClosingFrame();
}
});
}
}
For the handling of this thing do:
if the user selects yes then use setDefaultCloseOperation(DISPOSE_ON_CLOSE); within the curly braces of that if else
if a cancel is selected then use setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
Consider example:
int safe = JOptionPane.showConfirmDialog(null, "titleDetails!", "title!!", JOptionPane.YES_NO_CANCEL_OPTION);
if(safe == JOptionPane.YES_OPTION){
setDefaultCloseOperation(DISPOSE_ON_CLOSE);//yes
} else if (safe == JOptionPane.CANCEL_OPTION) {
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//cancel
} else {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);//no
}
To solve the same problem I tried the very first answer of this article.
As separate application it works, but not in my case.
Maybe difference is in JFrame(in answer) and FrameView (my case).
public class MyApp extends SingleFrameApplication { // application class of my project
...
protected static MyView mainForm; // main form of application
...
}
public class MyView extends FrameView {
...
//Adding this listener solves the problem.
MyApp.getInstance().addExitListener(new ExitListener() {
#Override
public boolean canExit(EventObject event) {
boolean res = false;
int reply = JOptionPane.showConfirmDialog(null,
"Are You sure?", "", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
res = true;
}
return res;
}
#Override
public void willExit(EventObject event) {
}
});
...
}
Not sure where your problem is, but this works for me!
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
int res=JOptionPane.showConfirmDialog(null,
"Do you want to exit.?");
if(res==JOptionPane.YES_OPTION){
Cal.this.dispose();
}
}
});
setDefaultCloseOperation() method helps in the problem .https://chortle.ccsu.edu/java5/Notes/chap56/ch56_9.html
view this link

Categories

Resources