With this,
JOptionPane.showInputDialog(null,"Enter Your Name");
I'd like the user input dialog box to auto exit. I mean within 2 or 3 seconds only show that JOptionPane user input dialog and close after that. It should automatically close that input dialog box only, not the whole program. The System.exit(0) method causes the full program to exit, but I want only close that input dialog box not full program. Then I want only Swing input dialog not message box and confirm box.
As shown in How to Make Dialogs, you can add intercept Automatic Dialog Closing in a PropertyChangeListener. Based on this example, the variation below adds a label, prompt, and text field to the option pane. A Swing Timer counts down from TIME_OUT, updating the label each time. The PropertyChangeListener dispatches a WINDOW_CLOSING event when the OK button is pressed or time runs out.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.Timer;
/**
* #see https://stackoverflow.com/a/44417958/230513
* #see https://stackoverflow.com/a/12451673/230513
*/
public class JOptionTimeTest implements ActionListener, PropertyChangeListener {
private static final int TIME_OUT = 10;
private int count = TIME_OUT;
private final Timer timer = new Timer(1000, this);
private final JDialog dialog = new JDialog();
private final JOptionPane optPane = new JOptionPane();
private final JLabel label = new JLabel(message());
private final JLabel prompt = new JLabel("Enter Your Name:");
private final JTextField text = new JTextField("Name");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new JOptionTimeTest().createGUI();
}
});
}
private void createGUI() {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
timer.setCoalesce(false);
text.selectAll();
Object[] array = {label, prompt, text};
optPane.setMessage(array);
optPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
optPane.setOptionType(JOptionPane.DEFAULT_OPTION);
optPane.addPropertyChangeListener(this);
dialog.add(optPane);
dialog.pack();
frame.add(new JLabel(frame.getTitle(), JLabel.CENTER));
frame.pack();
frame.setVisible(true);
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
timer.start();
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (JOptionPane.VALUE_PROPERTY.equals(prop)) {
thatsAllFolks();
}
}
public void actionPerformed(ActionEvent e) {
count--;
label.setText(message());
if (count == 0) {
thatsAllFolks();
}
timer.restart();
}
private String message() {
return "Closing in " + count + " seconds.";
}
private void thatsAllFolks() {
dialog.setVisible(false);
dialog.dispatchEvent(new WindowEvent(
dialog, WindowEvent.WINDOW_CLOSING));
}
}
Related
I have discovered class javax.swing.Popup. I wrote code to test its behavior. Code is shown below. When I run the code, after the JFrame is displayed, I click the SHOW button and the Popup is displayed. After that I click the HIDE button and the Popup disappears. But then if I click the SHOW button again, nothing happens. The Popup only appears after clicking the SHOW button for the first time. Also, if I click the HIDE button first, before clicking the SHOW button, then when I click the SHOW button, the Popup does not appear.
Am I missing something?
Am I doing something wrong?
I admit I haven't investigated this behavior. I haven't searched the Internet and I haven't looked at the code for class Popup nor PopupFactory, simply due to laziness and in the hope that someone can explain it to me.
Here is my MCVE.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class PopupTest implements ActionListener, Runnable {
private static final String HIDE = "HIDE";
private static final String SHOW = "SHOW";
private Popup popup;
public void actionPerformed(ActionEvent actionEvent) {
String actionCommand = actionEvent.getActionCommand();
switch (actionCommand) {
case HIDE:
popup.hide();
break;
case SHOW:
popup.show();
break;
}
}
public void run() {
showGui();
}
private void showGui() {
JFrame frame = new JFrame("Popup");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JLabel centerLabel = new JLabel("CENTER LABEL", SwingConstants.CENTER);
frame.add(centerLabel, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
JButton showButton = new JButton(SHOW);
showButton.addActionListener(this);
buttonsPanel.add(showButton);
JButton hideButton = new JButton(HIDE);
hideButton.addActionListener(this);
buttonsPanel.add(hideButton);
frame.add(buttonsPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
JLabel popupLabel = new JLabel("Popup_Label");
PopupFactory factory = PopupFactory.getSharedInstance();
Point pt = centerLabel.getLocationOnScreen();
int x = pt.x + 10;
int y = pt.y - 10;
popup = factory.getPopup(centerLabel, popupLabel, x, y);
}
public static void main(String[] args) {
PopupTest instance = new PopupTest();
EventQueue.invokeLater(instance);
}
}
https://docs.oracle.com/javase/7/docs/api/javax/swing/Popup.html#hide()
The documentation that you have chosen not to read is very clear that hide() disposes of the Popup and any further method calls on that Popup will result in indeterminate behaviour.
You must create a new Popup instance each time.
From the docs for hide():
"Hides and disposes of the Popup. Once a Popup has been disposed you
should no longer invoke methods on it. A disposed Popup may be
reclaimed and later used based on the PopupFactory."
As such, here is a quick and dirty modified version that works.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class PopupTest implements ActionListener, Runnable {
private static final String HIDE = "HIDE";
private static final String SHOW = "SHOW";
private Popup popup;
private JLabel centerLabel;
private JLabel popupLabel = new JLabel("Popup_Label");
private PopupFactory factory = PopupFactory.getSharedInstance();
public void actionPerformed(ActionEvent actionEvent) {
String actionCommand = actionEvent.getActionCommand();
switch (actionCommand) {
case HIDE:
if (popup == null) {
return;
}
popup.hide();
popup = null; // necessary to avoid using the disposed popup
break;
case SHOW:
if (popup != null) { // it's already showing
return;
}
Point pt = centerLabel.getLocationOnScreen();
int x = pt.x + 10;
int y = pt.y - 10;
popup = factory.getPopup(centerLabel, popupLabel, x, y);
popup.show();
break;
}
}
public void run() {
showGui();
}
private void showGui() {
JFrame frame = new JFrame("Popup");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
centerLabel = new JLabel("CENTER LABEL", SwingConstants.CENTER);
frame.add(centerLabel, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
JButton showButton = new JButton(SHOW);
showButton.addActionListener(this);
buttonsPanel.add(showButton);
JButton hideButton = new JButton(HIDE);
hideButton.addActionListener(this);
buttonsPanel.add(hideButton);
frame.add(buttonsPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
PopupTest instance = new PopupTest();
EventQueue.invokeLater(instance);
}
}
In my ActionListener class I have my if statements prompting the user to enter a string. When I try to execute the program, nothing happens. Before I added the JButton, the spelling game would appear in a small window and text could be entered, and a message displayed whether the correct spelling was given.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class spelling extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frame = new JFrame();
JButton button1;
public spelling() {
super("Question 1");
setLayout(new FlowLayout());
button1 = new JButton("Spelling game");
add(button1);
HandlerClass handler = new HandlerClass();
button1.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JFrame frame2 = new JFrame();
String answer1 = JOptionPane.showInputDialog("recipracate, reciprocate, reciprokate");
if (answer1.equals("reciprocate")) {
JOptionPane.showMessageDialog(frame2, "recriprocate is the correct answer");
}
else {
JOptionPane.showMessageDialog(frame2, "is the wrong answer");
}
String answer2 = JOptionPane.showInputDialog("quintessence, quintessance, qwintessence");
if (answer2.equals("quintessence")) {
JOptionPane.showMessageDialog(frame2, "quintessence is the correct answer");
}
else {
JOptionPane.showMessageDialog(frame2, "That is the wrong answer");
}
}
}
}
import javax.swing.JFrame;
public class spellingmain {
public static void main(String[] args) {
spelling test = new spelling();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(300, 150);
test.setVisible(true);
}
}
Your complete example raises several issues that merit consideration going forward:
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
To avoid a NullPointerException, a common practice is to invoke the equals() method on the constant, which is known to be non-null.
"reciprocate".equals(answer1)
Make your error dialog easier to read by including relevant text.
answer1 + " is the wrong answer"
Don't extend JFrame unless you are adding new functionality.
Don't open a new frame needlessly; you can use the existing frame; a message dialog may have a parentComponent, but one is not required.
Test your program by clicking Cancel on a question to see the result. Consider how you intend to handle this.
Code as tested:
import java.awt.FlowLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class Spelling extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frame = new JFrame();
JButton button1;
public Spelling() {
super("Questionss");
setLayout(new FlowLayout());
button1 = new JButton("Spelling game");
add(button1);
HandlerClass handler = new HandlerClass();
button1.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
String answer1 = JOptionPane.showInputDialog("recipracate, reciprocate, reciprokate");
if ("reciprocate".equals(answer1)) {
JOptionPane.showMessageDialog(null, "recriprocate is the correct answer");
}
else {
JOptionPane.showMessageDialog(null, answer1 + " is the wrong answer");
}
String answer2 = JOptionPane.showInputDialog("quintessence, quintessance, qwintessence");
if ("quintessence".equals(answer2)) {
JOptionPane.showMessageDialog(null, "quintessence is the correct answer");
}
else {
JOptionPane.showMessageDialog(null, answer2 + " is the wrong answer");
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Spelling test = new Spelling();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
});
}
}
a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)
I am facing issues when I set my first JDialog modal and the second one non-modal.
This is the functionality I am trying to implement:
On click of "Test the dialog!" button, a JDialog with name Custom Dialog
Main will open.
If click "yes" option in Custom Dialog Main, another
JDialog named Custom Dialog Search will open.
If click "yes" option in Custom Dialog Search, then
Custom Dialog Main should come front.
And I should be able to select any JDialog. For example if I select
Custom Dialog Search, the other dialog should go
back and vice versa.
Problem I am facing is when I click "yes" in Custom Dialog Main, then Custom Dialog Search is displayed behind the main dialog.
This is happening because I am setting Custom Dialog Search non-modal.
If I this dialog modal it is displayed correctly but after I click "yes" Custom Dialog Main doesn't come front.
I even tried to set CustomDialogSearch's parent to be CustomDialog the behaviour still not correct.
Below is the example code I am testing.
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
public class TestTheDialog implements ActionListener {
JFrame mainFrame = null;
JButton myButton = null;
public TestTheDialog() {
mainFrame = new JFrame("TestTheDialog Tester");
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
myButton = new JButton("Test the dialog!");
myButton.addActionListener(this);
mainFrame.setLocationRelativeTo(null);
mainFrame.getContentPane().add(myButton);
mainFrame.pack();
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(myButton == e.getSource()) {
System.err.println("Opening dialog.");
CustomDialog myDialog = new CustomDialog(mainFrame, true, "Custom Dialog Main?");
System.err.println("After opening dialog.");
if(myDialog.getAnswer()) {
System.err.println("The answer stored in CustomDialog is 'true' (i.e. user clicked yes button.)");
}
else {
System.err.println("The answer stored in CustomDialog is 'false' (i.e. user clicked no button.)");
}
}
}
public static void main(String argv[]) {
TestTheDialog tester = new TestTheDialog();
}
}
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
public class CustomDialog extends JDialog implements ActionListener {
private JPanel myPanel = null;
private JButton yesButton = null;
private JButton noButton = null;
private boolean answer = false;
private JFrame parentFrame;
public boolean getAnswer() { return answer; }
public CustomDialog(JFrame frame, boolean modal, String myMessage) {
super(frame, modal);
parentFrame = frame;
myPanel = new JPanel();
getContentPane().add(myPanel);
myPanel.add(new JLabel(myMessage));
yesButton = new JButton("Yes");
yesButton.addActionListener(this);
myPanel.add(yesButton);
noButton = new JButton("No");
noButton.addActionListener(this);
myPanel.add(noButton);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(yesButton == e.getSource()) {
CustomDialogSearch myDialog = new CustomDialogSearch(parentFrame, false, "CustomDialog Search?");
System.err.println("User chose yes.");
answer = true;
myDialog.getAnswer();
System.out.println("myDialog.getAnswer()="+myDialog.getAnswer());
myDialog.show();
if(myDialog.getAnswer()==true)
{
System.out.println("tofront");
this.toFront();
}
//setVisible(false);
}
else if(noButton == e.getSource()) {
System.err.println("User chose no.");
answer = false;
setVisible(false);
}
}
}
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
public class CustomDialogSearch extends JDialog implements ActionListener {
private JPanel myPanel = null;
private JButton yesButton = null;
private JButton noButton = null;
private boolean answer = false;
public boolean getAnswer() { return answer; }
public CustomDialogSearch(JFrame frame, boolean modal, String myMessage) {
super(frame, modal);
myPanel = new JPanel();
getContentPane().add(myPanel);
myPanel.add(new JLabel(myMessage));
yesButton = new JButton("Yes");
yesButton.addActionListener(this);
myPanel.add(yesButton);
noButton = new JButton("No");
noButton.addActionListener(this);
myPanel.add(noButton);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(yesButton == e.getSource()) {
System.err.println("Search User chose yes.");
answer = true;
//setVisible(false);
}
else if(noButton == e.getSource()) {
System.err.println("Search User chose no.");
answer = false;
setVisible(false);
}
}
}
I even tried to set CustomDialogSearch's parent to be CustomDialog the
behaviour still not correct.
I think you're in the right track here but you need to play with dialogs modality type. For instance:
Set the modality type of Custom Dialog Main ("parent" dialog) as Dialog.ModalityType.APPLICATION_MODAL. By doing this when this dialog is visible it will block all windows except its children.
Set the modality type of Custom Dialog Search ("child" dialog) as Dialog.ModalityType.MODELESS. This way it won't block any other window and you can go from the child to the parent and vice versa.
For a better understanding take a look to How to Use Modality in Dialogs article.
Example
Here is a code example about using modality as I've suggested above:
import java.awt.Dialog;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Demo {
private void createAndShowGUI() {
JButton button = new JButton("Create Parent modal dialog");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
JFrame owner = (JFrame)SwingUtilities.windowForComponent(button);
Demo.this.createAndShowParentDialog(owner);
}
});
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void createAndShowParentDialog(JFrame owner) {
JButton button = new JButton("Create Child non-modal dialog");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
JDialog parent = (JDialog)SwingUtilities.windowForComponent(button);
Demo.this.createAndShowChildrenDialog(parent);
}
});
JDialog parentDialog = new JDialog(owner, "Parent dialog");
parentDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
parentDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
parentDialog.getContentPane().add(button);
parentDialog.pack();
parentDialog.setLocationRelativeTo(null);
parentDialog.setVisible(true);
}
private void createAndShowChildrenDialog(JDialog parent) {
JButton backButton = new JButton("Back to parent dialog");
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
Window dialog = SwingUtilities.windowForComponent(button);
dialog.getOwner().toFront();
}
});
JDialog childDialog = new JDialog(parent, "Child dialog");
childDialog.setModalityType(Dialog.ModalityType.MODELESS);
childDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
childDialog.getContentPane().add(backButton);
childDialog.pack();
childDialog.setLocationRelativeTo(null);
childDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().createAndShowGUI();
}
});
}
}
Edit
I can select the windows of parent and child JDialogs but when I
select the parent JDialog window, the child JDialog is still in front
of parent JDialog.
Well I have a better understanding now on what is the problem. This behaviour depends on how native windowing system handles focused and active windows. Having said this if you call for instance toFront() it will attempt to place the window at the top of the stack BUT some platforms do not allow windows which own other windows to appear on top of its childre. The same happens when you call toBack() method. See the javadocs for more details.
I've tested my code on Windows 7 (32 bits if it makes any difference) and parent dialog becomes focused but its children still showing (not focused) at the top. As mentioned above it's up to the windowing system decide how to handle this matter.
Calling one JFrame from another using Timer without any buttons: time is decreased then open another JFrame without any buttons. Please help. Used in netbeans
Your question is very unclear, but the use of multiple frames is not recommended. As an alternative, consider a modeless dialog, shown below. The dialog's enclosed JOptionPane listens for a PropertyChangeEvent, while counting down from TIME_OUT using javax.swing.Timer. The JOptionPane button is convenient but not required.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/**
* #see https://stackoverflow.com/a/12451673/230513
*/
public class JOptionTimeTest implements ActionListener, PropertyChangeListener {
private static final int TIME_OUT = 10;
private int count = TIME_OUT;
private final Timer timer = new Timer(1000, this);
private JDialog dialog = new JDialog();
private final JOptionPane optPane = new JOptionPane();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new JOptionTimeTest().createGUI();
}
});
}
private void createGUI() {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
timer.setCoalesce(false);
optPane.setMessage(message());
optPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
optPane.setOptionType(JOptionPane.DEFAULT_OPTION);
optPane.addPropertyChangeListener(this);
dialog.add(optPane);
dialog.pack();
frame.add(new JLabel(frame.getTitle(), JLabel.CENTER));
frame.pack();
frame.setVisible(true);
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
timer.start();
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (JOptionPane.VALUE_PROPERTY.equals(prop)) {
thatsAllFolks();
}
}
public void actionPerformed(ActionEvent e) {
count--;
optPane.setMessage(message());
if (count == 0) {
thatsAllFolks();
}
timer.restart();
}
private String message() {
return "Closing in " + count + " seconds.";
}
private void thatsAllFolks() {
dialog.setVisible(false);
dialog.dispatchEvent(new WindowEvent(
dialog, WindowEvent.WINDOW_CLOSING));
}
}