Dialog box that disappear automatically - java

I am developing a application. I want when I exit it, a message box appears having message, for example, "Thanks for using Soft Attendance". Then disappear automatically say after few seconds.
I have write code for this as following:
public void windowClosing(WindowEvent e){
int whichOption;
whichOption=JOptionPane.showConfirmDialog(f1,"Are you Serious?","Soft Attendence",JOptionPane.YES_NO_OPTION);
if(whichOption==JOptionPane.YES_OPTION){
f1.dispose();
JOptionPane.showMessageDialog(null,"Thanks for using Soft Attendence");
}
}
When i click on exit button a confirmation dialog box appear and after clicking yes button
application is exited and a another message box appears.
Now I have two questions in my mind :
First question is I have dispose application already and then message box is shown. Is it fine to show message box after its parent is killed?
When second message box appears I don't want to click on "OK" button. I want it should automatically disappear. So my second question is How to shown message box that disappear automatically after some time?

Is it fine to show message box after its parent is killed?
I think this would not be a ideal case. But you can open dialog if the parentComponent has no Frame JOptionPane.showConfirmDialog(null,"...");
How to shown message box that disappear automatically after some time?
Auto disposable you can get it by a trick, you can create a SwingWorker which normally performs GUI-interaction tasks in a background thread. Set a timer and which will execute after time period and close your dialog explicitly.
class AutoDisposer extends SwingWorker<Boolean, Object> {
#Override
public String doInBackground() {
try{
JOptionPane.getRootFrame().dispose();
return Boolean.True;
}catch(Exception ex){...}
return Boolean.False;
}
}
...
new Timer(seconds * 1000, autoDisposer).start();

Related

Java Swing Dialog Window focus

In my application I have a main window and a utility popup dialog that is shown when the user clicks on a menu item. My issue is that if another program (say firefox) is opened over the java application, this obviously hides the java application. This is OK - but when the user then clicks on my java application again, only the main window is shown - the utility popup dialog is still hidden under firefox. I would like to design it such that when the user interacts with the main window in any way the utility popup dialog is also brought to the front.
I've tried adding a MouseInputListener to the main frame to bring the utility dialog to the front but this also transfers focus to it, which I don't want.
private MouseInputAdapter onWindowClick = new MouseInputAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (scheduleDialog != null)
scheduleDialog.toFront(); // the utility dialog
}
};
the utility popup dialog is still hidden
When the dialog is created you need to specify the main window as the owner of the dialog.
Then when you click on the icon for the window, the dialog will display as well.
Read the JDialog API for the proper constructor to use.

Close platform after closing a pop-up | JavaFX

So I have 2 stages, one is the main stage and the other is a pop-up screen. When the pop-up screen shows up you can close it by pressing the 'x' at the upper-left (or upper-right depending on your OS). Is there a way to close the main stage whenever you close the pop-up screen?
Stage and Popup inherit an onHidden property from Window. This is a handler that is invoked immediately after the window is hidden (by any mechanism). You can call Platform.exit() in the handler in order to exit the application:
popup.setOnHidden(event -> Platform.exit());
Note that Platform.exit() is generally preferred to System.exit(0): calling System.exit(...) will not allow the Application's stop() method to be called, so you may bypass any resource clean-up your application is performing.
There have a Event named setOnCloseRequest. If you are opening an Alert pop-up window.
Alert popup = new Alert(AlertType.INFORMATION);
Then your solution is:
alert.setOnCloseRequest(new EventHandler<DialogEvent>()
{
#Override
public void handle(DialogEvent t)
{
System.exit(0);
}
});
Else if you want to close another window with it's owner, then just use it's stage and replace DialogEvent with WindowEvent.

How to close a Java SWT window with a button?

As a newbie to Java, and many years of iOS and .NET experience, I found this to be massively confusing. What I want I thought would be very simple - I want a dialog (called from a main window) with OK and Cancel buttons. When you click OK, it does something, then dismisses the dialog. When you click Cancel, it just dismisses the dialog.
However, doing this using the SWT shell Dialog class is not obvious. How do you get a button to dismiss the dialog, and return execution back to the main Window?
Use Shell.close() rather than dispose() - so shlCheckOut.close().
Shell.close sends the SWT.Close event and then calls dispose.
With some trial-and-error and a lot of fruitless searching, I found in your button code, you have to call the .dispose() method of the dialog's shell variable. For example, my dialog is CheckOutDialog, thus I named the shell variable shlCheckOut. In the createContents() method, I put the button code as such:
...
Button btnCancel = new Button(shlCheckOut, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
shlCheckOut.dispose();
}
}
}

How do I change the value of a JOptionPane from a PropertyChangeListener without triggering the listener?

I am trying to make a program to manage a group of sports players. Each player has an enum Sport, and SportManager has convenient factory methods. What I am trying to do is open a dialog that has a JTextField for a name and a combo box to choose a sport. However, I want to stop the user from closing the dialog while the text field is blank, so I wrote a PropertyChangeListener so that when the text field is blank, it would beep to let the user know. However, if the user puts in something in the text after setting off the beep, it doesn't trigger the listener and you can't close the dialog without pressing cancel because the value is already JOptionPane.OK_OPTION, and cancel is the only way to change JOptionPane.VALUE_PROPERTY. So I tried to add
message.setValue(JOptionPane.UNITIALIZED_VALUE);
within the listener. However this just closes the window right away without giving the user a chance to fill in the text field, presumably because it triggers the listener I just registered. How do I make it so that it will beep more than once and give the user a chance to fill in the field?
FYI newPlayer is the component I'm registering the action to.
Code:
newPlayer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object[] msg = new Object [4];
msg[0] = new JLabel("Name:");
final JTextField nameField = new JTextField();
msg[1]=nameField;
msg[2] = new JLabel("Sport: ");
JComboBox<Sport> major = new JComboBox<Sport>(SportManager.getAllSports());
msg[3]=major;
final JOptionPane message = new JOptionPane();
message.setMessage(msg);
message.setMessageType(JOptionPane.PLAIN_MESSAGE);
message.setOptionType(JOptionPane.OK_CANCEL_OPTION);
final JDialog query = new JDialog(gui,"Create a new player",true);
query.setContentPane(message);
query.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
message.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (query.isVisible()&& (e.getSource() == message)&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
if(nameField.getText().equals("")&&message.getValue().equals(JOptionPane.OK_OPTION)){
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
return;
}
query.dispose();
}
}
});
query.pack();
query.setVisible(true);
if(Integer.parseInt(message.getValue().toString())==JOptionPane.OK_OPTION){
players.add(new Player(nameField.getText(),(Sport)major.getSelectedItem()));
edited=true;
}
gui.show(players);
}
});
I don't think you can do it with JOptionPane but you can using using TaskDialog framework and few others.
You can also create a dialog yourself, attach change listeners to your fields and enable/disable OK button based on content of your fields. This process is usually called "form validation"
However, I want to stop the user from closing the dialog while the
text field is blank
I get where you are going, but Java Swing is not very good at this. There is no way you can prevent the listener from being called. A solution would be to ignore the call, but this is complicated to implement.
The way I solved this issue is to let the pop-up disappear, check the returned value and if it is null/empty, beep and re-open it until user fills something.
JOptionPane does not internally support validation of inputs (Bug Reference). Your best bet is to create your own custom JDialog which supports disabling the OK button when the input data is invalid.
I'd recommend reading the bug report since other people talk about it and give workarounds.
However, I want to stop the user from closing the dialog while the text field is blank
The CustomDialog example from the section in the Swing tutorial on Stopping Automatic Dialog Closing has a working example that does this.
After taking a quick look at your code and the working example I think your code should be something like:
if (query.isVisible()
&& (e.getSource() == message)
&& (prop.equals(JOptionPane.VALUE_PROPERTY)))
{
if (message.getValue() == JOptionPane.UNINITIALIZED_VALUE)
return;
if (nameField.getText().equals("")
&& message.getValue().equals(JOptionPane.OK_OPTION))
{
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
else
query.dispose();
}
Otherwise, I'll let you compare your code with the working code to see what the difference is.
One way to solve this problem is to add a Cancel and Ok button to your dialog. Then, disable closing the popup via the X in the corner, forcing the user to click either Cancel or Ok to finish/close the dialog. Now, simply add a listener to the text field that will disable the Ok button if the text field is blank.
Judging from your code I assume you can figure out how to implement these steps, but if you have trouble let us know! Good luck!

JOptionPane won't show its dialog on top of other windows

I have problem currently for my swing reminder application, which able to minimize to tray on close. My problem here is, I need JOptionPane dialog to pop up on time according to what I set, but problem here is, when I minimize it, the dialog will pop up, but not in the top of windows when other application like explorer, firefox is running, anyone know how to pop up the dialog box on top of windows no matter what application is running?
Create an empty respectively dummy JFrame, set it always on top and use it as the component for the JOptionPane instead of null. So the JOptionPane remains always on top over all other windows of an application. You can also determine where the JOptionPane appears on screen with the location of the dummy JFrame.
JFrame frmOpt; //dummy JFrame
private void question() {
if (frmOpt == null) {
frmOpt = new JFrame();
}
frmOpt.setVisible(true);
frmOpt.setLocation(100, 100);
frmOpt.setAlwaysOnTop(true);
String[] options = {"delete", "hide", "break"};
int response = JOptionPane.showOptionDialog(frmOpt, msg, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, "delete");
if (response == JOptionPane.YES_OPTION) {
removeRow();
}
frmOpt.dispose();
}
Old post, but I was struggling with this.
My problem was more with Javafx allowing the JOptionPane to go behind the current Java window.
Therefore I used the following which does what the original poster asked by putting the JOptionPane in front of all windows; even JAVAFX.
Firstly the old JOptionPane:
JOptionPane.showMessageDialog(null, "Here I am");
Now an JOptionPane that stays in front:
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, "Here I am");
And for fun here is everything in one long line:
JOptionPane.showMessageDialog(
((Supplier<JDialog>) () -> {final JDialog dialog = new JDialog(); dialog.setAlwaysOnTop(true); return dialog;}).get()
, "Here I am");
You can make a static method some where that will return the JDialog for you and then just call it in the JOptionPane to clean up your code a bit.
Are you using one of the canned JOptionPanes? (Like JOptionPane.showCOnfirmDialog(...))
You may want to look at extending JDialog and making your own dialog panel, and then calling myDialog.setAlwaysOnTop(true);
Windows is blocking this operation since XP.
The scenario before was like:
Your a tiping in some text in an editor and not recognize that another dialog is coming to front when you are tipping the text. The coming dialog gets the focus and you are tiping in the new dialog. Maybe you click enter after you are ready and do this in the wrong dialog, which is asking whether you realy want to delet your hard disk ;)
The come to front call in java is only working for java windows.
The possibibilty to notify the user of a new window is to implement a Frame, which will highlighted/flashing in the windows task bar.
Correction the post above..
I have resolve my problem as below:
this.setVisible(true); // show main frame
MyDialog dialog = New MyDialog(this, true); // show my custom dialog
dialog.setVisible(true);
this.setVisible(false);
it works fine for me :)
You might think about using a JFrame instead. It may give you a little more flexibility.
If you are using a JFrame and you want it to popup on top of the other windows use:
myFrame.setVisible(true);
myFrame.setState(Frame.NORMAL);
The setState will show the window to the user if it was in minimized state previously.

Categories

Resources