Olá a todos, eu estou correndo atras de umas dicas de CRUD em javaFX usando modelo MVC, mas com a view feita em FXML.
Estou com muita dificuldade de entender a parte do model que eu poderia utilizar.
Queria uma estrutura que fosse nesse estilo os package
Acesse esse link JavaFX Tutorial, tem um tutorial de CRUD com JavaFX, entretanto a persistência é feita em arquivos XML, mas já serve como base. Se quiser mudar o modelo de persistência para um Banco de Dados é bem simples. (Comecei a desenvolver em JavaFX por esse tutorial).
Outro exemplo: CRUD JFX com Hibernate - Esse usa BD e ainda com o visual do W8.
Fala ai amigo vc teria um CRUD de JavaFX com JDBC, pois eu estou estudando com essa finalidade.
Minha dificuldade em fazer o projeto seria a ligação do model (bean, dao) com o controller.
Pois com property eu não consigo fazer ainda.
/*
* 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 model Eclispse JPA e Annotations;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author wssco
*/
@Entity(name = "contato")
public class Contato implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(length = 50, nullable = false)
private String nome;
@Column(length = 20, nullable = false)
private String fone;
@Column(length = 250)
private String email;
public Contato() {
}
public Contato(int id, String nome, String fone, String email) {
this.id = id;
this.nome = nome;
this.fone = fone;
this.email = email;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the fone
*/
public String getFone() {
return fone;
}
/**
* @param fone the fone to set
*/
public void setFone(String fone) {
this.fone = fone;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}
o CRUD fazendo a persistência:
/*
* 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 controller;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import model.Contato;
/**
*
* @author wssco
*/
public class ContatoController {
private final EntityManagerFactory emf;
private final EntityManager em;
private final EntityTransaction tx;
public ContatoController() {
emf = Persistence.createEntityManagerFactory("TemplusFXPU");
em = emf.createEntityManager();
tx = em.getTransaction();
}
public void gravar(Contato c) {
tx.begin();
em.persist(c);
em.flush();
tx.commit();
}
public void remover(Contato c) {
tx.begin();
em.remove(c);
tx.commit();
}
public List<Contato> lista() {
tx.begin();
List<Contato> list = em.createQuery("select c from contato c").getResultList();
tx.commit();
return list;
}
}
Agora a VIEW com JavaFX e SceneBuilder:
/*
* 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 controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import model.Contato;
/**
* FXML Controller class
*
* @author wssco
*/
public class FXMLContatoGuiController implements Initializable {
private final ObservableList<Contato> dadosContato;
private final ContatoController contatoController;
public FXMLContatoGuiController() {
contatoController = new ContatoController();
dadosContato = FXCollections.observableArrayList(contatoController.lista());
}
@FXML
private TableView contatoTable;
@FXML
private TableColumn idCol;
@FXML
private TableColumn nomeCol;
@FXML
private TableColumn foneCol;
@FXML
private TableColumn emailCol;
@FXML
private TextField nomeTextField;
@FXML
private TextField foneTextField;
@FXML
private TextField emailTextField;
@FXML
private Button gravarButton;
/**
* Initializes the controller class.
*
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
preencherTabela();
}
@FXML
public void eventGravarButtonClick(ActionEvent event) {
Contato c = new Contato();
try {
c.setNome(nomeTextField.getText());
c.setFone(foneTextField.getText());
c.setEmail(emailTextField.getText());
contatoController.gravar(c);
alert("Gravado com sucesso");
} catch (Exception ex) {
alert(ex.getMessage());
}
}
public void preencherTabela() {
idCol.setCellValueFactory(new PropertyValueFactory("Id"));
nomeCol.setCellValueFactory(new PropertyValueFactory("Nome"));
foneCol.setCellValueFactory(new PropertyValueFactory("Fone"));
emailCol.setCellValueFactory(new PropertyValueFactory("Email"));
contatoTable.setItems(dadosContato);
}
public void alert(String msg) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText(null);
alert.setTitle("Mensagem");
alert.setContentText(msg);
alert.show();
}
}
a classe Main do JavaFX
/*
* 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 view;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* @author wssco
*/
public class MainApp extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("FXMLContatoGui.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("Contato");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
O controller apenas se comunica com a camada service, e o service se comunica com a camada dao.
Se precisar de algum objeto persisitdo no banco de dados, epenas faça a camada service abstrair da camada dao e mandar para o controller
Voce só precisa inicializar um objeto da camada service no controller para tal.
Espero ter ajudado. O desenvolvimento da View foi feito com a criação da tela no SceneBuilder usando como controller a classe FXMLContatoGuiController para manipular a inicialização e a manipulação dos objetos.