Search code examples
javajframecursor

Setting Windows Cursor


I'm working with Jframe in my application, and I want to know if it's possible to .setCursor in the all the screen while my application is doing things in background. My application takes about 30 seconds to open the first Frame because he is preparing the files to begin the process, so I there any method to set all the Screen with Waiting Cursor.

private void incializaTelaPrincipal() {

    frameImportLoadCurve = new JFrame();
    frameImportLoadCurve.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    frameImportLoadCurve.setBounds(100, 100, 450, 229);
    frameImportLoadCurve.setTitle("Importador Gerador de curvas de carga");
    frameImportLoadCurve.setLocationRelativeTo(null);
    frameImportLoadCurve.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    frameImportLoadCurve.getContentPane().add(tabsMenuPrincipal);

    frameImportLoadCurve.addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            if (JOptionPane.showConfirmDialog(frameImportLoadCurve, "Tem certeza que deseja sair?", "Encerrando",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                try {
                    Decompress.deletePropertie();
                    Decompress.deleteDirectory(Decompress.createTempDirectory());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                System.exit(0);
            }
        }
    });

    /**
     * Conectar
     * 
     * @param panelConectar
     * @param labelConectarSelecione
     * @param comboBoxConectar
     */
    tabsMenuPrincipal.addTab("Conectar", null, panelConect, null);
    panelConect.setLayout(null);

    labelConect.setBounds(20, 60, 94, 27);
    panelConect.add(labelConect);

    comboBoxConect.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    comboBoxConect.setBounds(101, 63, 226, 20);

    panelConect.add(comboBoxConect);

    buttonConectValidate.setCursor(new Cursor(Cursor.HAND_CURSOR));
    buttonConectValidate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            buttonConectValidate.setCursor(new Cursor(Cursor.WAIT_CURSOR));
            try {
                serverConnection = new ServerConnection();
                textPaneLog.setText("");
                serverConnection.validateConexion(getEnviroment());
                // JOptionPane.showMessageDialog(null, "Conex\u00E3o
                // Realizada com Sucesso");
                tabsMenuPrincipal.setEnabledAt(1, true);
                tabsMenuPrincipal.setEnabledAt(3, true);
                tabsMenuPrincipal.setEnabledAt(4, true);
                tabsMenuPrincipal.setSelectedIndex(1);
                LogUtil.addLog("Conectado com sucesso no usu\u00E1rio: " + getEnviroment());
            } catch (Exception exe) {
                log.error("Error ao validar: " + exe);
                JOptionPane.showMessageDialog(null, "Erro ao Conectar no Banco", "Info",
                        JOptionPane.WARNING_MESSAGE);
            } finally {
                buttonConectValidate.setCursor(new Cursor(Cursor.HAND_CURSOR));
            }
        }

    });
    buttonConectValidate.setBounds(263, 129, 156, 23);
    panelConect.add(buttonConectValidate);

    /**
     * Import
     * 
     * @param panelImport
     * @param textFieldImportador
     * @param labelImportadorPlanilha
     * @param buttonImportFile
     * @param buttonImportImport
     */
    tabsMenuPrincipal.addTab("Importar", null, panelImport, null);
    panelImport.setLayout(null);

    textFieldImport.setBounds(113, 60, 230, 20);
    panelImport.add(textFieldImport);
    textFieldImport.setColumns(10);

    labelImportSheet.setBounds(21, 63, 89, 14);
    panelImport.add(labelImportSheet);

    buttonImportFile.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    buttonImportFile.setBounds(373, 59, 46, 23);
    panelImport.add(buttonImportFile);
    buttonImportFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            textFieldImport.setText(ViewController.selectSheet(panelImport));
        }
    });

    buttonImportImport.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            buttonImportImport.setCursor(new Cursor(Cursor.WAIT_CURSOR));
            if (textFieldImport.getText() != null) {
                try {

                    ViewController.createProgressDialog(frameImportLoadCurve);
                    ViewController.ExecuteImportTask executeImportTask = new ViewController.ExecuteImportTask();
                    executeImportTask.addPropertyChangeListener(new ViewController.ProgressChangeListener());
                    executeImportTask.setModel(model);
                    executeImportTask.setLogTextComponent(textPaneLog);
                    executeImportTask.execute();
                    // inicializatePUConverter();
                } catch (Exception exe) {
                    JOptionPane.showMessageDialog(null,
                            "<html><b>Error na importação da Curva de Carga<br/>" + "Verificar Aba Log</b></html>",
                            "Info", JOptionPane.WARNING_MESSAGE);
                }
            } else
                JOptionPane.showMessageDialog(null, "Error ao importar, diretório n\u00E3o indicado");
            buttonImportImport.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        }
    });

    buttonImportImport.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    buttonImportImport.setBounds(330, 129, 89, 23);
    panelImport.add(buttonImportImport);

    /**
     * Results
     * 
     * @param panelResults
     * @param scrollPaneResults
     * @param tableResults
     * @param checkBoxGenerateValidarDadosDaBase
     * @param checkBoxGenerateGenerateCurvaDeCargaDosConsumidores
     * @param checkBoxGenerateGenerateCurvaDeCargaDosTransformadores
     * @param buttonGenerateGenerate
     */
    tabsMenuPrincipal.addTab("Resultados", null, panelResults, null);
    panelResults.setLayout(new CardLayout(0, 0));

    panelResults.add(scrollPaneResults, "name_18882033882061");
    tableResults.setEnabled(false);
    scrollPaneResults.setViewportView(tableResults);
    tableResults.setColumnSelectionAllowed(true);

    /**
     * Gerar
     * 
     * @param panelGenerate
     * @param labelGenerateSelecioneAAcaoDesejada
     * @param checkBoxGenerateValidarDadosDaBase
     * @param checkBoxGenerateGenerateCurvaDeCargaDosConsumidores
     * @param checkBoxGenerateGenerateCurvaDeCargaDosTransformadores
     * @param buttonGenerateGenerate
     * @param labelValidate
     */
    tabsMenuPrincipal.addTab("Gerar", null, panelGenerate, null);
    panelGenerate.setLayout(null);

    checkBoxGenerateValidateDataBase.setBounds(6, 45, 20, 23);
    panelGenerate.add(checkBoxGenerateValidateDataBase);

    lblValidate.setBounds(27, 50, 179, 14);
    panelGenerate.add(lblValidate);

    checkBoxGenerateGenerateConsumerLoadCurve.setBounds(6, 71, 381, 23);
    panelGenerate.add(checkBoxGenerateGenerateConsumerLoadCurve);
    // checkBoxGenerateGenerateConsumerLoadCurve.setEnabled(false);

    checkBoxGenerateGenerateCTLoadCurve.setBounds(6, 97, 381, 23);
    panelGenerate.add(checkBoxGenerateGenerateCTLoadCurve);
    // checkBoxGenerateGenerateCTLoadCurve.setEnabled(false);

    labelGenerate.setBounds(6, 11, 260, 14);
    panelGenerate.add(labelGenerate);

    buttonGenerateGenerate.setBounds(309, 129, 110, 23);
    panelGenerate.add(buttonGenerateGenerate);
    buttonGenerateGenerate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            generateCurves = new GenerateAllLoadCurve();

            buttonGenerateGenerate.setCursor(new Cursor(Cursor.WAIT_CURSOR));
            try {
                generateCurves.generateLoadCurve(checkBoxGenerateValidateDataBase.isSelected(),
                        checkBoxGenerateGenerateConsumerLoadCurve.isSelected(),
                        checkBoxGenerateGenerateCTLoadCurve.isSelected());
            } catch (Exception e1) {
                LogUtil.addLog("Valida\u00E7\u00E3o sem sucesso");
                generateResults("NOVALIDATE");
                log.error("Error ao validar dados: " + e1);
                panelGenerate.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                buttonGenerateGenerate.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            } finally {
                buttonGenerateGenerate.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            }
        }
    });

    /**
     * Log
     * 
     * @param panelLog
     * @param scrollPaneLog
     * @param textPaneLog
     */
    tabsMenuPrincipal.addTab("Log", null, panelLog, null);
    panelLog.setLayout(new CardLayout(0, 0));

    panelLog.add(scrollPaneLog, "ScrollLogPanelText");

    scrollPaneLog.setViewportView(textPaneLog);
    textPaneLog.setEditable(false);

    tabsMenuPrincipal.setEnabledAt(1, false);
    tabsMenuPrincipal.setEnabledAt(2, false);
    tabsMenuPrincipal.setEnabledAt(3, false);
    tabsMenuPrincipal.setEnabledAt(4, false);

}

private static void inputValues(PrincipalWindow windowImportadorDeCurvas) {
    windowImportadorDeCurvas.tableResults.setModel(windowImportadorDeCurvas.model);
}

private static String[] setEnviroment() {

    String[] populateComboBox;
    try {
        populateComboBox = Decompress.menuZip();
        return populateComboBox;
    } catch (Exception e) {
        LogUtil.addLog("Error ao popular o comboBox");
        return null;
    }
}

public static String getEnviroment() {
    String env = comboBoxConect.getSelectedItem().toString();
    GenerateAllLoadCurve.resetFrame();
    checkBoxGenerateValidateDataBase.setSelected(false);
    checkBoxGenerateGenerateConsumerLoadCurve.setSelected(false);
    checkBoxGenerateGenerateCTLoadCurve.setSelected(false);
    checkBoxGenerateGenerateConsumerLoadCurve.setForeground(Color.black);
    checkBoxGenerateGenerateCTLoadCurve.setForeground(Color.black);
    checkBoxGenerateValidateDataBase.setEnabled(true);
    lblValidate.setForeground(Color.black);
    model.getDataVector().removeAllElements();
    return env;
}

public static void writeJText(String logs) {
    String oldLog = textPaneLog.getText();
    textPaneLog.setText(oldLog + "\n" + logs);
    log.info(logs);
}

public static void inicializatePUConverter() {
    try {
        generateCurves = new GenerateAllLoadCurve();
        tabsMenuPrincipal.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        JOptionPane.showMessageDialog(null, "Iniciando coners\u00E3o para PU");
        tabsMenuPrincipal.setEnabledAt(0, false);
        tabsMenuPrincipal.setEnabledAt(1, false);
        tabsMenuPrincipal.setEnabledAt(3, false);
        tabsMenuPrincipal.setSelectedIndex(4);
        generateCurves.callPUConverte();

    } catch (Exception exe) {
        log.error("Error ao converter dados para PU: " + exe.getStackTrace());
        exe.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error ao converter curvas para PU");
    } finally {
        for (int i = 0; i <= 3; i++) {
            tabsMenuPrincipal.setEnabledAt(i, true);
        }
        tabsMenuPrincipal.setSelectedIndex(2);
        tabsMenuPrincipal.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        buttonImportImport.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }
}

public static void setCursor() {
    if (tabsMenuPrincipal.getCursor().getName().toUpperCase().equals("DEFAULT_CURSOR")) {
        tabsMenuPrincipal.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        frameImportLoadCurve.setCursor(Cursor.WAIT_CURSOR);
    } else
        tabsMenuPrincipal.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}

public static void generateResults(String result) {
    EnumResultsGenerate enumResult = null;
    enumResult = EnumResultsGenerate.valueOf(result);
    switch (enumResult) {
    case NOVALIDATE: {
        lblValidate.setForeground(Color.red);
        JOptionPane.showMessageDialog(null, "<html><b>Error ao Validar os Dados da Base</b></html>", "Error",
                JOptionPane.ERROR_MESSAGE);
        break;
    }
    case VALIDATE: {
        lblValidate.setForeground(Color.green);
        JOptionPane.showMessageDialog(null, "<html><b>Validado com sucesso</b></html>");
        checkBoxGenerateValidateDataBase.setEnabled(false);
        break;
    }
    case CONSUMERNO: {
        checkBoxGenerateGenerateConsumerLoadCurve.setForeground(Color.red);
        JOptionPane.showMessageDialog(null, "<html><b>Error ao gerar dados das curvas de consumidores</b></html>",
                "INFO", JOptionPane.WARNING_MESSAGE);
        break;
    }
    case CONSUMER: {
        checkBoxGenerateGenerateConsumerLoadCurve.setForeground(Color.green);
        JOptionPane.showMessageDialog(null, "<html><b>Curvas de Clientes criadas com sucesso</b></html>");
        break;
    }
    case CTNO: {
        checkBoxGenerateGenerateCTLoadCurve.setForeground(Color.red);
        JOptionPane.showMessageDialog(null, "<html><b>Error ao gerar dados das curvas dos CT</b></html>", "Info",
                JOptionPane.WARNING_MESSAGE);
        break;
    }
    case CT: {
        checkBoxGenerateGenerateCTLoadCurve.setForeground(Color.green);
        JOptionPane.showMessageDialog(null, "<html><b>Curvas do transformado criadas com sucesso</b></html>");
        break;
    }
    case CTNOCONSUMER: {
        checkBoxGenerateGenerateCTLoadCurve.setForeground(Color.red);
        JOptionPane.showMessageDialog(null,
                "<html><b>Não é possível gerar curva de carga<br/>"
                        + "dos transformadores, pois não existe<br/>curva de carga de consumidores</b></html>",
                "Info", JOptionPane.WARNING_MESSAGE);
        break;
    }
    case NOTVALIDATEYET: {
        JOptionPane.showMessageDialog(null, "<html><b>Sistema não validado ainda</b></html>", "Info",
                JOptionPane.WARNING_MESSAGE);
        break;
    }
    }
}

public static void display(List<String> nullCell) {
    JList list = new JList(nullCell.toArray());
    JPanel panel = new JPanel();
    panel.add(list);
    JOptionPane.showMessageDialog(null, panel, "Células nulas", JOptionPane.INFORMATION_MESSAGE);
    list.removeAll();
}

}


Solution

  • One solution could be to display a transparent full screen window and set its content pane's cursor to Cursor.WAIT_CURSOR . This window is made "always on top" and will cover the taskbar.

    Then you perform your time consuming tasks and once you're done, display the application window and dispose the splash screen.

    The following demo will give you an idea, just note that this won't prevent the user from switching between applications (e.g with Alt+Tab). Also note that full transparency didn't work for me , that's why there is 1 instead of 0 for the value of the alpha channel .

    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    
    import javax.swing.JFrame;
    import javax.swing.JWindow;
    import javax.swing.SwingUtilities;
    
    public class SplashScreenDemo extends JWindow {
    
        boolean loaded = false;
    
        public SplashScreenDemo() {
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            double width = screenSize.getWidth();
            double height = screenSize.getHeight();
    
            setSize((int) width, (int) height);
            setLocation(0, 0);
            getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            setBackground(new Color(0, 0, 0, 1));
            setAlwaysOnTop(true);
    
        }
    
        public static void main(final String[] args) {
    
            final SplashScreenDemo splash = new SplashScreenDemo();
            splash.setVisible(true);
    
            // run your time-consuming things
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    // display actual frame
                    JFrame applicationFrame = new JFrame("Application");
                    applicationFrame.setSize(200, 200);
                    applicationFrame.setVisible(true);
                    // dispose splashscreen
                    splash.dispose();
    
                }
            });
    
        }
    
    }