DEV Community

ouryperd
ouryperd

Posted on

3 2

A self-dismissing dialog in Groovy

During the running of your program, you may want to display a dialog. It is easy with:

import javax.swing.JOptionPane
JOptionPane.showMessageDialog(null, "Message", "Title", JOptionPane.INFORMATION_MESSAGE)
Enter fullscreen mode Exit fullscreen mode

However, it needs manual intervention to be dismissed. If you are running an automated test and want to display some kind of progress, the following works well:

import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingConstants

(1..5).each { testCase ->
    popup("Attention", "test case ${testCase} is currently running", 3)
    // call test case
}


def popup(String title, String message, int duration) {
    String markup = "<html><font color='blue'><b>Progress: <b><i>" + message + "</i></font></html>"
    JLabel l = new JLabel(markup)
    l.setHorizontalAlignment(SwingConstants.CENTER)
    JPanel p = new JPanel(new java.awt.GridLayout(0, 1))
    p.add(l)
    JFrame f = new JFrame(title)
    f.setContentPane(p)
    f.setSize(300, 100)
    f.setLocationRelativeTo(null)
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    long startTime = System.currentTimeMillis()
    while (System.currentTimeMillis() < (startTime + (duration * 1000))) {
        f.setVisible(true)
    }
    f.setVisible(false)
    f.dispose()
}
Enter fullscreen mode Exit fullscreen mode

The message is in HTML and can be edited however you want with HTML tags.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)