Timer or other idea required to allow code to continue execution after calling method and JOptionPane

廉价感情. 提交于 2019-11-26 18:35:59

问题


I need a way to allow my program to keep running code after this method is called.

Currently, it waits for half an hour, gets the info, stores it to the object WeatherCard, and displays it, and repeats. But it hangs on the JOptionPane. I need a way to make it so that the program either keeps going underneath the JOptionPane or to close the pane after about 10 seconds. I am not sure how to work either into my code, currently

public void printWeatherCard(WeatherCard w, JFrame controlFrame) throws MalformedURLException, IOException{
    /* Displays a dialog box containing the temperature and location */
    BufferedImage img = ImageIO.read(new URL(w.imgSrc));
    ImageIcon icon = new ImageIcon(img);

    JOptionPane.showMessageDialog(controlFrame, "It is currently " + w.currentTemp + " \u00B0 F in " + w.location.city + ", " + w.location.state + ".\nCurrent humidity: " + w.currentHumidity + 
            "%.\nChance of precipitation: " + w.chancePrecip + "%.", "Weather Update: " + w.location.zipCode, JOptionPane.INFORMATION_MESSAGE, icon);
}

回答1:


But it hangs on the JOptionPane. I need a way to make it so that the program either keeps going underneath the JOptionPane or to close the pane after about 10 seconds. I am not sure how to work either into my code, currently

there are two ways

  • (better easier, comfortable) create JDialog(JFrame parent, boolean true), with default close operation HIDE_ON_CLOSE, only one JDialog as local variable, reuse this Object by setVisible(false/true)

  • looping inside arrays of all JOptionPanes (all exists there untill current JVM is alive) by @kleopatra




回答2:


Closing a modal dialog after some delay and updating the display behind a modal dialog are distinct issues.

  • In this example, a javax.swing.Timer is used to mark time, and the dialog is closed when a counter reaches zero or the user dismisses it.

  • A modal dialog only blocks user interaction. Add a modal dialog to this example to see that GUI updates continue in response to the javax.swing.Timer.

    public void run() {
        ...
        f.setVisible(true);
        JOptionPane.showMessageDialog(dt, TITLE);
    }
    



回答3:


JOptionPane is modal, which means code execution blocks until the user dismisses or acknowledges it. You need to use a non-modal dialog. Consider creating your own JDialog. http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html



来源:https://stackoverflow.com/questions/18726083/timer-or-other-idea-required-to-allow-code-to-continue-execution-after-calling-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!