I am buliding an NetBeans Platform application. When the user clicks on the X of the main window I want the application to do nothing and show a password JDialog. If the password is correct close the app, else do not close the app. How do I do this? I've created a Listener class that will show the password JDialog, but how do I stop the application from closing? Similar to JFrame's setDefaultCloseOperation, and setting it to do nothing on close.
public class Listener extends WindowAdapter {
private Frame frame;
#Override
public void windowActivated(WindowEvent event) {
frame = WindowManager.getDefault().getMainWindow();
frame.setSize(946, 768);
}
#Override
public void windowClosing(WindowEvent event) {
ShutDownMainWindowJDialog shutDownMainWindowJDialog;
shutDownMainWindowJDialog = new ShutDownMainWindowJDialog(null, true);
shutDownMainWindowJDialog.exeShutDownMainWindowJDialog();
shutDownMainWindowJDialog.setLocationRelativeTo(frame);
shutDownMainWindowJDialog.setVisible(true);
}
}
public class Installer extends ModuleInstall {
#Override
public void restored() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame frame = WindowManager.getDefault().getMainWindow();
frame.addWindowListener(new Listener());
}
});
}
}
It is easy. So create module with installer and overwrite method closing (may by), then show your dialog and return false (not close app). Jirka
So this is conclusion:
add to your module installer/activator
package master;
import org.openide.modules.ModuleInstall;
/**
* Manages a module's lifecycle. Remember that an installer is optional and
* often not needed at all.
*/
public class Installer extends ModuleInstall {
#Override
public void close() {
//your module shutdown
}
#Override
public boolean closing() {
// this is place for your Dialog() and return:
//
// true if you want to enable close the app
// other return false
/*
if you force shutdown app try LifecycleManager.getDefault().exit();
System.exit(0) is very dummy, because it does not respect betweenmodule dependencyis
}
}
Jirka
In your windowClosing() get the password from the user and dispose() the frame if it is correct.
public class PasswordToClose extends WindowAdapter {
private JFrame frame;
public PasswordToClose(JFrame frame) {
this.frame = frame;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Password to close");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new PasswordToClose(frame));
frame.setSize(200, 200);
frame.setVisible(true);
}
#Override
public void windowClosing(WindowEvent evt) {
String password = JOptionPane.showInputDialog(frame, "Enter password");
if ("secret".equals(password)) {
frame.dispose();
}
}
}
Related
I have a simple JFrame that asks a user for a confirmation to exit when they click X to close the window, this works fine. I also wanted the user to be presented with the same option if they also pressed the escape key (ESC), unfortunately it seems to be trapped in a state where the escape key seems to be constantly pressed when it is not. Where is the mistake and why?
public class Zz extends javax.swing.JFrame implements Events {
boolean exitAttempt = false;
java.awt.event.WindowEvent closeEvent;
//public Zz() {}
public static void main(java.lang.String[] args) {
Zz zz = new Zz();
zz.dostuff();
}
public void dostuff() {
setSize(800, 600);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(javax.swing.JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent we) {
exitAttempt = true;
}
});
closeEvent = new java.awt.event.WindowEvent(
this, java.awt.event.WindowEvent.WINDOW_CLOSING);
setVisible(true);
java.awt.Canvas canvas = new java.awt.Canvas();
canvas.setPreferredSize(new java.awt.Dimension(800, 600));
add(canvas);
Keys keys = new Keys();
addKeyListener(keys);
pack();
while (true) {
events(keys);
if (exitAttempt) {
if (javax.swing.JOptionPane.YES_OPTION ==
showConfirmDialog("Do you want to Exit ?",
"Confirmation:", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.QUESTION_MESSAGE, null)) {
exit();
break; //while loop
}
exitAttempt = false;
}
}
dispose();
}
public void triggerCloseEvent() {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
dispatchEvent(closeEvent);
}
});
}
public int showConfirmDialog(java.lang.Object message,
java.lang.String title, int optionType, int messageType,
javax.swing.Icon icon) {
return javax.swing.JOptionPane.showConfirmDialog(
this, message, title, optionType, messageType, icon);
}
public boolean exit() {
setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
return true;
}
public void events(Keys keys) {
System.out.println((keys.getPressed())[java.awt.event.KeyEvent.VK_ESCAPE]);
if ((keys.getPressed())[java.awt.event.KeyEvent.VK_ESCAPE]) {
triggerCloseEvent();
}
}
}
interface Events {
public void events(Keys keys);
}
class Keys implements java.awt.event.KeyListener {
private final boolean[] pressed;
public Keys() {
pressed = new boolean[256];
}
public void keyTyped(java.awt.event.KeyEvent event) {}
public void keyPressed(java.awt.event.KeyEvent event) {
pressed[event.getKeyCode()] = true;
}
public void keyReleased(java.awt.event.KeyEvent event) {
pressed[event.getKeyCode()] = false;
}
public boolean[] getPressed() {
return pressed;
}
}
I have a simple JFrame that asks a user for a confirmation to exit when they click X to close the window, this works fine
Your design is incorrect.
You should NOT have a while (true) loop.
GUI's are event driven. You create the frame and make it visible. That is the end of the code in your main() method or constructor. The GUI will then sit there forever doing nothing.
However, eventually, the user will then generate events that the GUI responds to.
This means that the code to display the JOptionPane should be moved to the windowClosing() method of your WindowListener.
See: Closing an Application for some basics and helpful classes to use.
I also wanted the user to be presented with the same option if they also pressed the escape key
Don't use a KeyListener.
Swing was designed to be used with Key Bindings.
You can use the ExitAction contained in the Closing an Application link when creating your key bindings:
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
InputMap im = frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(escapeKeyStroke, "escape");
frame.getRootPane().getActionMap().put("escape", new ExitAction());
Read the Swing tutorial. There are section on :
How to Uuse Key Bindings
How to Use Actions
to help explain how the above suggestions work.
The tutorial examples will also show you how to better structure your code and note that the never use a while (true) loop.
I am a beginner and not so familar with Java yet, so the solution to this might be simple.
I have one MainClass that includes the main method. This MainClass creates a JFrame which can have various JPanels inside. I have one class called CommandInput which creates a JPanel containing a JTextArea. Now I want that when the user closes the JFrame of the MainClass that it asks if he wants to save the changes. As the JPanels inside the JFrame vary I do not really want to include this in the MainClass. I know that it is possible for every "SubClass" like the CommandInput to add a windowListener to the JFrame of the MainClass but that does not really seems efficient to me:
public class CommandInput {
public CommandInput(JFrame mainFrame) {
mainFrame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override //Overwrites the normal behavior of this method
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.out.println("Closing Event triggered and detected by CommandInput object");
}
});
}
}
Should I maybe rather have one WindowAdapter in the MainClass and add this code to its windowClosing method? And if so how would I do that?
I now solved it in a way that each SubClass adds an anonymous inner class of an interface containing a method that returns if the JFrame can be closed to a list. Only if all of the anonymous inner classes in the list return true the JFrame closes:
public interface ClosingListener {
public boolean allowClosing();
}
public MainClass {
private ArrayList<ClosingListener> closingListeners = new ArrayList<ClosingListener>();
public MainClass() {
JFrame frame = new JFrame();
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
boolean canClose = true;
for (ClosingListener closingListener : closingListeners) {
if (!closingListener.allowClosing()) {
canClose = false;
break;
}
}
if (canClose) {
System.exit(0);
}
}
});
}
public void addClosingListener(ClosingListener closingListener) {
closingListeners.add(closingListener);
}
}
May be you need this
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
int choice = JOptionPane.showConfirmDialog(null, "Save changes?");
if(choice==0) System.exit(0);
}
});
I want my GUI to make some checks when a JOptionPane appears.
Because I can't find any other way, I though I can do those each time the application window loses focus(its just checking a string). For that reason I added the following code on my JFrame:
appFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Focus Lost");
}
#Override
public void windowClosing(WindowEvent e) {
//some other stuff here that work
}
});
The window closing listener works fine. Although when the JFrame isn't focused nothing happens. Shouldn't "Focus Lost" be printed each time I switch from JFrame to some other window? Also, will this method be triggered when a JOptionPane is shown?
The key to me is that you want a change in the GUI triggered by a change of a String variable. The best way I see to solve this is to make the String variable a bound property by using PropertyChangeListenerSupport. This way you can have the GUI attach a PropertyChangeListener to the class that holds the String variable and then be notified when it changes allowing you to update the GUI appropriately.
If you go this route, consider giving the observed class a SwingPropertyChangeSupport field so that the listeners will be notified on the Swing event thread and hopefully avoid any Swing concurrency issues.
Here's a brief example:
import java.awt.Dimension;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
public class ShowPropertyChangeSupport {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final MainGUI mainGui = new MainGUI("Title");
final ObservedClass observedClass = new ObservedClass();
observedClass.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getPropertyName().equals(ObservedClass.BOUND_PROPERTY)) {
mainGui.setTitle(pcEvt.getNewValue().toString());
}
}
});
mainGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainGui.pack();
mainGui.setLocationRelativeTo(null);
mainGui.setVisible(true);
int timerDelay = 6000; // every 6 seconds
new Timer(timerDelay, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String result = JOptionPane.showInputDialog(mainGui,
"Please enter a String", "Set GUI title", JOptionPane.PLAIN_MESSAGE);
if (result != null) {
observedClass.setBoundProperty(result);
}
}
}){{setInitialDelay(1000);}}.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// ** note that I don't like extending JFrame,
// but will do this for sake of example simplicity
class MainGUI extends JFrame {
public MainGUI(String title) {
super(title);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
}
class ObservedClass {
public static final String BOUND_PROPERTY = "bound property";
private String boundProperty = "";
private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
this);
public SwingPropertyChangeSupport getSpcSupport() {
return spcSupport;
}
public void setSpcSupport(SwingPropertyChangeSupport spcSupport) {
this.spcSupport = spcSupport;
}
public String getBoundProperty() {
return boundProperty;
}
public void setBoundProperty(String boundProperty) {
String oldValue = this.boundProperty;
String newValue = boundProperty;
this.boundProperty = newValue;
spcSupport.firePropertyChange(BOUND_PROPERTY, oldValue, newValue);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
spcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
spcSupport.removePropertyChangeListener(listener);
}
}
The key to all this in my mind is to use the listener so that the class with the bound property -- the String being listened to -- has no knowledge of the GUI, the listener, and the GUI, likewise has no knowledge of the class with the bound property. They are fully decoupled.
I'm not going to go into why you are doing what you are doing, but it is not working as you expect for the following reason:
WindowAdapter is a convenience class so you can create one listener and register it for multiple types of events. You have only registered it for one set of events, you need to also register it for focus events via: Window.addWindowFocusListener()
WindowAdapter adapter = new WindowAdapter() {
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Focus Lost");
}
#Override
public void windowClosing(WindowEvent e) {
//some other stuff here that work
}
};
appFrame.addWindowListener(adapter);
appFrame.addWindowFocusListener(adapter);
1) JOptionPane / modal JDialog have got modality issue, but modality could be advantage if all containers have got own owner, for real workaround you need to know (I'll talking about how can I do test that)
numbers of Window[], and if isDisplayable(), then you can use follows
you can get SwingUtilities#getAccessibleIndexInXxx can returns AccessibleState
KeyboardFocusManager (very interesting methods for multi-touch) returns getXxxFocusXxx methods
Focus, FocusSubsystem is pretty asynchronous,
2) Please, with due respect, I don't know why you needed that, for why reasons I need to know about that, there is about business rules, you always need to know ...., and if is done on EDT
Focus, FocusSubsystem is pretty asynchronous,
I'm working in Java to create an internal tool. The two consists of two JPanels which are anticipated to run on two separate screens. I want to be able to click a JButton which is part of JFrame A which will send a keyboard action to JFrame B.
Unfortunately I can't seem to do this because JFrame B doesn't have the focus and I can't use any of the request Focus methods because JFrame B is not a child of the Focus Window (JFrame A is).
So how can I either give JFrame B focus despite it not being a child of the Focus Window or send Keyboard Events to JFrame B that it will respond to without having focus?
is so hard to manage Focus between two JFrames, better would be create only one JFrame and other Top-level Containers would be JDialogs, create one/two JDialog(s) and reuse that by removing all JComponents
basicaly it would be :
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
someComponent.grabFocus();
someComponent.requestFocus();//or inWindow depends if Swing or Awt
}
});
but between two JFrames is things little bit complicated, just basic and uncompleted example (based on code from old.good.sun.forums.com)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PMDialog extends JDialog {
private static final long serialVersionUID = 1L;
private boolean modal = false;
private WindowAdapter parentWindowListener;
private Window owner;
private JFrame blockedFrame = new JFrame("Blocked Frame");
private JFrame noBlockedFrame = new JFrame("No Blocked Frame");
public PMDialog() {
noBlockedFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
noBlockedFrame.getContentPane().add(new JButton(new AbstractAction("Test button") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Non blocked button pushed");
/*if (blockedFrame.isVisible()) {
noBlockedFrame.setVisible(false);
} else {
blockedFrame.setVisible(true);
}*/
noBlockedFrame.setVisible(true);
blockedFrame.setVisible(true);
}
}));
noBlockedFrame.setSize(200, 200);
noBlockedFrame.setVisible(true);
blockedFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
blockedFrame.getContentPane().add(new JButton(new AbstractAction("Test Button") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent evt) {
final PMDialog pmd = new PMDialog(blockedFrame, "Partial Modal Dialog", true);
pmd.setSize(200, 100);
pmd.setLocationRelativeTo(blockedFrame);
pmd.getContentPane().add(new JButton(new AbstractAction("Test button") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Blocked button pushed");
pmd.setVisible(false);
blockedFrame.setVisible(false);
noBlockedFrame.setVisible(true);
}
}));
pmd.setDefaultCloseOperation(PMDialog.DISPOSE_ON_CLOSE);
pmd.setVisible(true);
System.out.println("Returned from Dialog");
}
}));
blockedFrame.setSize(200, 200);
blockedFrame.setLocation(300, 0);
blockedFrame.setVisible(false);
}
public PMDialog(JDialog parent, String title, boolean isModal) {
super(parent, title, false);
initDialog(parent, title, isModal);
}
public PMDialog(JFrame parent, String title, boolean isModal) {
super(parent, title, false);
initDialog(parent, title, isModal);
}
private void initDialog(Window parent, String title, boolean isModal) {
owner = parent;
modal = isModal;
parentWindowListener = new WindowAdapter() {
#Override
public void windowActivated(WindowEvent e) {
if (isVisible()) {
System.out.println("Dialog.getFocusBack()");
getFocusBack();
}
}
};
}
private void getFocusBack() {
Toolkit.getDefaultToolkit().beep();
super.setVisible(false);
super.pack();
super.setLocationRelativeTo(owner);
super.setVisible(true);
super.toFront();
}
#Override
public void dispose() {
owner.setEnabled(true);
owner.setFocusableWindowState(true);
super.dispose();
}
#Override
#SuppressWarnings("deprecation")
public void hide() {
owner.setEnabled(true);
owner.setFocusableWindowState(true);
super.hide();
}
#Override
public void setVisible(boolean visible) {
boolean blockParent = (visible && modal);
owner.setEnabled(!blockParent);
owner.setFocusableWindowState(!blockParent);
super.setVisible(visible);
if (blockParent) {
System.out.println("Adding listener to parent ...");
owner.addWindowListener(parentWindowListener);
try {
if (SwingUtilities.isEventDispatchThread()) {
System.out.println("EventDispatchThread");
EventQueue theQueue = getToolkit().getSystemEventQueue();
while (isVisible()) {
AWTEvent event = theQueue.getNextEvent();
Object src = event.getSource();
if (event instanceof ActiveEvent) {
((ActiveEvent) event).dispatch();
} else if (src instanceof Component) {
((Component) src).dispatchEvent(event);
}
}
} else {
System.out.println("OUTSIDE EventDispatchThread");
synchronized (getTreeLock()) {
while (isVisible()) {
try {
getTreeLock().wait();
} catch (InterruptedException e) {
break;
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Error from EDT ... : " + ex);
}
} else {
System.out.println("Removing listener from parent ...");
owner.removeWindowListener(parentWindowListener);
owner.setEnabled(true);
owner.setFocusableWindowState(true);
}
}
#Override
public void setModal(boolean modal) {
this.modal = modal;
}
public static void main(String args[]) {
PMDialog pMDialog = new PMDialog();
}
}
EDIT: for How to adds Focus to the JDialog is there excelent Woodoo by camickr Dialog Focus but AncestorListener isn't my cup of Java and too much abstract for me
Is this a Swing GUI (you don't mention or add a tag to a gui library)? If so, consider using Key Bindings which can be more flexible about focus compared with KeyListeners.
Nothing says you can't have one Action send a message to another. In this example, Enter also needs to Clear, so it forwards the ActionEvent. Note also that each NumberButton binds two keystrokes to Click. In your case, you may have to to remove an existing binding and perhaps call toFront() on the other window. Note the caveats that lend support to #mKorbel's answer.
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
}
}
}