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.
Related
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.
I want to implement a method where the user needs to hold the left and right mouse buttons at the same time.
I'm using Swing and Java 1.7. I've tried this, but it doesn't detect the both-buttons case like I'd expect it to:
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && SwingUtilities.isRightMouseButton(e)){
///code here
}
}
i tried to separate methods and use bool values to decide if the mouse button is pressed and then i set a condition to find out if both of them are pressed at the same time , but that didint work out too ..
This is an SSCCE that does what you want... i.e. if I understood your question correctly.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StackOverflow15957076 extends MouseAdapter
{
private JLabel status;
private boolean isLeftPressed;
private boolean isRightPressed;
public StackOverflow15957076 ()
{
JFrame frame = new JFrame ();
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel (new FlowLayout (FlowLayout.CENTER));
status = new JLabel ("waiting for both mouse buttons...");
status.addMouseListener (this);
panel.add (status);
frame.add (panel);
frame.pack ();
frame.setVisible (true);
isLeftPressed = false;
isRightPressed = false;
}
#Override
public void mousePressed (MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton (e))
{
isLeftPressed = true;
}
else if (SwingUtilities.isRightMouseButton (e))
{
isRightPressed = true;
}
if (isLeftPressed && isRightPressed)
{
status.setText ("both buttons are pressed");
}
}
#Override
public void mouseReleased (MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton (e))
{
isLeftPressed = false;
}
else if (SwingUtilities.isRightMouseButton (e))
{
isRightPressed = false;
}
status.setText ("waiting for both mouse buttons...");
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
#Override
public void run ()
{
new StackOverflow15957076 ();
}
});
}
}
It seems that it's not possible do it directly, since mouse events are fired sequentially. See, for example, this SO question/answers.
So you will need to decide what "at the same time" actually means to you (i.e. how close in time thay should be). Then you can capture two separate events and compare their getWhen() values.
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();
}
}
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
I'm in the process of creating a GUI in Netbeans 6.1 for my senior design project but i've run into an annoying snag. Temporary Windows like my login PopUp and others wont disappear when i tell it. I've been researching how to solve this for about 2 months on an off. I've even mad a separate thread for my Pop Up but it still wont work....the only way it will disappear if i literally dont mess with any of the other GUI components....my sample code should help describe my anger...dont mind the shadow code, it was for testing purposes, which obviously didnt help.
//This method is called once a user presses the "first" login button on the main GUI
public synchronized void loginPopUpThread() {
doHelloWorld = new Thread(){
#Override
public synchronized void run()
{
try
{
loginPopUpFrame.pack();
loginPopUpFrame.setVisible(true);
System.out.println("waitin");
doHelloWorld.wait();
System.out.println("Not Sleepin..");
loginPopUpFrame.pack();
loginPopUpFrame.setVisible(false);
}
catch (InterruptedException e)
{
}
}
};
doHelloWorld.start();
//This is called when the "second" loginB is pressed and the password is correct...
public synchronized void notifyPopUp() {
synchronized(doHelloWorld) {
doHelloWorld.notifyAll();
System.out.println("Notified");
}
}
I've also tried Swing Utilities but maybe i implemented it wrong as it's my first time using them. It essentially does the same thing as the code above except the window freezes when it gets to wait, which the above code doesnt do:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public synchronized void run() {
try
{
loginPopUpFrame.pack();
loginPopUpFrame.setVisible(true);
System.out.println("waitin");
wait();
System.out.println("Not Sleepin.");
loginPopUpFrame.pack();
loginPopUpFrame.setVisible(false);
}
catch (InterruptedException e)
{
}
}
});
PLEASE HELP ME!!!
Rules of thumb:
Don't manipulate GUI components in arbitrary threads; always arrange to manipulate them in the event thread
Never wait or sleep inside the event thread (so, never inside code sent to invokeLater())
So the answer to how you solve this problem is "some other way"...
Standing back from the problem a bit, what is it you're actually trying to do? If you just want a login dialog to wait for the user to enter user name and password, is there a reason not to just use a modal JDialog (after all, that's what it's there for...).
If you really do want some arbitrary thread to wait for a signal to close the window/manipulate the GUI, then you need to do the waiting in the other thread, and then make that thread call SwingUtilities.invokeLater() with the actual GUI manipulation code.
P.S. There are actually some GUI manipulation methods that it is safe to call from other threads, e.g. calls that are "just setting a label" are often safe. But which calls are safe isn't terribly well-defined, so it's best just to avoid the issue in practice.
The Swing components should only be manipulated by the swing event dispatch thread.
class SwingUtilites has methods to submit tasks to the dispatch thread.
It is difficult to diagnose your problem. I'm not sure what you're trying to do with the wait methods, but I recommend leaving wait/notify alone.
This code has two frames - when you create a second frame, the first is hidden until you close it.
public class SwapFrames {
private JFrame frame;
private JFrame createMainFrame() {
JButton openOtherFrameButton = new JButton(
"Show other frame");
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(openOtherFrameButton);
frame.pack();
openOtherFrameButton
.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
onClickOpenOtherFrame();
}
});
return frame;
}
private void onClickOpenOtherFrame() {
frame.setVisible(false);
JFrame otherFrame = new JFrame();
otherFrame
.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
otherFrame.setContentPane(new JLabel(
"Close this to make other frame reappear."));
otherFrame.pack();
otherFrame.setVisible(true);
otherFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
JFrame frame = new SwapFrames().createMainFrame();
frame.setVisible(true);
}
}
Because I don't see any evidence of them in your code, I'm going to suggest you read up on using event listeners rather than trying to "wait" for code to finish.
It isn't entirely clear what you're trying to achieve, but you might be better off with a modal dialog:
public class DialogDemo {
public JFrame createApplicationFrame() {
JButton openDialogButton = new JButton("Open Dialog");
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = frame.getContentPane();
container.setLayout(new FlowLayout());
container.add(openDialogButton);
frame.pack();
openDialogButton
.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
onOpenDialog(frame);
}
});
return frame;
}
private void onOpenDialog(JFrame frame) {
JDialog dialog = createDialog(frame);
dialog.setVisible(true);
}
private JDialog createDialog(JFrame parent) {
JButton closeDialogButton = new JButton("Close");
boolean modal = true;
final JDialog dialog = new JDialog(parent, modal);
dialog
.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
Container container = dialog.getContentPane();
container.add(closeDialogButton);
dialog.pack();
dialog.setLocationRelativeTo(parent);
closeDialogButton
.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
return dialog;
}
public static void main(String[] args) {
new DialogDemo().createApplicationFrame().setVisible(
true);
}
}
How about doing simply:
//This method is called once a user presses the "first" login button on the main GUI
public void loginPopUpThread() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
loginPopUpFrame.pack();
loginPopUpFrame.setVisible(true);
}
};
}
//This is called when the "second" loginB is pressed and the password is correct...
public void notifyPopUp() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
loginPopUpFrame.setVisible(false);
}
};
}
What you really want to be using is a modal JDialog.
Note, bits of this are left out. It's your homework/project.
public void actionPerformed(ActionEvent e)
{
// User clicked the login button
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
LoginDialog ld = new LoginDialog();
// Will block
ld.setVisible(true);
}
});
}
public class LoginDialog extends JDialog
{
public LoginDialog()
{
super((Frame)null, "Login Dialog", true);
// create buttons/labels/components, add listeners, etc
}
public void actionPerformed(ActionEvent e)
{
// user probably clicked login
// valid their info
if(validUser)
{
// This will release the modality of the JDialog and free up the rest of the app
setVisible(false);
dispose();
}
else
{
// bad user ! scold them angrily, a frowny face will do
}
}
}