设置Windows游标

时间:2017-02-09 13:53:25

标签: java jframe cursor

我在我的应用程序中使用Jframe,我想知道在我的应用程序在后台执行操作时是否可以在所有屏幕中使用.setCursor。我的应用程序需要大约30秒才能打开第一帧,因为他正在准备文件以开始这个过程,所以我有任何方法来设置所有屏幕与等待光标。

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();
}

}

2 个答案:

答案 0 :(得分:0)

嗯,我不认为在整个屏幕上等待光标的良好逻辑,如果一个应用程序在等待工作,那么它并不意味着你不能同时使用其他应用程序。

  

我从你的问题中理解你想要设置等待光标   正在加载文件。

您可以使用JFrame#setCursor方法将光标设置为等待光标,然后在文件加载时再次将光标重置为正常光标。

在执行加载文件的操作之前,请参考当前JFrame

设置等待光标
frameReference.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

完成文件加载操作后,将光标重置为正常,

frameReference.setCursor(Cursor.getDefaulCursor());

答案 1 :(得分:0)

一种解决方案是显示透明的全屏窗口并将其内容窗格的光标设置为Cursor.WAIT_CURSOR。 此窗口“始终位于顶部”,将覆盖任务栏。

然后执行耗时的任务,完成后,显示应用程序窗口并配置启动画面。

以下演示将为您提供一个想法,请注意,这不会阻止用户在应用程序之间切换(例如 Alt + Tab )。 另请注意,完全透明对我来说不起作用,这就是为什么alpha通道的值为1而不是0。

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();

            }
        });

    }

}