JDialog исчезает слишком рано для пользователя, чтобы просмотреть информацию, которую он содержит
Когда я пытаюсь отобразить мой JDialog, содержащий правильную информацию (передаваемую через пользовательский объект WeatherCard), он исчезает сразу же после создания. Я что-то пропустил или я слишком сильно выдумал?
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);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
Label lb = new Label("It is currently " + w.currentTemp + " \u00B0 F in " + w.location.city + ", " + w.location.state + ".\nCurrent humidity: " + w.currentHumidity);
panel.add(lb);
final JDialog dialog = new JDialog(controlFrame, "Weather Update: " + w.location.zipCode);
dialog.setSize(500,500);
dialog.add(panel);
dialog.pack();
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
dialog.setVisible(true);
}
1 ответ
Ваш подход работает в этом полном примере ниже. Ваш результат может быть артефактом пренебрежения созданием графического интерфейса в потоке отправки событий. Также, start()
Timer
после того, как диалог виден.
Также рассмотрите этот пример, который отображает оставшееся время.
import java.awt.EventQueue;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
* @see https://stackru.com/a/19003038/230513
*/
public class Test {
static class TestAction extends AbstractAction {
private final JFrame f;
public TestAction(String name, JFrame f) {
super(name);
this.f = f;
}
@Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
Label label = new Label("It is currently sunny & warm somewhere.");
panel.add(label);
final JDialog dialog = new JDialog(f, "Weather Update");
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(f);
dialog.setVisible(true);
Timer timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
}
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JButton(new TestAction("Test", f)));
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Test().display();
}
});
}
}