Figure out when a button is pressed in another window - java

I run my main window in the main method like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NoteSystem MainWindow = new NoteSystem();
MainWindow.initUI();
}
});
And then when a button is pressed on this form, I create a window by instantiating a class I made. I'm having trouble detecting when the second form is closed and what the textboxes/other controls contained.
What is the proper way to:
a) Fire an event in NoteSystem when the second window is closed
b) allow NoteSystem to check all the components/controls in the second window
I considered using a JOptionPane, but I'd like to create the window entirely in my own class. The idea of having the main window frozen while waiting for response from the second window works for my application though, so if I could use JOptionPane with my own class, that would be ideal.
Thanks

The best way is to use a modal dialog, a window like a JFrame, but that halts program flow in the calling code until it is no longer visible. This way, the calling code will know exactly when the dialog window has been dealt with, since its code flow will resume once again, and so often the calling code will extract information from the dialog window code at that point. A JOptionPane is one type of these, and so is a modeal JDialog (of which a JOptionPane is a sub-type). Either of these can display as complex a GUI as any that is displayed within a JFrame, so don't sell them short. You'll notice that the second parameter of most JOptionPane methods is of type Object, meaning anything can go in there, but most often you'll pass in either a String for a simple JOptionPane, or a JPanel that can be chock full of components and other nested JPanels, and in this way the JOptionPane can display the complex GUI if need be.
For examples, please see:
Passing values between JFrames
action listener to JDialog for clicked button
trouble obtaining variable info from another JFrame
How do you return a value from a java swing window closes from a button?

Related

JFrame that waits for User Input [duplicate]

In a JFrame, when I click on 'login', I pop up another Jframe which is the login window.
How do I make my main Jframe wait for my login Jframe to exit, before doing anything else?
Just use a modal dialog in stead of a frame, that way you cannot do anything else until it'is closed
see http://mindprod.com/jgloss/modal.html for explanation
and see http://www.java2s.com/Tutorial/Java/0240__Swing/ASimpleModalDialog.htm for code example
If you insist on using a JFrame, you could use a workaround by cover the other frame by a glassframe.. Not too a nice solution, I admit..
I agree that a modal dialog would be the best option here, but if I were to answer this question in it's more general form, say:
How do I make one JFrame wait for another JFrame?
I would say the easiest way to acheive this is by registering and firing event listeners.
In your "child" frame, register the "main" frame as an event listener.
In your "main" frame,
implement your choice of listener, e.g. ActionListener
in the method called by the listener, e.g. actionPerformed, code the logic that handles what happens upon each of the actions it can respond to in the "child" frame.
One can easily implement this to a ny number of situations, including the login scenario described in the question.
Use JModalFrame instead of JFrame.

Open java Applet or Frame inside a parent Applet method and wait for input

I have a Java applet (lets call it parentApplet) with a public method which must return information regarding the status of the performed actions (let's call it getUserInput()) . This method opens another Applet which needs user button input, by adding it as a child with add(childApplet), and afterwards adding itself (the parent) as an ActionListner of the buttons in the childApplet, being able to run other methods when the user clicks on the buttons in the childApplet.
My question is, how can I halt getUserInput() execution until the user has clicked the childApplet buttons?
I tried to have a static variable that tracks the return information, and spinning on a while(var == null) Thread.Sleep(1000); but it blocks the main thread, as it should.
PS: Having the childApplet as an applet can be changed to anything that could better fulfil the requirement of opening another panel on top of the parent applet.
Details on getUserInput()
That childApplet has a canvas (a Graphics object from a BufferedImage) on which the user can draw and OK/Clear/Cancel buttons. When the user presses OK, I need to get the BufferedImage drawn. Do you know if this can be accomplished by extending a JDialog?
You really need to restructure your app. You can't do it the way you want.
Try creating a JDialog set it up as you like with input fields and an OK/Cancel button.
Then to show the dialog do:
MyDialog dialog = new MyDialog(null, true); //true = modal
//dialog.setModalityType(ModalityType.DOCUMENT_MODAL); //or specify modal here
dialog.setVisible(true); //waits until dialog is closed
if (dialog.wasAccepted()) {
//grab values from dialog
dialog.getCanvas();
}
In the dialog you would have:
private boolean accepted = false;
public boolean wasAccepted() {return accepted;}
public Canvas getCanvas() {return canvas;}
public ? getWhateverElseYouWant() {return ...;}
The OK button would:
accepted=true;
dispose();
The Cancel button would:
accepted=false;
dispose();
The JDialog will pump events while it's visible. So the setVisible() function will halt execution until the dialog is closed.
That should work better, and then you can return many user input fields.
You can even change the JDialog constructor to pass default value(s) in.
That childApplet has a canvas (a Graphics object from a BufferedImage) on which the user can draw and ok/clear/cancel buttons. When the user presses OK, I need to get the BufferedImage drawn.
First of all, it should not be an applet but a JPanel (it is not impossible to do it as an applet, but also not trivial). Then you can show the JPanel in a one of three ways.
JOptionPane.showMessageDialog(..). The idea would be to use the ready made OK/Cancel buttons of the option pane to tell the main app. whether to actually use image drawn. I (as a user) would tend to expect the Clear button to not be in the group of buttons that dismisses the dialog. Put that button in the panel you pass to the option pane.
A modal JDialog. Creating a dialog is more work than using an option pane, but also more versatile. For instance, if the panel you put into the dialog has a 'set size of drawing' option, it is easier to resize a dialog than an option pane.
Another card of a CardLayout. The two previous suggestions have the dis/advantage that they will block the app. and the browser until dismissed. This is good in that you can simply query the state of the drawing immediately after it is shown, confident that the user has finished drawing. But it is bad in that the user might have the dialog or option pane sitting on screen for 30 minutes, and the rest of the browser will be inaccessible to them in that time. By instead flipping to a card that shows the drawing panel, the browser is not blocked, and the app. can query the state of the drawing as soon as the user makes one of the OK/Cancel selections.

Exiting out of one of two JFrame exits out of both

I have two seperate JFrames but when i click the X in the topright of one, it will exit out of the other also. I have an "exit" button near the bottom to do setVisible(false), but i still have the tendency to use the x button. How would i make it so that it doesnt cancel out of the entire project?
Also, how would i make it so that the second JFrame locks out of the other JFrame untill the second JFrame is closed, like how a popup message works
Don't give your GUI two JFrames. The GUI ideally should have only one GUI. If a separate window is required, then make it a dialog such as a JDialog, and this won't happen.
Also, how would i make it so that the second JFrame locks out of the other JFrame untill the second JFrame is closed, like how a popup message works
You are perfectly describing the behavior of a modal JDialog or JOptionPane. Just use 'em.
Later we'll chat about using CardLayouts to swap views in a single GUI.
Edit, you state:
Im using Netbeans form editor to create them faster but I only see JFrame and JPanel. Can I edit them in Netbeans? I'd rather not do them through scratch Java
You've touched on another zealous belief of mine, that this is yet another reason not to use a code generator when learning a library as one can get too tied into the code generator, that it prevents one from learning the library. I strongly advise you to put aside your code-generation tool and create by hand, referring to the tutorials and API. Then later when you get more familiar with the library, sure use the tool. By the way, an answer to your direct question here is to gear your GUI's to create JPanels, and then use these JPanels where and how you want them -- in JFrames, or JDialogs, or JOptionPanes, or swapped in CardLayouts, or JTabbedPanes or nested in other JPanels,... etc...
You should be using a modal JDialog, not a second JFrame, because JDialogs provide certain functionality such as not adding another window bar to the taskbar, and automatically setting focus when the parent JFrame receives focus. Modal JDialogs prevent user input to the JFrame while it's open, useful for an "Are you sure you want to exit?" dialog, for example.
As for one JFrame exiting the other, you probably have their default close operation set to EXIT_ON_CLOSE. If you do this:
jframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
jframe.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
handleUserWantsToCloseWindow();
}
});
Then you can control what happens when the user wants to close, such as popping up a "Save Changes?" modal JDialog or "Are you sure you want to quit?" modal JDialog. Note that you have to manually dispose of the JFrame if you use this method.

JButton needs to be clicked twice after JDialog

I've been struggling with some problem while creating my app based on Swing. I have a main JFrame which consists of:
JMenu
JPanel containing a JButton and a JLabel
JButton is linked with ActionListener. Clicking JMenu (MenuListener) brings up a JDialog with some form. The problem is, when the JDialog is closed (it doesn't make difference whether I do it with dispose() or rather showVisible(false)) I need to click the JButton two times before it triggers for the first time. From now it normally works with one click.
Every time the JDialog is in front, the problem appears.
PS. The JDialog is set to be modal, with JFrame as parent.
It sounds like a focus issue.
The first click restores focus to the app and the second clicks the button. Typically, I have seen this when the JDialog has the wrong parent and focus can not be returned.
Thank you for your answers.
I have considered posting some code, but it involves 4 classes so will be quite long.
I have also tried things with focus before, but nothing helped. What is interesting: if I display the JDialog by new myDialog.showVisible(true) it behaves like I've described. But if I use construction like this:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JDialog.setVisible(true);
}
});
it closes normally and parent frame doesn't need to be clicked before responding, but on the other hand the displayed Dialog needs so. Additonally, what I do not understand, after opening the Dialog cursor is placed in the text field and I can write normally, but to click some button on it I must click once on the Dialog, only second and next clicks behave like I want to.
PS. Closing the dialog like in the second included example changes nothing.

How can I make a Swing text area have the focus as soon as it is loaded?

I've created a simple Swing panel that, when loaded, takes up my application's entire window. It contains two JTextAreas and a handful of buttons. I want one of the text areas to have the focus when the panel loads, so that the user can immediately start typing instead of having to click on the text area first. How can I achieve this?
By default focus goes to the first component defined on the window.
If this is not the component you want to have focus then you need to request focus once the window is realized.
The Dialog Focus example shows a couple of ways to do this.
See here the Documentation which contains exactlly what you are searching for (I think):
A component can also be given the
focus programmatically, such as when
its containing frame or dialog-box is
made visible. This code snippet shows
how to give a particular component the
focus every time the window gains the
focus:
//Make textField get the focus whenever frame is activated.
frame.addWindowFocusListener(new WindowAdapter() {
public void windowGainedFocus(WindowEvent e) {
textField.requestFocusInWindow();
}
});
You just need to call requestFocus method of Jcomponent class,
public void requestFocus()
On the Component that you want to focus.
And pleas make sure that you call this method after setVisible is called for its parent component.
For example:-
You have a Jframe in which you added a JTextArea, so after calling you should call in following order:-
jframe.setVisible(true);
jarea.requestFocus();

Categories