On button click, close the application Java GUI - java

I have a java application, want to close the GUI with confirmation window to close the application
for example:-
frmViperManufacturingRecord.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frmViperManufacturingRecord.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e){
JFrame frame = (JFrame)e.getSource();
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to close the application?", "Please Confirm",JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
This is working fine, when I press the window close (x) button, but I want to bring this event to a button to perform the action 'On Click', since I am newbie finding difficulties to bring it inside the 'actionPerformed'
So far I have tried the code below and it didn't work...
//close window button
JButton btnCloseWindow = new JButton("Close Window");
btnCloseWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//frmViperManufacturingRecord.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frmViperManufacturingRecord.dispose();
//System.exit(0);
JFrame frame = (JFrame)e.getSource();
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to close the application?", "Please Confirm",JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
Please give me some directions on this, thanks

Change this:
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
to
if (result == JOptionPane.YES_OPTION)
System.exit(0);
}
frame.setDefaultCloseOperation is what happens when someone clicks the 'x' to close the window. Every other way to exit is controlled by you. The best way is to have your window closing listener and action listener call the same method that will pop up the dialog and call System.exit(0) if the user wants to exit. This will also help you with cleanup operations.
Sample code:
public class Test extends JPanel implements WindowListener {
public Test() {
setLayout(new BorderLayout());
add(new JLabel("This is a test."), BorderLayout.CENTER);
JButton b = new JButton("Exit");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exit();
}
});
add(b, BorderLayout.SOUTH);
}
public static void main(String[] args) throws Exception {
JFrame f = new JFrame();
Test t = new Test();
f.add(t, BorderLayout.CENTER);
f.addWindowListener(t);
f.pack();
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
exit();
}
private void exit() {
System.exit(0);
}
}

You can try:
if (result == JOptionPane.YES_OPTION){
frame.dispose();
}
Also note CastException on the line 122.
Instead of
JFrame frame = (JFrame)e.getSource();
change to:
JFrame frame = new JFrame();

if still not working then try
frame.setVisible(false);
frame.dispose();
in if(result == JOptionPane.YES_OPTION){} block

Related

JFrame is disabled after closing JFileChooser and JDialog

I really need your help, cause I'm struggling with it. I've created a JFrame in which I can open up a JDialog for e.g. changing settings. In the JDialog there is a button for starting a JFileChooser. I'm able to choose a file and everything works fine. But if I'm just closing the JFileChooser AND the JDialog, the JFrame will disable and minimize.
Does anyone know how to fix that?
Building JFrame:
frame = new JFrame("My first JFrame");
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
closeWindow();
}
});
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
frame.getRootPane().getActionMap().put("Cancel", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
[...]
frame.getContentPane().setLayout(null);
frame.setVisible(true);
Building JDialog:
final EditColumnsDialog editColumnsDialog = new EditColumnsDialog(frame, ...);
editColumnsDialog.editPicPath();
...
class EditColumnsDialog extends JDialog {
EditColumnsDialog(final JFrame owner, ...) throws Exception {
super(owner, owner.getTitle());
[...]
}
...
protected void editPicPath() {
[...]
JButton searchButton = new JButton("Search");
searchButton.setVisible(true);
searchButton.addActionListener(e -> {
File folder = WindowBuilder.fileChooser(JFileChooser.DIRECTORIES_ONLY, picPath.getText());
if (folder != null) {
picPath.setText(folder.getAbsolutePath());
}
});
[...]
pack();
setVisible(true);
setModal(true);
}
}
Building JFileChooser:
static File fileChooser(final int fileSelectionMode, final String dir) {
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setFileSelectionMode(fileSelectionMode);
jFileChooser.setCurrentDirectory(new File(dir));
Action details = jFileChooser.getActionMap().get("viewTypeDetails");
details.actionPerformed(null);
if (jFileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
return jFileChooser.getSelectedFile();
} else {
return null;
}
}
Found the solution:
in EditColumnsDialog (JDialog) setting "setModal(true)" BEFORE (!!!) "setVisible(true)"
This will ensure that the new window (JDialog) opened in a JFrame is blocking the old window, then the JFileChooser window is blocking the JDialog and after closing it the other one will gain focus.

Opening a new JFrame and close previous after clicking button

How can I code a button that, when clicked, closes the current JFrame and opens a new one?
This is what I have so far, but the old frame stays open:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
practise1 s = new practise1();
s.setVisible(true);
}
I have tried using .close() after the first { but it gives me an error.
If you plan on using the originial JFrame later, use setVisible(false) on the original JFrame. If you plan on closing the first JFrame and never reusing it, you can use dispose().
public void actionPerformed(ActionEvent e)
{
if(e.getSource () == button)
{
test = new JFrame();
test.setSize(300,300);
test.setVisible (true);
this.dispose();
}
}
Dispose AFTER creating the new Frame.
Thanks for the help everyone. I got it working using the this.dispose(); method
Lets say current Frame is FirstFrame
and clicking on JButton goes to NewFrame
import javax.swing.*;
public class FirstFrame extends Jframe implements ActionListener{
JButton button;
public FirstFrame(){
setVisible(true);
setSize(500,500);
button=new JButton("Click me");
button.addActionListner(this);
add(button);
}
public static void main(String[] args)
{
new FirstFrame();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
NewFrame nf=new NewFrame(); // Clicking on the Button will OPEN new Frame in NewFrame.java file
dispose(); //this method will close the FirstFrame
}
}
}
you just put this in your code :
(the exemple here i JButton to do this with the ActionPerformed method)
/**********************************************************************/
private void openBTNActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
FrameTarget t = new FrameTaregt();
t.setVisible(true);
//set the size : 1250 pixels de width and 720 pixels de height
t.setSize(1250, 720);
//make the frame in the center wuth this
t.setLocationRelativeTo(null);
t.setResizable(true);
}

making JOptionPane disappear

public void windowClosing (WindowEvent e)
{
JFrame frame = new JFrame();
int confirm = JOptionPane.showConfirmDialog (frame, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION)
{
dispose ();
}
else
{
frame.setVisible(false);
}
}
So when the user clicks on the close button, a JOptionPane pops up. When the user clicks on "No" the JOptionpane is supposed to disappear and then return to the frame it was originally displaying, but with my code, even when I click on No, both frames, the one for the JOptionPane and the one it sits on, disappear.
One thing:
I know I should not create a new JFrame for a JOptionPane, but I tried using this for the component, like: JOptionPane.showConfirmDialog (this, "...",...) when the user clicks on "No" the JOptionPane is the only thing that's supposed to disappear (so I set it to: this.setVisible(false);) but when I use this even the main frame disappears, so I just thought to create a new frame to meet my needs. I can't set it to null either because I need it to appear at the center of the screen. If anyone could advise me on how to handle this, please do.
It's really simple, your frame disappear because you say that it should not be visible, just remove that else:
public void windowClosing (WindowEvent e) {
int confirm = JOptionPane.showConfirmDialog (this, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
dispose();
}
}
EDIT:
Also replace setDefaultCloseOperation (EXIT_ON_CLOSE); with setDefaultCloseOperation (DO_NOTHING_ON_CLOSE);, else the main frame would close regardless of what happens in the windowClosing method.
Just don't put else if you don't want to hide the frame. The JOptionPane will disappear by itself, whether you click yes or no.
Don't create a new JFrame in the method. That's why you have random frame from now where.
public void windowClosing (WindowEvent e)
{
JFrame frame = new JFrame();
Pass the reference of the JFrame in question. If the code above is from a JDialog you can do something like this
public class MyDialog extends JDialog {
public MyDialog(final JFrame frame, boolean modal) {
super(frame, modal);
public void windowClosing (WindowEvent e) {
int confirm = JOptionPane.showConfirmDialog (frame, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
dispose ();
}
}
}
}
And just instantiate the JDialog like this from your GUI class with the JFrame
MyDialog dialog = new MyDialog(thisFrame, true);
Side Note
Why Even have a JOptionPane and a JDialog? Ultimately, a JDialog is just a custom JOptionPane, they have the same functionality.
EDIT
If you just want to pass the JFrame class as reference to the JOPtionPane just pass
MyFrameClass.this
instead of a new JFrame()
UDPATE
Test out this program using a simple custom JDialog.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogExample extends JFrame {
public JDialogExample() {
JButton exit = new JButton("Do you want to Exit?");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new HelloDialog(JDialogExample.this, true);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(exit);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private class HelloDialog extends JDialog {
public HelloDialog(final JFrame frame, boolean modal) {
super(frame, modal);
JButton exit = new JButton("EXIT");
JButton cancel = new JButton("CANCEL");
setLayout(new GridLayout(2, 1));
JPanel panel = new JPanel();
panel.add(exit);
panel.add(cancel);
add(new JLabel("Do you want to exit?", JLabel.CENTER));
add(panel);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JDialogExample();
}
});
}
}

How do I prevent a window from closing?

first sorry for my bad english.
Hi, i'm trying to use a confirmDialog with a YES_NO_OPTION.
what i want is that when i close a frame a confimDialog will be displayed asking me if want to close.
if i press yes everyThing most be closed, if i press no the confirmDialog will disapear
but the problem is even if i press no button the frame close this is my code:
final JFrame frame = new JFrame("2D Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1600,600);
frame.setResizable(false);
private void continuerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_continuerButtonActionPerformed
int level=getlevel();
System.out.println(niveau);
if(niveau == 1)
{
this.dispose();
frame.add(new Board());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
doExitOption();
}
});
}
}
and this is doExitOption methode:
public void doExitOption()
{
int option=JOptionPane.showConfirmDialog(null, "do you want to quit the game", "Warnning",JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
{
frame.dispose();
}
}
See Closing an Application. It can manager the default close operation for you.
You need to change the JFrame's default close operation so that your call to dispose is the only call being made to dispose the window:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Change Default closing of JFrame to DO_NOTHING_ON_CLOSE .

How does JFileChooser return the exit value?

A typical way to use JFileChooser includes checking whether user clicked OK, like in this code:
private void addModelButtonMouseClicked(java.awt.event.MouseEvent evt) {
JFileChooser modelChooser = new JFileChooser();
if(modelChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ){
File selectedFile = modelChooser.getSelectedFile();
if(verifyModelFile(selectedFile)){
MetModel newModel;
newModel = parser.parse(selectedFile, editedCollection.getDirectory() );
this.editedCollection.addModel(newModel);
this.modelListUpdate();
}
}
}
I tried to mimic this behavior in my own window inheriting JFrame. I thought that this way of handling forms is more convenient than passing collection that is to be edited to the new form. But I have realized that if I want to have a method in my JFrame returning something like exit status of it I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window.
So, how does showOpenDialog() work? When I tried to inspect the implementation, I found only one line methods with note "Compiled code".
I tried to mimic this behavior in my own window inheriting JFrame.
JFrame is not a modal or 'blocking' component. Use a modal JDialog or JOptionPane instead.
E.G.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/** Typical output:
[JTree, colors, violet]
User cancelled
[JTree, food, bananas]
Press any key to continue . . .
*/
class ConfirmDialog extends JDialog {
public static final int OK_OPTION = 0;
public static final int CANCEL_OPTION = 1;
private int result = -1;
JPanel content;
public ConfirmDialog(Frame parent) {
super(parent,true);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
content = new JPanel(new BorderLayout());
gui.add(content, BorderLayout.CENTER);
JPanel buttons = new JPanel(new FlowLayout(4));
gui.add(buttons, BorderLayout.SOUTH);
JButton ok = new JButton("OK");
buttons.add(ok);
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = OK_OPTION;
setVisible(false);
}
});
JButton cancel = new JButton("Cancel");
buttons.add(cancel);
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
result = CANCEL_OPTION;
setVisible(false);
}
});
setContentPane(gui);
}
public int showConfirmDialog(JComponent child, String title) {
setTitle(title);
content.removeAll();
content.add(child, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getParent());
setVisible(true);
return result;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Test ConfirmDialog");
final ConfirmDialog dialog = new ConfirmDialog(f);
final JTree tree = new JTree();
tree.setVisibleRowCount(5);
final JScrollPane treeScroll = new JScrollPane(tree);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Choose Tree Item");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = dialog.showConfirmDialog(
treeScroll, "Choose an item");
if (result==ConfirmDialog.OK_OPTION) {
System.out.println(tree.getSelectionPath());
} else {
System.out.println("User cancelled");
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(b);
p.setBorder(new EmptyBorder(50,50,50,50));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
I guess you wait for the user to click some button by constantly checking what button is pressed.
"I need to make it wait for user clicking OK or Cancel without freezing the form/dialog window."
May be you should use evens to get notified, when the user clicks on something, not waiting for them to press the button - maybe there is some OnWindowExit event?
Or maybe something like this:
MyPanel panel = new MyPanel(...);
int answer = JOptionPane.showConfirmDialog(
parentComponent, panel, title, JOptionPane.YES_NO_CANCEL,
JOptionPane.PLAIN_MESSAGE );
if (answer == JOptionPane.YES_OPTION)
{
// do stuff with the panel
}
Otherwise you might see how to handle window events, especially windowClosing(WindowEvent) here

Categories

Resources