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
Related
I am working with Swing right now and I do not get this to work properly.
What I need is the following:
I've got a class "Client" that is able to connect to a TCP server.
If the connection fails (wrong IP for example), then it will show an error dialog that can be closed by clicking on the "OK" Button.
However if the client connected successfully, a window should popup that runs until my client receives a specific message from the server.
My code looks like this:
if(ip != null) {
Client c = new Client();
try{
c.connect(ip, 56556);
JOptionPane msg = new JOptionPane("Connecting...", JOptionPane.INFORMATION_MESSAGE);
JDialog dlg = msg.createDialog("Connecting...");
dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dlg.setVisible(true);
c.addIncomingMessageHandler(new IncomingMessageHandler(){
#Override
public void incomingMessage(Connection<?> cnctn, Object o) {
dlg.setVisible(false);
dlg.dispose();
}
});
}catch(Exception e) {
int n = JOptionPane.showOptionDialog(this, "Oops! Something went wrong!",
"Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
null, new Object[] {"OK"}, JOptionPane.OK_OPTION);
}
}
So the exception is throws if c.connect() fails.
c.addIncomingMessageHandler() is a listener that listens to any incoming messages to the client. If the server sends something, this method will be called. If that's the case, the JDialog will be closed. But this window can be closed right now by clicking on the OK-Button.
I'd like to rename that button and add a function.
The new text should be "Cancel" and if the button is pressed, the client should be closed (c.disconnect) and the window itself should be closed as well.
How could I do that?
From the Documentation:
Stopping Automatic Dialog Closing
By default, when the user clicks a JOptionPane-created button, the dialog closes. But what if you want to check the user's answer before closing the dialog? In this case, you must implement your own property change listener so that when the user clicks a button, the dialog does not automatically close.
DialogDemo contains two dialogs that implement a property change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog, that uses JOptionPane both to get the standard icon and to get layout assistance. The other dialog, whose code is below, uses a standard Yes/No JOptionPane. Though this dialog is rather useless as written, its code is simple enough that you can use it as a template for more complex dialogs.
Besides setting the property change listener, the following code also calls the JDialog's setDefaultCloseOperation method and implements a window listener that handles the window close attempt properly. If you do not care to be notified when the user closes the window explicitly, then ignore the bold code.
final JOptionPane optionPane = new JOptionPane(
"The only way to close this dialog is by\n"
+ "pressing one of the following buttons.\n"
+ "Do you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
final JDialog dialog = new JDialog(frame,
"Click a button",
true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setLabel("Thwarted user attempt to close window.");
}
});
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (dialog.isVisible()
&& (e.getSource() == optionPane)
&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
//If you were going to check something
//before closing the window, you'd do
//it here.
dialog.setVisible(false);
}
}
});
dialog.pack();
dialog.setVisible(true);
int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
setLabel("Try using the window decorations "
+ "to close the non-auto-closing dialog. "
+ "You can't!");
}
Click here!
Related question.
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!
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);
}
here is my code :
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the program?", "Exit Program ",
JOptionPane.YES_NO_OPTION);
System.out.println(a);
if(a==JOptionPane.OK_OPTION){
dispose();
}
}});
The problem is either a==OK_OPTION or a==CANCEL_OPTION the frame will close.
Why?
You might have set the default close operation of JFrame as EXIT_ON_CLOSE. So this exits the JFrame no matter if you press OK or CANCEL. You should instead set the default close operation as DO_NOTHING_ON_CLOSE if you want to manually handle the close operation of your JFrame.
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the program?", "Exit Program ",
JOptionPane.YES_NO_OPTION);
System.out.println(a);
if(a==JOptionPane.OK_OPTION){
dispose();//You can use System.exit(0) if you want to exit the JVM
}
}});
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
}
}
}
);
}