0

Criação de botão "Voltar" para voltar para menu principal com Java

#Java
Gustavo Moura
Gustavo Moura

Aqui é um exemplo de uma aplicação que estou desenvolvendo para controle de vendas, e nessa aplicação existem diversas funções, dentro dessas funções, existisse um botão de retornar ao menu principal na minha aplicação através do botão criado "voltar", Veja o código:


O código segue como:(MainViewController)

package gui;


import java.io.IOException;

import java.net.URL;

import java.util.ResourceBundle;

import java.util.function.Consumer;


import application.Main;

import gui.util.Alerts;

import javafx.fxml.FXML;

import javafx.fxml.FXMLLoader;

import javafx.fxml.Initializable;

import javafx.scene.Node;

import javafx.scene.Scene;

import javafx.scene.control.Alert.AlertType;

import javafx.scene.control.Button;

import javafx.scene.control.MenuItem;

import javafx.scene.control.ScrollPane;

import javafx.scene.layout.VBox;

import model.services.DepartmentService;

import model.services.FuncionarioService;


public class MainViewController implements Initializable{

//@FXML

//private MenuItem menuItemSeller;

//@FXML

//private MenuItem menuItemDepartment;

@FXML

private MenuItem menuItemAbout;

@FXML

Button btCadastroCliente;

@FXML

Button btCadastroFuncionario;

// @FXML

// public void onMenuItemSellerAction() {

// System.out.println("onMenuItemSellerAction");

//

// }

@FXML

public void onBtCadastroClienteAction() {

loadView("/gui/listaDeClientes.fxml", (ClienteController controller) -> {

controller.setDepartmentService(new DepartmentService());

controller.updateTableView();

});

}

@FXML

public void onBtCadastroFuncionarioAction() {

loadView2("/gui/listaDeFuncionario.fxml", (FuncionarioListController controller) -> {

controller.setFuncionarioService(new FuncionarioService());

controller.updateTableView();

});

}

@FXML

public void onMenuItemAboutAction() {

loadView("/gui/About.fxml", x -> {});

}


@Override

public void initialize(URL url, ResourceBundle rb) {

// TODO Auto-generated method stub

}

private synchronized <T> void loadView(String absoluteName, Consumer<T> initializingAction) {

try {

FXMLLoader loader = new FXMLLoader(getClass().getResource(absoluteName));

VBox newVBox = loader.load();

Scene mainScene = Main.getMainScene();

VBox mainVBox = (VBox) ((ScrollPane) mainScene.getRoot()).getContent();

Node mainMenu = mainVBox.getChildren().get(0);

mainVBox.getChildren().clear();

mainVBox.getChildren().add(mainMenu);

mainVBox.getChildren().addAll(newVBox.getChildren());

T controller = loader.getController();

initializingAction.accept(controller);

}

catch (IOException e) {

Alerts.showAlert("IO Exception", "Error loading view", e.getMessage(), AlertType.ERROR);}

}

private synchronized <T> void loadView2(String absoluteName, Consumer<T> initializingAction) {

try {

FXMLLoader loader = new FXMLLoader(getClass().getResource(absoluteName));

VBox newVBox = loader.load();

Scene mainScene = Main.getMainScene();

VBox mainVBox = (VBox) ((ScrollPane) mainScene.getRoot()).getContent();

Node mainMenu = mainVBox.getChildren().get(0);

mainVBox.getChildren().clear();

mainVBox.getChildren().add(mainMenu);

mainVBox.getChildren().addAll(newVBox.getChildren());

T controller = loader.getController();

initializingAction.accept(controller);

}

catch (IOException e) {

Alerts.showAlert("IO Exception", "Error loading view", e.getMessage(), AlertType.ERROR);

}

}

}


------------------------------------------------------------------------------------


e ClienteController como:


package gui;


import java.io.IOException;

import java.net.URL;

import java.util.List;

import java.util.Optional;

import java.util.ResourceBundle;


import application.Main;

import db.DbIntegrityException;

import gui.listeners.DataChangeListener;

import gui.util.Alerts;

import gui.util.Utils;

import javafx.beans.property.ReadOnlyObjectWrapper;

import javafx.collections.FXCollections;

import javafx.collections.ObservableList;

import javafx.event.ActionEvent;

import javafx.fxml.FXML;

import javafx.fxml.FXMLLoader;

import javafx.fxml.Initializable;

import javafx.scene.Node;

import javafx.scene.Scene;

import javafx.scene.control.Alert.AlertType;

import javafx.scene.control.Button;

import javafx.scene.control.ButtonType;

import javafx.scene.control.ScrollPane;

import javafx.scene.control.TableCell;

import javafx.scene.control.TableColumn;

import javafx.scene.control.TableView;

import javafx.scene.control.cell.PropertyValueFactory;

import javafx.scene.layout.Pane;

import javafx.scene.layout.VBox;

import javafx.stage.Modality;

import javafx.stage.Stage;

import model.entities.Cliente;

import model.services.DepartmentService;


public class ClienteController implements Initializable, DataChangeListener {


private DepartmentService service;


@FXML

private TableView<Cliente> tableViewDepartment;


@FXML

private TableColumn<Cliente, Integer> tableColumnId;


@FXML

private TableColumn<Cliente, String> tableColumnName;

@FXML

private TableColumn<Cliente, String> tableColumnSolicitante;


@FXML

private TableColumn<Cliente, Cliente> tableColumnEDIT;

@FXML

private TableColumn<Cliente, Cliente> tableColumnREMOVE;

@FXML

private TableColumn<Cliente, String> tableColumnEndereco;

@FXML

private TableColumn<Cliente, Integer> tableColumnTelefone;

@FXML

private TableColumn<Cliente, String> tableColumnEmail;


@FXML

private Button btNew;

@FXML

Button btVoltar;


private ObservableList<Cliente> obsList;

/*@FXML

public void onbtVoltarAction() {

loadView("/gui/MainView.fxml", (MainViewController controller) -> {

controller.setDepartmentService(new DepartmentService());

controller.updateTableView();

});

}

*/


@FXML

public void onbtNewAction(ActionEvent event) {

Stage parentStage = Utils.currentStage(event);

Cliente obj = new Cliente();

createDialogForm(obj, "/gui/ClienteForm.fxml", parentStage);

}

@FXML

public void onbtVoltarAction(ActionEvent event) {

Stage parentStage = Utils.currentStage(event);

createDialogForm(obj, "/gui/ClienteForm.fxml", parentStage);

}


public void setDepartmentService(DepartmentService service) {

this.service = service;

}


@Override

public void initialize(URL url, ResourceBundle rb) {

initializeNodes();


}


private void initializeNodes() {

tableColumnId.setCellValueFactory(new PropertyValueFactory<>("ID"));

tableColumnName.setCellValueFactory(new PropertyValueFactory<>("Nome"));

tableColumnEndereco.setCellValueFactory(new PropertyValueFactory<>("endereco"));

tableColumnTelefone.setCellValueFactory(new PropertyValueFactory<>("telefone"));

tableColumnEmail.setCellValueFactory(new PropertyValueFactory<>("email"));

tableColumnSolicitante.setCellValueFactory(new PropertyValueFactory<>("nomeSolicitante"));

Stage stage = (Stage) Main.getMainScene().getWindow();

tableViewDepartment.prefHeightProperty().bind(stage.heightProperty());

}


public void updateTableView() {

if (service == null) {

throw new IllegalStateException("Service estava nulo");

}

List<Cliente> list = service.findAll();

obsList = FXCollections.observableArrayList(list);

tableViewDepartment.setItems(obsList);

initEditButtons();

initRemoveButtons();

}


private void createDialogForm(Cliente obj, String absoluteName, Stage parentStage) {

try {

FXMLLoader loader = new FXMLLoader(getClass().getResource(absoluteName));

Pane pane = loader.load();


ClienteFormController controller = loader.getController();

controller.setDepartment(obj);

controller.updateFormData();

controller.setDepartmentService(new DepartmentService());

controller.subscribeDataChangeListener(this);


Stage dialogStage = new Stage();

dialogStage.setTitle("Informe os dados do cliente");

dialogStage.setScene(new Scene(pane));

dialogStage.setResizable(false);

dialogStage.initOwner(parentStage);

dialogStage.initModality(Modality.WINDOW_MODAL);

dialogStage.showAndWait();

} catch (IOException e) {

Alerts.showAlert("IO Exception", "Error loading view", e.getMessage(), AlertType.ERROR);

}

}


@Override

public void onDataChanged() {

updateTableView();


}


private void initEditButtons() {

tableColumnEDIT.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));

tableColumnEDIT.setCellFactory(param -> new TableCell<Cliente, Cliente>() {

private final Button button = new Button("Editar");

@Override

protected void updateItem(Cliente obj, boolean empty) {

super.updateItem(obj, empty);

if (obj == null) {

setGraphic(null);

return;

}

setGraphic(button);

button.setOnAction(

event -> createDialogForm( obj, "/gui/ClienteForm.fxml",Utils.currentStage(event)));

}

});

}

private void initRemoveButtons() {

tableColumnREMOVE.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));

tableColumnREMOVE.setCellFactory(param -> new TableCell<Cliente, Cliente>() {

private final Button button = new Button("Deletar");

@Override

protected void updateItem(Cliente obj, boolean empty) {

super.updateItem(obj, empty);

if (obj == null) {

setGraphic(null);

return;

}

setGraphic(button);

button.setOnAction(event -> removeEntity(obj));

}

});

}


private void removeEntity(Cliente obj) {

Optional <ButtonType> result = Alerts.showConfirmation("Confirmação", "Deseja deletar o registro?");

if(result.get() == ButtonType.OK) {

if (service == null) {

throw new IllegalStateException("Service was null");

}

try {

service.remove(obj);

updateTableView();

}

catch(DbIntegrityException e) {

Alerts.showAlert("erro ao remover objeto", null, e.getMessage(), AlertType.ERROR);

}

}

}

}


0
41

Comentários (0)

None

Brasil