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

Asked

Viewed 1,558 times

3

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

Example: when I clicked on the swing button it would start the "conta()". After the loop is inside that "conta()", if finished it will appear the dialog box. I just want this box to appear on the user screen even though the application is MINIMIZED, in case you don’t need to click on your application to see the message, it will just appear to you, without having to go to it, you understand?

For example, I leave this application running after clicking the button and I will use something else on the pc (and it is minimized), and when it was to appear the dialog box it would show on the normal screen, without needing 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                   

}
  • JOptionPane.showMessageDialog (null, "Texto da mensagem", "titulo", JOptionPane.INFORMATION_MESSAGE); doesn’t solve?

  • No, I need to open the application again, just like this to visualize. I would like it to appear without needing to go directly to see if there are any messages, it would simply appear on the screen.

  • Then add a [mcve] of your application so it is possible to view the problem.

  • Actually you don’t even need the code, but here’s the thing, for example, I let this one run, it will take a while to finish, and when (imagine that this is a swing, that when I click on a button it starts the loop), after that I would minimize the screen and use the pc normally, i wanted the dialog to appear on my screen without me having to click on the application (which is minimized) to see understand?

  • Without seeing the code becomes complicated to suggest something, the question would be wide and could be closed, because there are several ways to do this. It would be interesting to add an example that can be played, from the screen where you want to do this.

  • Okay, it’s edited. I’m learning to deal with it here. If you can try again to help me with the main question, I’d appreciate it.

  • I tested the code with the minimized screen and the message box appeared even with the window being minimized. Joptionpane always appears in the foreground.

  • Okay, try it this way now. Click on the button and then click on another icon, for example from the browser (without clicking to minimize), you will see that now does not appear.

  • Can help me even diegofm?

  • I’m doing some tests, just a moment and I’ve already put a solution.

  • Okay, thank you very much!

Show 6 more comments

1 answer

2


As suggested in this answer on Soen, it is possible to do this by 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 cannot be guaranteed, since it is the operating system that decides. In tests here on windows, it worked perfectly, but may not work this way on other systems.

Adapting to the example of your code, would look like below, 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 a String the instance of JOptionPane.

If you are going to use in other classes, the most interesting thing is to create a JDialog the part, on the site there are some examples how to manipulate these dialogue windows.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.