Мне нужно обновить всю информацию одного из столбцов моей базы данных, исходя из изменений, которые пользователь вносит в tableView простым нажатием кнопки, но я понятия не имею, как ее использовать. Я думал об использовании listview.forEach()
, чтобы он проходил через каждый из пунктов. Как я могу получить информацию из таблицы, используя forEach
для обновления базы данных?
Вот мой TableController:
package sempre.alerta.financeiro;
import connection.ConnectionClasse;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.application.Platform;
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.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.AnchorPane;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* @author Mayumi Liz
*/
public class TabelaVisaoGeralController implements Initializable {
@FXML
private AnchorPane AnchorPaneTabelaVisaoGeral;
@FXML
private MenuBar mnbMenuVisaoGeral;
@FXML
private Menu mnuOpcoes;
@FXML
private MenuItem mnuiNovo;
@FXML
private MenuItem mnuiEditar;
@FXML
private MenuItem mnuiApagar;
@FXML
private Menu mnuAtualizar;
@FXML
private MenuItem mnuiAtualizarDados;
@FXML
private Menu mnuAjuda;
@FXML
private MenuItem mnuiSobre;
@FXML
private TableView<TabelaGeral> tableTabelaVisaoGeral;
@FXML
private TableColumn<TabelaGeral, String> tbcUEB;
@FXML
private TableColumn<TabelaGeral, String> tbcNome;
@FXML
private TableColumn<TabelaGeral, String> tbcData;
@FXML
private TableColumn<TabelaGeral, String> tbcRamo;
@FXML
private TableColumn<TabelaGeral, Boolean> tbcCondicao;
public String sql;
ObservableList<TabelaGeral> listview = FXCollections.observableArrayList();
int x = 0;
/**
* Initializes the controller class.
*/
@FXML
private void mnuNovo(ActionEvent event) throws IOException {
System.out.println("menu Novo");
AnchorPane pane = FXMLLoader.load(getClass().getResource("TelaCadastro.fxml"));
Platform.runLater(new Runnable() { //esse método permite controlar objetos graficos a partir de outras classes
@Override
public void run() {
TelaMenuController.controleMenu.AnchorPaneTelas.getChildren().setAll(pane);
}
});
}
@FXML
private void mnuApagar(ActionEvent event) {
TabelaGeral tabela = tableTabelaVisaoGeral.getSelectionModel().getSelectedItem(); //vetor que tem valor do objeto selecionado na tabela
String ueb = tabela.getCodigoueb();
try {
ConnectionClasse cn = new ConnectionClasse();
Connection cn1 = cn.fileconnection();
PreparedStatement stmt = cn1.prepareStatement("DELETE FROM cadastro WHERE codigoueb = '"+ ueb + "'");
stmt.execute();
}
catch(Exception e){
}
tableTabelaVisaoGeral.getItems().removeAll(tabela); //remove da TABELA
System.out.println(ueb + " deletado.");
}
@FXML
private void mnuiAtualizarDados(ActionEvent event) {
listview.forEach(item -> { //I thought about introducing the code to update the database right here.
});
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
RamosController tabela = new RamosController();
tbcUEB.setCellValueFactory(new PropertyValueFactory<>("codigoueb"));
tbcNome.setCellValueFactory(new PropertyValueFactory<>("nome"));
tbcData.setCellValueFactory(new PropertyValueFactory<>("datadenasc"));
tbcRamo.setCellValueFactory(new PropertyValueFactory<>("ramo"));
tbcCondicao.setCellValueFactory(new PropertyValueFactory<>("selected"));
try{
ConnectionClasse cn = new ConnectionClasse();
Connection cn1 = cn.fileconnection();
if (tabela.tipo == "lobinhos"){
sql = "SELECT * FROM CADASTRO WHERE ramo = 'Lobinhos'";
}
if (tabela.tipo == "escoteiros"){
sql = "SELECT * FROM CADASTRO WHERE ramo = 'Escoteiros'";
}
if (tabela.tipo == "senior"){
sql = "SELECT * FROM CADASTRO WHERE ramo = 'Sênior'";
}
if (tabela.tipo == "pioneiros"){
sql = "SELECT * FROM CADASTRO WHERE ramo = 'Pioneiros'";
}
if (tabela.tipo == "geral") {
sql = "SELECT * FROM CADASTRO";
}
Statement s = cn1.createStatement();
ResultSet r = s.executeQuery(sql); //ResultSet é uma tabela de dados que representa um conjunto de dados do BD.
while(r.next())
{
listview.add(new TabelaGeral(
r.getString("DATADENASC"),
r.getString("NOME"),
r.getString("RAMO"),
r.getString("CODIGOUEB"),
r.getBoolean("PAGO")
));
}
tbcCondicao.setCellFactory(CheckBoxTableCell.forTableColumn(tbcCondicao)); //renderiza o campo Condição
//como uma checkBox.
tableTabelaVisaoGeral.setItems(listview);
//con.close();
} catch(Exception e) {
}
}
}
А вот мой fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" fx:id="AnchorPaneTabelaVisaoGeral" prefHeight="416.0" prefWidth="517.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sempre.alerta.financeiro.TabelaVisaoGeralController">
<children>
<MenuBar fx:id="mnbMenuVisaoGeral" layoutY="2.0" prefHeight="25.0" prefWidth="517.0">
<menus>
<Menu fx:id="mnuOpcoes" mnemonicParsing="false" text="Opções">
<items>
<MenuItem fx:id="mnuiNovo" mnemonicParsing="false" onAction="#mnuNovo" text="Novo" />
<MenuItem fx:id="mnuiEditar" mnemonicParsing="false" text="Editar" />
<MenuItem fx:id="mnuiApagar" mnemonicParsing="false" onAction="#mnuApagar" text="Apagar" />
</items></Menu>
<Menu fx:id="mnuAtualizar" mnemonicParsing="false" text="Atualizar">
<items>
<MenuItem fx:id="mnuiAtualizarDados" mnemonicParsing="false" onAction="#mnuiAtualizarDados" text="Atualizar dados" />
</items>
</Menu>
<Menu fx:id="mnuAjuda" mnemonicParsing="false" text="Ajuda">
<items>
<MenuItem fx:id="mnuiSobre" mnemonicParsing="false" text="Sobre" />
</items>
</Menu>
</menus>
</MenuBar>
<TableView fx:id="tableTabelaVisaoGeral" editable="true" layoutY="27.0" prefHeight="390.0" prefWidth="517.0">
<columns>
<TableColumn fx:id="tbcUEB" prefWidth="69.0" text="UEB" />
<TableColumn fx:id="tbcNome" prefWidth="226.0" text="Nome" />
<TableColumn fx:id="tbcData" prefWidth="86.0" text="Data de nasc." />
<TableColumn fx:id="tbcRamo" prefWidth="83.0" text="Ramo" />
<TableColumn fx:id="tbcCondicao" prefWidth="52.0" text="Pago" />
</columns>
</TableView>
</children>
</AnchorPane>