Display dialog box on the foreground screen even if the window is in the background

3

I'm developing an application where it works with schedules, the user will leave the problem running and will continue to use the pc normally and when you give a certain time will play a sound (already is done) and a dialog box would appear warning about the time. But I wanted this screen to be in the foreground, it would appear on the user screen without it needing to click on the application.

Example: When I clicked the swing button it would start " conta() ". After the LOOP FOR within that " conta() " has been completed it will pop up the dialog box. I just want this box to appear on the user's screen even though the application is MINIMIZED, in case you will not need to click on your application to see the message, it will simply appear to you without having to go to it,

For example, I leave this application running after clicking the button and I will use something else on the pc (and it gets minimized), and when it was to appear the dialog box would show on the normal screen, without having to maximize the application .

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

import javax.swing.JOptionPane;

/**
 *
 * @author Hamon
 */
public class asd extends javax.swing.JFrame {

    /** Creates new form asd */
    public asd() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(156, 156, 156)
                .addComponent(jButton1)
                .addContainerGap(171, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(79, 79, 79)
                .addComponent(jButton1)
                .addContainerGap(198, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        conta();
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(asd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(asd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(asd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(asd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new asd().setVisible(true);
            }
        });
    }

    **public void conta(){

        for(int i = 0; i < 100000; i++){

            System.out.println(i);
        }**

       JOptionPane.showMessageDialog(null, "Mensagem", "Titulo", JOptionPane.INFORMATION_MESSAGE);



    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   

}
    
asked by anonymous 11.01.2017 / 14:25

1 answer

2

As suggested in this answer on SOEn , you can do so using JDialog :

JOptionPane optionPane = new JOptionPane();
javax.swing.JDialog dialog = optionPane.createDialog(this, "Aviso");
java.awt.Toolkit.getDefaultToolkit().beep();
dialog.setAlwaysOnTop(true);    
dialog.setVisible(true);

The method setAlwaysOnTop defines that this dialog window is above all others, although this can not be guaranteed, because who decides is the operating system. In testing here on windows, it worked perfectly, but might not work this way on other systems.

Adapting to your code example would look like this if this window is used only on this screen:

import javax.swing.JOptionPane;

public class Teste extends javax.swing.JFrame {

    public Teste() {
        initComponents();
    }

    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(156, 156, 156)
                .addComponent(jButton1)
                .addContainerGap(171, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(79, 79, 79)
                .addComponent(jButton1)
                .addContainerGap(198, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        conta();
    }                                        

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Teste().setVisible(true);
            }
        });
    }

    public void conta(){

        for(int i = 0; i < 50000; i++){

            System.out.println(i);
        }
        showCustomAlert("Terminado");
    }

    public void showCustomAlert(String message){

        JOptionPane optionPane = new JOptionPane(message);
        javax.swing.JDialog dialog = optionPane.createDialog(this, "Aviso");
        java.awt.Toolkit.getDefaultToolkit().beep();
        dialog.setAlwaysOnTop(true);    
        dialog.setVisible(true);
        //coloca a janela na frente após fechar o aviso
        this.toFront();

    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   

}

Note that to display a message to JDialog , it is necessary to pass String to JOptionPane instance.

If it is to be used in other classes, the most interesting thing is to create a JDialog the part, there are some examples on how to manipulate these dialog windows.

    
11.01.2017 / 15:28