MessageBox when closing - java

I looking for create mechanism for messaging when exiting and changes has been made.
I want it to display a messagebox asking the user :
( Are you sure you don't want to save the changes - yes / no)
Upon closing the form by clicking on the button named 'Exit' or when use close button, ''X". Don't know the syntax for it, can someone help me please?

Here's some basic code on how to do it:
public class ClosingFrame extends JFrame {
public ClosingFrame() {
super("Shutdown hook");
setSize(400, 400);
setLocationByPlatform(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* important */
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
int showConfirmDialog = JOptionPane.
showConfirmDialog(ClosingFrame.this, "Do you want to save?");
if (showConfirmDialog == JOptionPane.YES_OPTION) {
System.out.println("saved");
System.exit(0);
} else if (showConfirmDialog == JOptionPane.NO_OPTION) {
System.out.println("not saved");
System.exit(0);
} else {
System.out.println("aborted");
// do nothing
}
}
});
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new ClosingFrame());
}
}

Related

Java bluetooth connection with jssc - troubles with key listeners

I'm trying to make an app to connect computer with arduino via bluetooth.
So far it was going well (I had simple buttons to sent 0 or 1 and connection was going smoothly), but when I added key listeners it stopped responding right after it connected.
It's basically like this:
- I click 'run', app opens, I can click buttons, I can push keys on keyboard and I get info that I'm not connected
- click 'connect' - it's connected via bluetooth
- I can still click on buttons (which now don't do anything) but as soon as I push a key I can't do anything - even click on an 'x' to close it.
It appeared that the frame lost focus, so I set focusable on false on everything accept the frame.
I'm out of ideas where the problem might be...
here's the code of connect button:
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!connected){
textArea.append("Connecting to the device on port "+ selectedCOM + "....\n");
try {
serialPort = new SerialPort(selectedCOM);
textArea.append("Port opened: " + serialPort.openPort() + "\n");
textArea.append("Params set: " + serialPort.setParams(4800, 8, 1, 0) + "\n");
textArea.append("Connected succesfully!\n");
connected = true;
} catch (SerialPortException e1) {
//e1.printStackTrace();
textArea.append("Error: "+e1.getExceptionType()+"\n");
}
} else {
textArea.append("You can't do that, you are already connected!\n");
}
}
});
And a fragment of key listener (the rest if analogical):
addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP) {
up.getModel().setPressed(true);
if(connected){
try {
serialPort.writeInt(FORWARD);
System.out.println(FORWARD);
} catch (SerialPortException e1) {
textArea.append("Error: "+e1.getExceptionType()+"\n");
e1.printStackTrace();
}
}
else {
textArea.append("You are not connected.\n");
}
FORWARD is defined as 1 :
private final int FORWARD = 1;
And also here is the whole main class:
public class Communication{
private static void createAndShowGUI() {
//Create and set up the window.
Frame frame = new Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window.
frame.setFocusable(true);
frame.setSize(new Dimension(600,600));
frame.setLayout(new GridLayout());
frame.setLocation(500, 250);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The whole Frame class (which extends JFrame) has about 300 lines, so I didn't want to post it whole here. If it helps it's in here
EDIT: I changed key listeners to key bindings with swing workers, as suggested in comments, but it still doesn't responding. I think there may be some errors with connection but I have no idea how to resolve them...
Changes in the code:
forwardAction = new AbstractAction(){
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingWorker<Void,Integer> worker = new SwingWorker<Void,Integer>(){
#Override
protected Void doInBackground() throws Exception {
goForward();
return null;
}
};
worker.execute();
}
};
pane.getInputMap(IFW).put(KeyStroke.getKeyStroke("UP"), MOVE_FORWARD);
pane.getActionMap().put(MOVE_FORWARD,forwardAction);

Implementing WindowListener Error

Hello I'm having a problem with adding a WindowListener to my JFrame... It's saying "windowClosing can't be resolved to a type" and I don't know how to fix the error.
public Editor() {
//Create JFrame For Editor
JFrame SimplyHTMLJFrame = new JFrame();
SimplyHTMLJFrame.setTitle("Simply HTML - Editor");
SimplyHTMLJFrame.setSize(800, 600);
SimplyHTMLJFrame.setResizable(true);
SimplyHTMLJFrame.setLocationRelativeTo(null);
SimplyHTMLJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
SimplyHTMLJFrame.addWindowListener(new windowClosing()); //The error is here it underlines windowClosing in red
SimplyHTMLJFrame.setVisible(true);
System.out.println("Editor - JFrame 'SimplyHTMLJFrame' - Created");
//Program Closing Alert
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?\n"
+ "All unsaved changes will be lost!","Confirm", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else {
//Do nothing
}
}
}
You have to implement an inner class for the WindowListener callback.
public class Editor {
public Editor() {
// Create JFrame For Editor
JFrame SimplyHTMLJFrame = new JFrame();
SimplyHTMLJFrame.setTitle("Simply HTML - Editor");
SimplyHTMLJFrame.setSize(800, 600);
SimplyHTMLJFrame.setResizable(true);
SimplyHTMLJFrame.setLocationRelativeTo(null);
SimplyHTMLJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
SimplyHTMLJFrame.addWindowListener(new WindowAdapter() {
// Program Closing Alert
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?\n" + "All unsaved changes will be lost!", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else {
// Do nothing
}
}
}); // The error is here it underlines windowClosing in red
SimplyHTMLJFrame.setVisible(true);
System.out.println("Editor - JFrame 'SimplyHTMLJFrame' - Created");
}
new windowClosing() is not a class, so you can't instantiate it. You have two options.
Make the class implements WindowListener and use .addWindowListener(this).
Or, create an annonymous class
SimplyHTMLJFrame.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e) {
....
});
Note, if you choose method one, you will need to implements all the window listener methods below You can leave the ones you don't need, empty methods, but they still all need to be overridden. If you choose the second method, you can just use a WindowAdapter and just override the methods you need.
#Override
public void windowOpened(WindowEvent e) {}
#Override
public void windowClosing(WindowEvent e) {}
#Override
public void windowClosed(WindowEvent e) {}
#Override
public void windowIconified(WindowEvent e) {}
#Override
public void windowDeiconified(WindowEvent e) {}
#Override
public void windowActivated(WindowEvent e) {}
#Override
public void windowDeactivated(WindowEvent e) {}
As a side note, it's good practice to use the #Override annotation for method that is being overriden, so you know that you are correctly overriding a method.
The mistake you have done is, you are instantiating a method instead of a type
SimplyHTMLJFrame.addWindowListener(new windowClosing());
here windowClosing is a method in your JFrame class
You need to create our own WindowAdapter/WindowListener and add it as listener to your JFrame
Create a separate class in same/other package
class MyWindowAdapter extends WindowAdapter {
#Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?\n"
+ "All unsaved changes will be lost!","Confirm", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
} else {
//Do nothing
}
}
}
add it to your JFrame Editor
SimplyHTMLJFrame.addWindowListener(new MyWindowAdapter());
windowClosing() is the name of a method and not a class that can be instantiated.
You need to pass an instance of a WindowListener to SimplyHTMLJFrame.addWindowListener. Assuming that your Editor class either implements WindowListener or extends WindowAdapter, an assumption I'm making based on the presence of the windowClosing method, this line would be valid.
SimplyHTMLJFrame.addWindowListener(this);

confirmation before press YES to exit program in Java

private void windowClosing(java.awt.event.WindowEvent evt)
{
int confirmed = JOptionPane.showConfirmDialog(null, "Exit Program?","EXIT",JOptionPane.YES_NO_OPTION);
if(confirmed == JOptionPane.YES_OPTION)
{
dispose();
}
}
I want to close program by pressing Close Window Button with confirmation...But when I choose "No" to back to my Jframe, it still helps me to exit the program???
From what i understand you want something like this
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();
}
}
});
If you want to use it on some button do similiar function to button. Put listener on it and do same. But I'm not sure if I get your question right. But If you want to use button use ActionListener and action performed method.
check question - Java - Message when closing JFrame Window
JFrame frame = new JFrame();
// ...
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
int resp = JOptionPane.showConfirmDialog(frame, "Are you sure you want to exit?",
"Exit?", JOptionPane.YES_NO_OPTION);
if (resp == JOptionPane.YES_OPTION) {
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} else {
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
});
Try this, it's working for me.
private void windowClosing(java.awt.event.WindowEvent evt) {
int confirmed = JOptionPane.showConfirmDialog(null, "Exit Program?","EXIT",JOptionPane.YES_NO_OPTION);
if(confirmed == JOptionPane.YES_OPTION)
{
dispose();
}
} else {
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

JOptionPane.showMessageDialog wait until OK is clicked?

This might be a very simple thing that I'm overlooking, but I just can't seem to figure it out.
I have the following method that updates a JTable:
class TableModel extends AbstractTableModel {
public void updateTable() {
try {
// update table here
...
} catch (NullPointerException npe) {
isOpenDialog = true;
JOptionPane.showMessageDialog(null, "No active shares found on this IP!");
isOpenDialog = false;
}
}
}
However, I don't want isOpenDialog boolean to be set to false until the OK button on the message dialog is pressed, because if a user presses enter it will activate a KeyListener event on a textfield and it triggers that entire block of code again if it's set to false.
Part of the KeyListener code is shown below:
public class KeyReleased implements KeyListener {
...
#Override
public void keyReleased(KeyEvent ke) {
if(txtIPField.getText().matches(IPADDRESS_PATTERN)) {
validIP = true;
} else {
validIP = false;
}
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
if (validIP && !isOpenDialog) {
updateTable();
}
}
}
}
Does JOptionPane.showMessageDialog() have some sort of mechanism that prevents executing the next line until the OK button is pressed? Thank you.
The JOptionPane creates a modal dialog and so the line beyond it will by design not be called until the dialog has been dealt with (either one of the buttons have been pushed or the close menu button has been pressed).
More important, you shouldn't be using a KeyListener for this sort of thing. If you want to have a JTextField listen for press of the enter key, add an ActionListener to it.
An easy work around to suite your needs is the use of showConfirmDialog(...), over showMessageDialog(), this lets you take the input from the user and then proceed likewise. Do have a look at this example program, for clarification :-)
import javax.swing.*;
public class JOptionExample
{
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
int selection = JOptionPane.showConfirmDialog(
null
, "No active shares found on this IP!"
, "Selection : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.INFORMATION_MESSAGE);
System.out.println("I be written" +
" after you close, the JOptionPane");
if (selection == JOptionPane.OK_OPTION)
{
// Code to use when OK is PRESSED.
System.out.println("Selected Option is OK : " + selection);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Code to use when CANCEL is PRESSED.
System.out.println("Selected Option Is CANCEL : " + selection);
}
}
});
}
}
You can get acces to the OK button if you create optionpanel and custom dialog. Here's an example of this kind of implementation:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author OZBORN
*/
public class TestyDialog {
static JFrame okno;
static JPanel panel;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
zrobOkno();
JButton przycisk =new JButton("Dialog");
przycisk.setSize(200,200);
panel.add(przycisk,BorderLayout.CENTER);
panel.setCursor(null);
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
przycisk.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor"));
final JOptionPane optionPane = new JOptionPane(
"U can close this dialog\n"
+ "by pressing ok button, close frame button or by clicking outside of the dialog box.\n"
+"Every time there will be action defined in the windowLostFocus function"
+ "Do you understand?",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION);
System.out.println(optionPane.getComponentCount());
przycisk.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
final JFrame aa=new JFrame();
final JDialog dialog = new JDialog(aa,"Click a button",false);
((JButton)((JPanel)optionPane.getComponents()[1]).getComponent(0)).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
aa.dispose();
}
});
dialog.setContentPane(optionPane);
dialog.pack();
dialog.addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Zamykam");
aa.dispose();
}
#Override public void windowGainedFocus(WindowEvent e) {}
});
dialog.setVisible(true);
}
});
}
public static void zrobOkno(){
okno=new JFrame("Testy okno");
okno.setLocationRelativeTo(null);
okno.setSize(200,200);
okno.setPreferredSize(new Dimension(200,200));
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel();
panel.setPreferredSize(new Dimension(200,200));
panel.setLayout(new BorderLayout());
okno.add(panel);
}
}
Try this,
catch(NullPointerException ex){
Thread t = new Thread(new Runnable(){
public void run(){
isOpenDialog = true;
JOptionPane.setMessageDialog(Title,Content);
}
});
t.start();
t.join(); // Join will make the thread wait for t to finish its run method, before
executing the below lines
isOpenDialog = false;
}

event when closing a Window, but without closing it

I want to show a "Confirm Close" window when closing the main app window, but without making it disappear. Right now I am using a windowsListener, and more specifially the windowsClosing event, but when using this event the main window is closed and I want to keep it opened.
Here is the code I am using:
To register the listener
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
thisWindowClosing(evt);
}
});
The implementation of the handling event:
private void thisWindowClosing(WindowEvent evt) {
new closeWindow(this);
}
Also I've tried using this.setVisible(true) in the thisWindowClosing() method but it doesn't work.
Any suggestions?
package org.apache.people.mclark.examples;
import java.awt.event.*;
import javax.swing.*;
public class ClosingFrame extends JFrame {
public ClosingFrame() {
final JFrame frame = this;
// Setting DO_NOTHING_ON_CLOSE is important, don't forget!
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int response = JOptionPane.showConfirmDialog(frame,
"Really Exit?", "Confirm Exit",
JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.OK_OPTION) {
frame.dispose(); // close the window
} else {
// else let the window stay open
}
}
});
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClosingFrame().setVisible(true);
}
});
}
}

Categories