Manipulação de objetos no JavaFX[dúvida]

0 respostas
bruno_bls

Fala galera

Então preciso de uma ajuda para entender como manipular algum objetos no JavaFX

Estou com um projeto de um programa de backup. Para que possam entender melhor vou demonstrar a hierarquia dos pacotes

Meu projeto esta dividido da seguinte maneira

--Projeto
     app
        |Aplicacao.java   //principal onde abro login, verifico um arquivo properties e inicio um systemtray
     controller
        |ArquivoController.java      //lê e grava as informações no properties
        |ConfiguracaoController.java
        |LoginController.java
        |Task.java       //utilizo este para iniciar o systemtray e criar uma tarefa agendada pelo TimerTask
     resources
        //imagens e css
     view
        |Login.fxml
        |Configuracao.fxml
     vo
        |VoPropriedades.java

Na classe principal que tenho o main eu inicio um SystemTray, a classe fica assim

public class Aplicacao extends Application {

    public static java.awt.TrayIcon trayIcon;
    
    public static java.awt.SystemTray tray;

    @Override
    public void start(Stage stage) throws Exception {
        
        File file = new File("C:\\Backup Online\\Conf.Properties");
        ArquivoController con = new ArquivoController();
        
        if(!file.exists())
            con.newFile();
        
        Parent root = FXMLLoader.load(getClass().getResource("/view/Login.fxml"));
            
        this.stage = stage;
        
        Platform.setImplicitExit(false);

        // sets up the tray icon (using awt code run on the swing thread).
        javax.swing.SwingUtilities.invokeLater(this::addAppToTray);
              
        addDragListeners(root, stage); 

        root.setStyle(
            "-fx-background-color: rgba(255, 255, 255, 0.5);" +
            "-fx-background-insets: 50;"
        );
        
        Scene scene = new Scene(root, 384, 257, Color.TRANSPARENT);
        scene.setFill(Color.TRANSPARENT);
        
        stage.setScene(scene);
        stage.setTitle("Login");
        stage.setResizable(false);
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private void addAppToTray(){
        try {
            java.awt.Toolkit.getDefaultToolkit();

            if (!java.awt.SystemTray.isSupported()) {
                System.out.println("No system tray support, application exiting.");
                Platform.exit();
            }

            this.tray = java.awt.SystemTray.getSystemTray();
            
            java.awt.Image image = ImageIO.read(getClass().getClassLoader().getResourceAsStream("res/download.png"));
            this.trayIcon = new java.awt.TrayIcon(image,"Backup Online");

            this.trayIcon.addActionListener(event -> Platform.runLater(this::showStage));

            java.awt.MenuItem openItem = new java.awt.MenuItem("Abrir");
            openItem.addActionListener(event -> Platform.runLater(this::showStage));

            java.awt.Font defaultFont = java.awt.Font.decode(null);
            java.awt.Font boldFont = defaultFont.deriveFont(java.awt.Font.BOLD);
            openItem.setFont(boldFont);

            java.awt.MenuItem exitItem = new java.awt.MenuItem("Sair");
            exitItem.addActionListener(event -> {
                notificationTimer.cancel();
                Platform.exit();
                this.tray.remove(this.trayIcon);
            });

            // setup the popup menu for the application.
            final java.awt.PopupMenu popup = new java.awt.PopupMenu();
            popup.add(openItem);
            popup.addSeparator();
            popup.add(exitItem);
            this.trayIcon.setPopupMenu(popup);
            
            Task task = new Task();
            task.tarefa();
            
            // add the application tray icon to the system tray.
            //this.tray.add(this.trayIcon);
        } catch (IOException e) {
            System.out.println("Unable to init system tray");
            //e.printStackTrace();
        }
    }
}

Certo, depois que esta classe abre o Login.fxml e o LoginController eu efetuo o login e vai para a classe ConfiguracaoController.

Em ConfiguracaoController eu tenho um método que é ativo ao clicar em um button
O método é este

@FXML
    public void cliqueBtnSalvar(ActionEvent event) throws FileNotFoundException {
        vo.setNomeempresa(tfEmpresa.getText());
        vo.setHora_backup(tfHora.getText());
        vo.setMinuto_backup(tfMinuto.getText());

        ArquivoController saveConfig = new ArquivoController();
        saveConfig.writeConfigBackup(vo);    // aqui vai ser gravada as informações novas como hora, minuto e empresa
        
        new Task();  // depois leio o properties para abrir um novo TimeTask
    }

A classe Task vai mandar verificar o novo horário do backup e criar a task.

import static app.Aplicacao.trayIcon;
import static app.Aplicacao.tray;

public class Task {   
    
    public void tarefa() throws FileNotFoundException{
        VoPropriedades vo = new ArquivoController().LoadProperties();
        
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(vo.getHora_backup()));
        calendar.set(Calendar.MINUTE, Integer.parseInt(vo.getMinuto_backup()));
        calendar.set(Calendar.SECOND, 0);
        Date time = calendar.getTime();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {  //mais tarde ele vai invocar um método para acionar o envio de backup
                javax.swing.SwingUtilities.invokeLater(() ->
                        trayIcon.displayMessage(
                                        "Backup Online",
                                        "Efetuando backup " ,
                                        java.awt.TrayIcon.MessageType.INFO
                                )
                            );                          
            }
        }, time);
        
            try {
                tray.add(trayIcon);
            } catch (AWTException ex) {
                Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
            }
    }  
}

Como podem ver eu tento adicionar ao balão do SystemTray uma mensagem de backup, porém não dá certo. A tentativa foi feita tentando dar um importe na variável static da classe Principal.

Minha duvida é, como posso manipular este SystemTray (pelo ConfiguracaoControllerou Task) que criei anteriormente em outra classe?

Criado 7 de novembro de 2015
Respostas 0
Participantes 1