This question already has an answer here:
Closing a runnable JOptionPane
(1 answer)
Closed 7 years ago.
I want to close a JOptionPane after passed some time, i have tried with dispose(), hide(), and using the command getRootPane().dispose() with no results.
I want to close it after 3 seconds or more so the user don't need to press the button at any time the JOptionPane emerges.
You can use one of these statements to hide/close the JFrame.
Frame.setVisible(false);
or
jFrame.dispose();
i.e.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new JOptionPane());
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
Thread.sleep(5000); //sleep 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.setVisible(false);
}
You can loop over the active windows creating this method on the class you want to do it:
private Timer createTimerClose(int seconds) {
ActionListener close = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window[] windows = Window.getWindows();
for (Window window : windows) {
if (window instanceof JDialog) {
JDialog dialog = (JDialog) window;
if (dialog.getContentPane().getComponentCount() == 1
&& dialog.getContentPane().getComponent(0) instanceof JOptionPane){
dialog.dispose();
}
}
}
}
};
Timer t = new Timer(seconds * 1000, close);
t.setRepeats(false);
return t;
}
And after it you call the metod createTimerClose(secondsyouwanttoclose).start(); before calling your JOptionPane.
Related
I have this code sample in a separate jDialog (jDialog is in the same package as that of JFrame) which used to check (using a Thread) if the jCheckBox1 in the jFrame is whether visible or not. JDialog is set to visible by clicking a JLabel (Change Password) in JFrame. I have not set the visibility of the JFrame even to false even after I click on the Change Password JLabel.
The problem I encountered is that even if the JFrame is not visible i.e when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible" and I'm more than sure that the jFrame is not visible and not running.
This is the code snippet (Thread) I have used to check the visibility of the JFrame's jCheckBox1:
LockOptions lock = new LockOptions();
private void setLocation2() {
new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lock.jCheckBox1.isVisible()) {
System.out.println("Visible");
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
And this is the Code I have written in JFrame's Change Password JLabel:
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {
Container c = new ChangePassword(this, rootPaneCheckingEnabled);
if (!c.isShowing()) {
c.setVisible(true);
hideMeToSystemTray();
this.requestFocusInWindow();
}
}
But when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible"
I have attached a Screenshots of both JFrame and JDialog
JFrame containing jCheckBox1
JDialog:
OK, let's have the simplest possible example.
The following code creates a main frame having a button to create a new frame of class LockOptionsWindow, which extends JFrame.
The class FrameDemo implements Runnable. So can it be accessed on the event dispatching thread using SwingUtilities.invokeLater as mentioned in Swing's Threading Policy. So it is possible creating a new thread checklockoptionswindow which then can check whether the new window created by the button is visible or not visible.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameDemo extends WindowAdapter implements ActionListener, Runnable {
private LockOptionsWindow lockoptionswindow;
private Thread checklockoptionswindow = new Thread();
private void showLockOptionsWindow() {
if (lockoptionswindow != null && lockoptionswindow.isDisplayable()) {
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
} else {
lockoptionswindow = new LockOptionsWindow();
lockoptionswindow.setSize(new Dimension(300, 100));
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
}
}
private void startCheckLockOptionsWindow() {
if (!checklockoptionswindow.isAlive()) {
checklockoptionswindow = new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lockoptionswindow.isVisible()) {
if (lockoptionswindow.getExtendedState() == Frame.ICONIFIED) {
System.out.println("Visible iconified");
} else {
System.out.print("Visible on screen ");
int x = lockoptionswindow.getLocation().x;
int y = lockoptionswindow.getLocation().y;
System.out.println("at position " + x + ", " + y);
}
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
checklockoptionswindow.start();
}
}
public void actionPerformed(ActionEvent e) {
showLockOptionsWindow();
startCheckLockOptionsWindow();
}
public void run() {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Show LockOptions frame");
button.addActionListener(this);
Container contentPane = frame.getContentPane();
contentPane.add(button);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new FrameDemo());
}
class LockOptionsWindow extends JFrame {
public LockOptionsWindow() {
super("LockOptions frame");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
Edited to determine whether the LockOptionsWindow is visible iconified only or is really showed as window on the screen.
This question already has an answer here:
While loop with delay makes JFrame unresponsive
(1 answer)
Closed 9 years ago.
I am making a simple PopUp game where the code below calls a new instance of a class called PopUp. PopUp is a Jframe with a button on it. When the constructor is called inside the loop the button is not displayed. However when the loop is removed the button is displayed just fine. Please help me. Thank you.
public void game() {
PopUp p1;
while(!gameover) {
try {
//If block to set the difficulty of the game
if(diff==0)
TimeUnit.MILLISECONDS.sleep(1000);
else if(diff==1)
TimeUnit.MILLISECONDS.sleep(750);
else if(diff==2)
TimeUnit.MILLISECONDS.sleep(500);
else if(diff==3)
TimeUnit.MILLISECONDS.sleep(250);
else if(diff==4)
TimeUnit.MILLISECONDS.sleep(100);
p1 = new PopUp(); //keep
p1.setLocation(((int)(Math.random()*2000)), ((int)(Math.random()*1000)));
popUpsOpen++;
} catch (InterruptedException ex) {
Logger.getLogger(PopUpGame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Try to call Game constructor with different Thread.
Thread queryThread = new Thread() {
public void run() {
new game();
}
};
queryThread.start();
and in Game constructor show the popup with UI thread
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
p1 = new PopUp(); //keep
p1.setLocation(((int)(Math.random()*2000)), ((int)(Math.random()*1000)));
popUpsOpen++;
}
});
i think the button is not displaying because the UI thread busy with looping,so the button doesnt get chance to rendered by UI thread
place the these statements after the try-catch block, and also check the value of the variable gameover.
p1 = new PopUp(); //keep
p1.setLocation(((int)(Math.random()*2000)), ((int)(Math.random()*1000)));
popUpsOpen++;
I am working on an application in which I have developed a window with three check boxes. When first and second check boxes are selected, new windows will be opened as desired. The third check box is for closing the application. When Exit check box is selected, it is showing the conformation Dialog as desired but Exit check box is not ticked.
I could not trace out the issue here. Please help me to resolve this issue!
package jcheckbox;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InitiaaWindow extends JPanel {
static JFrame frame = new JFrame("Credit Contract Validation");
private static final long serialVersionUID = 1L;
JCheckBox jValidateECOUT;
JCheckBox jValidateSuperDeals;
JCheckBox jEXIT;
JLabel jlbPicture,jlbPicture1;
CheckBoxListener myListener = null;
public InitiaaWindow() {
myListener = new CheckBoxListener();
jValidateECOUT = new JCheckBox("ValidateECOUT");
jValidateECOUT.setMnemonic(KeyEvent.VK_C);
jValidateECOUT.setSelected(false);
jValidateECOUT.addItemListener(myListener);
jValidateSuperDeals = new JCheckBox("ValidateSuperDeals");
jValidateSuperDeals.setMnemonic(KeyEvent.VK_G);
jValidateSuperDeals.setSelected(false);
jValidateSuperDeals.addItemListener(myListener);
jEXIT = new JCheckBox("EXIT");
jEXIT.setMnemonic(KeyEvent.VK_G);
jEXIT.setSelected(false);
jEXIT.addItemListener(myListener);
jlbPicture = new JLabel(new ImageIcon("src/jcheckbox/image.jpg"));
jlbPicture1 = new JLabel(new ImageIcon("src/jcheckbox/image1.jpg"));
JPanel jplCheckBox = new JPanel();
jplCheckBox.setLayout(new GridLayout(0, 1));
jplCheckBox.add(jValidateECOUT);
jplCheckBox.add(jValidateSuperDeals);
jplCheckBox.add(jEXIT);
setLayout(new BorderLayout());
add(jplCheckBox, BorderLayout.WEST);
add(jlbPicture1, BorderLayout.CENTER);
add(jlbPicture, BorderLayout.EAST);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
class CheckBoxListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (jValidateECOUT.isSelected())
{
try {
UIPack.UI.myMethod(null);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (jValidateSuperDeals.isSelected())
{
try {
ValidateSuperDealsUIPack.UI.ValidateSuperDealsUI(null);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (jEXIT.isSelected())
{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Would you like to close the application", "Conformation message",dialogButton);
if(dialogResult==0)
System.exit(1);
else
JOptionPane.getRootFrame().dispose();
}
}
}
public static void main(String s[]) {
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new InitiaaWindow());
frame.pack();
frame.setVisible(true);
}
}
Since showConfirmDialog creates a modal dialog until the dialog is closed the execution of item selection event may not propagate to other listeners which might be responsible for updating the display of the checkbox.
If you click 'No' in the dialog, does the checkbox update properly? If yes then you can create the dialog in a separate runnable task using SwingUtilities.invokeLater this will ensure the current processing of selection event completes before the modal dialog is opned.
You can add
jEXIT.setSelected(true);
before
int dialogButton = JOptionPane.YES_NO_OPTION;
1.Sorry, but your code style is really terrible (IMHO, I don't want you to be dissappointed of that).
2.Use ActionListener instead of ItemListener for JCheckBox. And check the source of action before process it:
ActionListener listener = new ActionListener({
#Override
public void actionPerfomed(ActionEvent ae) {
if (ae.getSource().equals(comboBox1) {
//process 1
} else if (ae.getSource().equals(comboBox2) {
//process 2
} else if (ae.getSource().equals(comboBox3) {
//process 3
}
}
});
comboBox1.add(listener);
comboBox2.add(listener);
comboBox3.add(listener);
3.If you want to show modal dialogs on action events, it is good to use SwingUtilities.invokeLater() for that, because your action' source should repaint after action perfomed.
I am working on a project in which I would like to close a generic JOptionPane programmatically (by not physically clicking on any buttons). When a timer expires, I would like to close any possible JOptionPane that may be open and kick the user back to the login screen of my program. I can kick the user back just fine, but the JOptionPane remains unless I physically click a button on it.
I have looked on many sites with no such luck. A doClick() method call on the "Red X" of the JOptionPane does not seem possible, and using JOptionpane.getRootFrame().dispose() does not work.
Technically, you can loop through all windows of the application, check is they are of type JDialog and have a child of type JOptionPane, and dispose the dialog if so:
Action showOptionPane = new AbstractAction("show me pane!") {
#Override
public void actionPerformed(ActionEvent e) {
createCloseTimer(3).start();
JOptionPane.showMessageDialog((Component) e.getSource(), "nothing to do!");
}
private Timer createCloseTimer(int seconds) {
ActionListener close = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window[] windows = Window.getWindows();
for (Window window : windows) {
if (window instanceof JDialog) {
JDialog dialog = (JDialog) window;
if (dialog.getContentPane().getComponentCount() == 1
&& dialog.getContentPane().getComponent(0) instanceof JOptionPane){
dialog.dispose();
}
}
}
}
};
Timer t = new Timer(seconds * 1000, close);
t.setRepeats(false);
return t;
}
};
This code gotten from
https://amp.reddit.com/r/javahelp/comments/36dv3t/how_to_close_this_joptionpane_using_code/ seems to be the best approach to me. It involves Instantiating the JOptionPane class rather that using the static helper methods to do it for you. The benefit is you have a JOptionPane object that you can dispose when you want to close the dialog.
JOptionPane jop = new JOptionPane();
jop.setMessageType(JOptionPane.PLAIN_MESSAGE);
jop.setMessage("Hello World");
JDialog dialog = jop.createDialog(null, "Message");
// Set a 2 second timer
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
dialog.dispose();
}
}).start();
dialog.setVisible(true);
This question already has answers here:
Make splash screen with progress bar like Eclipse
(2 answers)
Closed 9 years ago.
i get this source code for creating splash screen and thread management in Java. But i don't know how to implement it.
public class SplashWindow extends JWindow {
public SplashWindow(String filename, Frame f, int waitTime)
{
super(f);
JLabel l = new JLabel(new ImageIcon(filename));
getContentPane().add(l, BorderLayout.CENTER);
pack();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = l.getPreferredSize();
setLocation(screenSize.width/2 - (labelSize.width/2),
screenSize.height/2 - (labelSize.height/2));
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
setVisible(false);
dispose();
}
});
final int pause = waitTime;
final Runnable closerRunner = new Runnable()
{
public void run()
{
setVisible(false);
dispose();
}
};
Runnable waitRunner = new Runnable()
{
public void run()
{
try
{
Thread.sleep(pause);
SwingUtilities.invokeAndWait(closerRunner);
}
catch(Exception e)
{
e.printStackTrace();
// can catch InvocationTargetException
// can catch InterruptedException
}
}
};
setVisible(true);
Thread splashThread = new Thread(waitRunner, "SplashThread");
splashThread.start();
}
}
I try to implement like this :
...
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
SplashWindow window = new SplashWindow("splash-scren.jpg", frame, 1000);
}
...
But nothing to show.
Please help me, thank you :)
Dont put :
"setVisible(true);"
In the constructor , after
SplashWindow window = new SplashWindow("splash-scren.jpg", frame, 1000);
write:
window.setVisible(true);