How to prevent that closing a JDialog closes the entire application - java

I have a main(screen) gui window and need to open a few "multi input" windows (jdialog or when not possible jframe), for example to add preferences (4 textfields with 2 filechoosers and 2 radiobuttons).
When pressing OK/Cancel in these JDialogs (or JFrames), my entire application closes.
I don't want that. How can I prevent that?
First try: I tried the intelliJ option "New -> Create Dialog class", which gives me a JDialog with OK/Cancel button. Pressing one of the buttons closes the JDialog and my entire application.
Second try: I wrote a class "by hand" which creates a JDialog (and also tried JFrame). Again: Pressing one of the buttons closes the JDialog and my entire application.
I removed "dispose()" and "setVisible(false)" options from theJDialog (JFrame), but still my entire application is closed.
main class method
public class mainScreen {
// Menu action listener (only relevant options)
class MenuActionListener implements ActionListener {
// menuListener
public void actionPerformed(ActionEvent ev) {
//myVariables myVars = new myVariables();
String[] dummy = null;
System.out.println("Selected: " + ev.getActionCommand());
switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
}
// method that opens the external class (see below in following code block)
private void showPreferencesDialog() {
prefJDialog myprefs = new prefJDialog(prefsPanel);
myprefs.showDialog();
boolean okPressed = myprefs.isOkPressed();
if (okPressed) {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"OK pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"Cancel pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
}
}
// This is the class which is mention in the manifest
public mainScreen(JFrame frame) {
boolean preferences = false;
Preferences prefs = Preferences.userRoot();
createmyMenuBar(frame);
groupRadiobuttonsandListen();
fileNamesTableListener();
try {
myUtils.DisplayLogo(mainScreen.this.iconLabel);
} catch(IOException ex) {
System.out.println("Error reading Logo");
}
preferences = check_preferences();
if (!preferences) {
myUtils.checkExifTool(mainScreen.this.rootPanel);
}
programButtonListeners();
}
// main method in my main class for my project
public static void main(String[] args) {
JFrame frame = new JFrame("jExifToolGUI");
frame.setContentPane(new mainScreen(frame).rootPanel);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The JDialog class/method that is called from the main class
package org.hvdw.jexiftoolgui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class prefJDialog extends JDialog {
private JButton okButton;
private JButton cancelButton;
private JPanel prefsPanel;
private boolean okPressed;
public prefJDialog(JPanel prefsPanel) {
super(JOptionPane.getFrameForComponent(prefsPanel), true);
this.prefsPanel = prefsPanel;
setTitle("Preferences");
initDialog();
}
public void showDialog() {
setSize(800, 768);
double x = getParent().getBounds().getCenterX();
double y = getParent().getBounds().getCenterY();
setLocation((int) x - getWidth() / 2, (int) y - getHeight() / 2);
setVisible(true);
}
private void initDialog() {
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
add(pane);
pane.add(Box.createVerticalGlue());
FlowLayout l = new FlowLayout(FlowLayout.RIGHT);
JPanel buttonsPane = new JPanel(l);
okButton = new JButton("Save"); //$NON-NLS-1$
buttonsPane.add(okButton);
pane.getRootPane().setDefaultButton(okButton);
cancelButton = new JButton("CANCEL"); //$NON-NLS-1$
buttonsPane.add(cancelButton);
buttonsPane.setMaximumSize(new Dimension(Short.MAX_VALUE, (int) l.preferredLayoutSize(buttonsPane).getHeight()));
pane.add(buttonsPane);
addListeners();
}
private void addListeners() {
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//saveProperties();
setVisible(false);
okPressed = true;
//close();
// dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
//dispose();
//close();
okPressed = false;
}
});
}
public boolean isOkPressed() {
return okPressed;
}
/*public void close() {
WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}*/
}
So how do I prevent that upon clicking OK or Cancel in the JDialog, the entire application closes. That needs to stay open until the user clicks the "window close" X in the top-right, or from the menu "File -> Exit"
I have searched Google for several days, but can't find a solution (and one same question without answer).
Edit:
After Patrick's answer I changed the close method to
public void close() {
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
}
And removed the /* and */.
I also activated the close(); in the listeners again, but it doesn't make a difference. My main app is still closed.

switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
And the problem is that you don't have a break statement in your switch case so the code falls through to the "Exit" logic and does a System.exit(0)
This is why we need a proper "MCVE" with every question. When you post random pieces of code we can't see the entire logic flow.

Related

how to use mouse click event

Hi i have a class where i am using mouseclick event i want to call another class when i click from my mouse
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JList theList = (JList) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2) {
int index = theList.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Object o = theList.getModel().getElementAt(index);
// System.out.println("Double-clicked on: " + o.toString());
String a=o.toString();
LiistSelection.setListIndex(a);
System.out.println(LiistSelection.getListIndex());
new MyGui4();
}
}
}
};
i want to call this class when user click on list then new window should open
here is my class mygui4.java
public class MyGui4 extends JFrame
{
JLabel jLabel1;
Container pane;
private static ResultSet resultSet = null;
public void Gui( )
{
{
getContentPane().setBackground(new java.awt.Color(255,153,51));
}
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
ImageIcon image = new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\a0.png");
Border border = LineBorder.createGrayLineBorder();
jLabel1 = new JLabel(image);
jLabel1.setBorder(border);
jLabel1.setBackground(Color.red);
c.add(jLabel1);
setLayout(null);
}
public static void main( String[] args )
{
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
}
}
You want to Create a object of another Class and call a function using a object.
class second
{
//.....
public void function()
{
//........
}
public void function(int index)
{
//..........
}
}
second s=new second();
s.function()//calling function
int i=10;
s.function(i)//calling function with parameter
Try This Example :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class m extends JFrame
{
String s="The Value of List is 10";
m()
{
setVisible(true);
pack();
setLayout(null);
JButton b=new JButton("Click to Open another form");
b.setBounds(10,10,200,40);
add(b);
b.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
new s(s);//calling another class contructor
}
});
}
public static void main (String[] args)
{
new m();
}
}
class s extends JFrame
{
s(String s)
{
setVisible(true);
setSize(100,100);
setTitle(s);
}
}
Click The button Another Class and Open The Window
It looks to me like you are tying to invoke the class MyGui4 from the command line when you start the JVM or from another application when you click on the JList, If so then the code needs to be the same in both places.
When invoked from the command line the main() method is invoked which in turn invokes 3 lines of code:
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
When you invoke the code when clicking on the JList you invoke 1 line of code:
new MyGui4();
Can you tell me what the difference is?
Of course I still don't understand the point of this code because none of the methods in your MyGui4 class accept a parameter. So it doesn't matter which item in the JList you click on you will still display the same GUI with the same information. You need to pass the selected object from your JList to your GUI.

Run and pause a GUI background thread by clicking a button

I need to run a background thread in my Java GUI that only runs when I click a button and pauses when I click that button again. I am not exactly sure how to set this up, but I have placed a thread in my constructor and the while loop within is set to go through when I set a specific boolean to TRUE. One button switches from setting this boolean TRUE or FALSE.
Everything else I have in this GUI works fine. When I tried debugging the thread, it actually works as I step through the thread but nothing when I try running the GUI completely. The GUI is rather large so I'm gonna put up a portion of the constructor and the action listener of the button. The rest of the code is unnecessary since it works just fine. I need to know what I am doing wrong here:
public BasketballGUI() {
// certain labels and buttons
Thread runningSim = new Thread() {
public void run() {
while(simRun) {
// do stuff here
}
}
};
runningSim.start();
}
// other GUI stuff
// actionListener that should run the thread.
class SimButtonListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
if(!simRun) {
simRun = true;
sim.setText("Pause Simulator");
}
else if(simRun) {
simRun = false;
sim.setText("Run Simulator");
}
// other stuff in this actionListener
}
}
Establish a Swing based Timer with an ActionListener that will be called repeatedly.
In the actionPerformed(ActionEvent) method call repaint().
Start the timer (Timer.start()) when the user clicks Start
Stop the timer (Timer.stop()) when the user clicks Stop
If you cannot get it working from that description, I suggest you post an SSCCE of your best attempt.
I thought I had one 'lying around'.. Try this working SSCCE which uses images created in this SSCCE.
I could see this background thread useful for a Java GUI when handling button events to affect something like a text area or progress bar.
For the sake of argument, I will build you a tiny GUI that affects a Text Area. I hope this helps you.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.*;
public class TestClass extends JPanel {
super("TestClass - Title");
private AtomicBoolean paused;
private JTextArea jta;
private JButton btn;
private Thread thread;
public TestClass() {
paused = new AtomicBoolean(false);
jta = new JTextArea(100, 100);
btn = new JButton();
initialize();
}
public void initialize() {
jta.setLineWrap(true);
jta.setWrapStyleWord(true);
add(new JScrollPane(jta));
btn.setPreferredSize(new Dimension(100, 100));
btn.setText("Pause");
btn.addActionListener(new ButtonListener());
add(btn);
Runnable runnable = new Runnable() {
#Override
public void run() {
while(true) {
for(int i = 0; i < Integer.MAX_VALUE; i++) {
if(paused.get()) {
synchronized(thread) {
try {
thread.wait();
} catch(InterruptedException e) {
}
}
}
}
jta.append(Integer.toString(i) + ", ");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
};
thread = new Thread(runnable);
thread.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 30);
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
if(!paused.get()) {
btn.setText("Start");
paused.set(true);
} else {
btn.setText("Pause");
paused.set(false);
synchronized(thread) {
thread.notify();
}
}
}
}
}
Main class to call everything.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainClass {
public static void main(final String[] arg) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestClass());
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
});
}
}
I did not test this code to see if it works exactly, Its main goal is to break you through your coders block and use my components to fix your issue. Hope this helped. Need anything else Email me at DesignatedSoftware#gmail.com

Java: How to cancel application exit

On one of my programs, I want a Dialog to appear when the user attempts to exit the application. The user must then choose to save some state of the program, not to save or to cancel the exit operation.
I wrote this in an attempt to find a solution first and ony then implement it:
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
class WL implements WindowListener
{
private boolean statussaved;
private JFrame tframe;
WL (JFrame frame)
{
statussaved = false;
tframe = frame;
}
#Override public void windowActivated (WindowEvent w) { }
#Override public void windowClosed (WindowEvent w) { }
#Override public void windowDeactivated (WindowEvent w) { }
#Override public void windowDeiconified (WindowEvent w) { }
#Override public void windowIconified (WindowEvent w) { }
#Override public void windowOpened (WindowEvent w) { }
#Override public void windowClosing (WindowEvent w)
{
if (statussaved)
{
return;
}
final JDialog diag = new JDialog (tframe, "Save Progress", true);
diag.setPreferredSize (new Dimension (500, 100));
diag.setResizable (false);
diag.setDefaultCloseOperation (JDialog.DISPOSE_ON_CLOSE);
JPanel notifypanel = new JPanel ();
notifypanel.add (new JLabel ("Do you want to save the current status ?"));
JButton yesbutton = new JButton ("Yes");
JButton nobutton = new JButton ("No");
JButton cancelbutton = new JButton ("Cancel");
yesbutton.addActionListener (new ActionListener ()
{
#Override public void actionPerformed (ActionEvent a)
{
//SAVE THE STATUS
System.out.println ("Saving status...");
statussaved = true;
diag.dispose ();
tframe.dispose ();
}
});
nobutton.addActionListener (new ActionListener ()
{
#Override public void actionPerformed (ActionEvent a)
{
//just exit/close the application
diag.dispose ();
tframe.dispose ();
}
});
cancelbutton.addActionListener (new ActionListener ()
{
#Override public void actionPerformed (ActionEvent a)
{
//DON'T EXIT !!!
diag.dispose ();
}
});
notifypanel.add (yesbutton);
notifypanel.add (nobutton);
notifypanel.add (cancelbutton);
diag.setContentPane (notifypanel);
diag.pack ();
diag.setVisible (true);
}
}
public class SaveTest
{
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
#Override public void run ()
{
JFrame frame = new JFrame ("Save Test");
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener (new WL (frame));
JLabel lab = new JLabel ("just some information");
frame.setPreferredSize (new Dimension (400, 300));
frame.setResizable (false);
frame.add (lab);
frame.pack ();
frame.setVisible (true);
}
});
}
}
It compiles and runs without any change, so you can test it.
The "Yes" and "No" choices work as expected, but I have absolutely no idea what to write in the ActionListener of the "Cancel" button. What I want is, when the user clicks the "Cancel" button, the dialog dissapears, but the main window remains visible (i.e. the program keeps running).
Now, since all this is implemented in the windowClosing method, it's kind of clear that some sort of dispose signal was sent in order to destroy the JFrame. This means that there is probably no way this can be done in the current design. I don't mind reorganizing/redesigning all this to make it work. It's just... I don't know how.
Any ideas ?
Replace
mainframe.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
with
mainframe.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);
If user cancels closing - do nothing. If agrees - call dispose() manually.
Have a look at JOptionPane, which handles most of this stuff for you, e.g.
JOptionPane.showConfirmDialog(frame, "please choose one",
"information",
OptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
Your DefaultCloseOperation needs to be DO_NOTHING_ON_CLOSE so that your dialog can handle things - otherwise the window will get disposed before the user can cancel it. Then you manually close the window or exit the application or whatever according to the user's choice.

Java - Show a minimized JFrame window

If a JFrame window is minimized, is there any way to bring it back to focus?
I am trying to get it to click a certain point, then restore it.
while (isRunning) {
start = System.currentTimeMillis();
frame.setState(Frame.ICONIFIED);
robot.mouseMove(clickX, clickY);
robot.mousePress(InputEvent.BUTTON1_MASK);
frame.setState(Frame.NORMAL);
Thread.sleep(clickMs - (System.currentTimeMillis() - start));
}
If you want to bring it back from being iconified, you can just set its state to normal:
JFrame frame = new JFrame(...);
// Show the frame
frame.setVisible(true);
// Sleep for 5 seconds, then minimize
Thread.sleep(5000);
frame.setState(java.awt.Frame.ICONIFIED);
// Sleep for 5 seconds, then restore
Thread.sleep(5000);
frame.setState(java.awt.Frame.NORMAL);
Example from here.
There are also WindowEvents that are triggered whenever the state is changed and a WindowListener interface that handles these triggers.In this case, you might use:
public class YourClass implements WindowListener {
...
public void windowDeiconified(WindowEvent e) {
// Do something when the window is restored
}
}
If you are wanting to check another program's state change, there isn't a "pure Java" solution, but just requires getting the window's ID.
You can set the state to normal:
frame.setState(NORMAL);
Full example:
public class FrameTest extends JFrame {
public FrameTest() {
final JFrame miniFrame = new JFrame();
final JButton miniButton = new JButton(
new AbstractAction("Minimize me") {
public void actionPerformed(ActionEvent e) {
miniFrame.setState(ICONIFIED);
}
});
miniFrame.add(miniButton);
miniFrame.pack();
miniFrame.setVisible(true);
add(new JButton(new AbstractAction("Open") {
public void actionPerformed(ActionEvent e) {
miniFrame.setState(NORMAL);
miniFrame.toFront();
miniButton.requestFocusInWindow();
}
}));
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new FrameTest();
}
}

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