有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

调用方法和JOptionPane后,允许代码继续执行所需的java计时器或其他想法

我需要一种方法,允许我的程序在调用此方法后继续运行代码

目前,它等待半小时,获取信息,将其存储到对象WeatherCard,并显示它,然后重复。但它挂在JOptionPane上。我需要一种方法,使它使程序要么继续在JOptionPane下运行,要么在大约10秒后关闭窗格。目前,我不确定如何在我的代码中使用这两种方法

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);
}

共 (3) 个答案

  1. # 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

    有两种方法

    • (更容易、更舒适)创建JDialog(JFrame parent, boolean true),使用默认的关闭操作HIDE_ON_CLOSE,只有一个JDialog作为local variable,通过setVisible(false/true)重用这个Object

    • 通过{}

  2. # 2 楼答案

    JOptionPane是模态的,这意味着代码执行会被阻塞,直到用户解除或确认它为止。你需要使用非模态对话框。考虑创建自己的j对话框。{a1}

  3. # 3 楼答案

    延迟一段时间后关闭模式对话框,并更新模式对话框后面的显示,这是明显的问题

    • 在这个example中,一个javax.swing.Timer用于标记时间,当计数器达到零或用户将其取消时,对话框关闭

    • 模式对话框只会阻止用户交互。向该example添加一个模式对话框,以查看GUI更新是否继续响应javax.swing.Timer

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