In java fxml I am retrieving the data from .csv file. I am adding dynamic columns and rows to table view and columns are adding to it but not the rows.
I am trying and searching internet but I could not get any suitable result.
My code:-
public class FXMLDocumentController {
#FXML
private TableView tableView;
String headers[] = null;
String items[] = null;
Employee ee;
#FXML
private void initialize() {
Insert();
}
public void Insert() {
List<String> columns = new ArrayList<String>();
List<String> rows = new ArrayList<String>();
ObservableList<ObservableList> csvData = FXCollections.observableArrayList();
try {
int columnIndex = 0;
TableColumn[] tableColumns;
File f = new File("C:\\Users\\admin\\Desktop\\Project\\shipforecast\\Data\\Recieve\\ShipId-1432530905282-1.csv");
if (f.exists() && !f.isDirectory()) {
FileReader fin = new FileReader(f);
BufferedReader in = new BufferedReader(fin);
String l;
int i = 0;
while ((l = in.readLine()) != null) {
if (i < 1) {
headers = l.split(",");
for (String w : headers) {
columns.add(w);
}
tableColumns = new TableColumn[columns.size()];
columnIndex = 0;
for (String columName : columns) {
//System.out.println("dynamic.FXMLDocumentController.Insert()"+columns.size());
tableColumns[columnIndex++] = new TableColumn(columName);
}
tableView.getColumns().addAll(tableColumns);
} else {
ObservableList<String> row = FXCollections.observableArrayList();
items = l.split(",");
for (String item:items) {
row.add(item);
}
csvData.add(row);
System.out.println("hi");
}
i++;
tableView.getItems().add(csvData);
}
} else {
System.out.println("File Not Found");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
What you are missing is a cellValueFactory for your columns that will tell the column what value to display in its cells.
Something like this:
TableView<ObservableList<String>> tableView = new TableView<>();
List<String> columnNames = dataGenerator.getNext(N_COLS);
for (int i = 0; i < columnNames.size(); i++) {
final int finalIdx = i;
TableColumn<ObservableList<String>, String> column = new TableColumn<>(
columnNames.get(i)
);
column.setCellValueFactory(param ->
new ReadOnlyObjectWrapper<>(param.getValue().get(finalIdx))
);
tableView.getColumns().add(column);
}
Sample Application
This solution was based slightly on Narayan's blog post: Updated: Dynamic TableView Data From Database. Rather than that blog post, this solution uses a test data generator to generate some dummy data and some of the Java 8 lambda features which make the cell value factory definition a bit less unwieldy to write and look at.
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import java.util.*;
public class DynamicTableView extends Application {
private static final int N_COLS = 5;
private static final int N_ROWS = 1_000;
public void start(Stage stage) throws Exception {
TestDataGenerator dataGenerator = new TestDataGenerator();
TableView<ObservableList<String>> tableView = new TableView<>();
// add columns
List<String> columnNames = dataGenerator.getNext(N_COLS);
for (int i = 0; i < columnNames.size(); i++) {
final int finalIdx = i;
TableColumn<ObservableList<String>, String> column = new TableColumn<>(
columnNames.get(i)
);
column.setCellValueFactory(param ->
new ReadOnlyObjectWrapper<>(param.getValue().get(finalIdx))
);
tableView.getColumns().add(column);
}
// add data
for (int i = 0; i < N_ROWS; i++) {
tableView.getItems().add(
FXCollections.observableArrayList(
dataGenerator.getNext(N_COLS)
)
);
}
tableView.setPrefHeight(200);
Scene scene = new Scene(tableView);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
private static class TestDataGenerator {
private static final String[] LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tempus cursus diam ac blandit. Ut ultrices lacus et mattis laoreet. Morbi vehicula tincidunt eros lobortis varius. Nam quis tortor commodo, vehicula ante vitae, sagittis enim. Vivamus mollis placerat leo non pellentesque. Nam blandit, odio quis facilisis posuere, mauris elit tincidunt ante, ut eleifend augue neque dictum diam. Curabitur sed lacus eget dolor laoreet cursus ut cursus elit. Phasellus quis interdum lorem, eget efficitur enim. Curabitur commodo, est ut scelerisque aliquet, urna velit tincidunt massa, tristique varius mi neque et velit. In condimentum quis nisi et ultricies. Nunc posuere felis a velit dictum suscipit ac non nisl. Pellentesque eleifend, purus vel consequat facilisis, sapien lacus rutrum eros, quis finibus lacus magna eget est. Nullam eros nisl, sodales et luctus at, lobortis at sem.".split(" ");
private int curWord = 0;
List<String> getNext(int nWords) {
List<String> words = new ArrayList<>();
for (int i = 0; i < nWords; i++) {
if (curWord == Integer.MAX_VALUE) {
curWord = 0;
}
words.add(LOREM[curWord % LOREM.length]);
curWord++;
}
return words;
}
}
}
Related
I have trouble with my Java application. I'm writing a program that connects to public transport API and perform some operations, which includes showing map of Warsaw with bus stops. I want to add an EventHandler function that allows to tap on a bus stop on the map, which will result in showing a box with some informations about this bus stop. How can I do such a thing?
My application so far:
Main.java:
package gui;
import api.Api;
import com.gluonhq.charm.down.ServiceFactory;
import com.gluonhq.charm.down.Services;
import com.gluonhq.charm.down.plugins.StorageService;
import com.gluonhq.maps.MapPoint;
import com.gluonhq.maps.MapView;
import com.gluonhq.maps.demo.PoiLayer;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.io.File;
import java.util.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Main extends Application{
private ContentType currentContent = ContentType.SCHEDULE;
private HashMap<ContentType, Pane> contentPaneMap;
private HBox buttonBox;
private Stage stage;
private Theme theme;
private final int height = 500;
private final int width = 800;
private final ToggleGroup menuButtonToggle = new ToggleGroup();
private String selectedStopId;
#Override
public void start(Stage primaryStage) {
this.stage = primaryStage;
theme = Theme.DARK;
buttonBox = new HBox();
buttonBox.getChildren().addAll(getMenuButtons());
initContentPanes();
getContentPaneAndResetStage();
primaryStage.show();
}
private void getContentPaneAndResetStage(){
Pane contentPane = contentPaneMap.get(currentContent);
VBox rootPane = new VBox();
rootPane.getChildren().addAll(buttonBox, contentPane);
Scene scene = new Scene(rootPane, width, height);
scene.getStylesheets().add(theme.cssFile);
stage.setScene(scene);
}
private List<ToggleButton> getMenuButtons(){
List<ToggleButton> buttonList = new ArrayList<>();
for(ContentType contentType:ContentType.values()){
ToggleButton button = new ToggleButton(contentType.buttonText);
button.setPrefWidth((double) width/4);
button.setOnAction(e -> {
Main.this.currentContent = contentType;
getContentPaneAndResetStage();
});
buttonList.add(button);
button.setToggleGroup(Main.this.menuButtonToggle);
}
return buttonList;
}
private void initContentPanes(){
contentPaneMap = new HashMap<>();
Api.saveLocalisationToCache();
contentPaneMap.put(ContentType.MAP, getMapPane());
contentPaneMap.put(ContentType.SCHEDULE, getSchedulePane());
contentPaneMap.put(ContentType.ROUTE, getRoutePane());
contentPaneMap.put(ContentType.SETTINGS, getSettingsPane());
}
private Pane getSchedulePane(){
VBox schedulePane = new VBox();
Label stopNameLabel = new Label("Nazwa przystanku: ");
stopNameLabel.setPadding(new Insets(5));
TextField stopName = new TextField();
stopName.setOnAction(e -> {
List<String> stopId = Api.getId(stopName.getText());
selectedStopId = null;
schedulePane.getChildren().remove(1);
schedulePane.getChildren().add(getContentForSchedulePane(stopId, stopName.getText()));
});
schedulePane.getChildren().add(new HBox(stopNameLabel, stopName));
if (selectedStopId == null) schedulePane.getChildren().add(new Pane(new Label("Nie znaleziono przystanku")));
else schedulePane.getChildren().add(new Label(selectedStopId));
return schedulePane;
}
private Pane getContentForSchedulePane(List<String> stopId, String stopName){
if (stopId.size() == 0) return new Pane(new Label("Nie znaleziono przystanku"));
if (stopId.size() == 1) {
String stop1id = stopId.get(0);
Label stopNameLabel = new Label("Przystanek " + stopName.toUpperCase() + " (id " + stop1id + ")");
stopNameLabel.setPadding(new Insets(5));
VBox newContentPane = new VBox(stopNameLabel);
ChoiceBox<String> busStopNr = new ChoiceBox<>(
FXCollections.observableArrayList(List.of(new String[]{"01", "02"})));
busStopNr.setValue("01");
ChoiceBox<String> lineChoice = new ChoiceBox<>(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue())));
Label times = new Label();
lineChoice.setOnAction(
e -> times.setText(Api.getTimes(stop1id, busStopNr.getValue(), lineChoice.getValue()).toString()));
busStopNr.setOnAction(
e -> lineChoice.setItems(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue()))));
newContentPane.getChildren().addAll(
new HBox(new Label("Nr słupka: "), busStopNr),
new HBox(new Label("Nr linii: "), lineChoice),
times);
return newContentPane;
}
GridPane newButtonPane = new GridPane();
int i = 1; int j = 0;
for (String id:stopId) {
Button b = new Button(id);
b.setOnAction(event -> {
selectedStopId = b.getText();
contentPaneMap.get(ContentType.SCHEDULE).getChildren().remove(1);
contentPaneMap.get(ContentType.SCHEDULE).getChildren()
.add(getContentForSchedulePane(Collections.singletonList(b.getText()), stopName));
});
((GridPane) newButtonPane).add(b, i, j);
i = (i+1)%4+1; j = i==1?j+1:j;
}
return newButtonPane;
}
private Pane getRoutePane(){return new VBox(new Circle(20, Color.BLUE));}
private Pane getMapPane(){
MapView mapView = new MapView();
PoiLayer poiLayer = new PoiLayer();
List<Map<String, String>> pointList = Api.getLocalization();
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
poiLayer.addPoint(point, new Circle(3, Color.RED));
}
mapView.setCenter(new MapPoint(52.230926, 21.006701));
mapView.setZoom(13);
mapView.addLayer(poiLayer);
return new StackPane(mapView);
}
public void getInfo(){
}
private Pane getSettingsPane(){
GridPane settingsPane = new GridPane();
ChoiceBox<Theme> themeChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(Theme.values()));
themeChoiceBox.setOnAction(e -> {
Main.this.theme = themeChoiceBox.getValue();
getContentPaneAndResetStage();
});
Label themeLabel = new Label("Motyw: ");
themeLabel.setPadding(new Insets(5));
settingsPane.add(themeLabel, 1, 1);
settingsPane.add(themeChoiceBox, 2, 1);
settingsPane.setHgap(10);
settingsPane.setVgap(10);
settingsPane.setGridLinesVisible(false);
return settingsPane;
}
#Override
public void init() {
System.setProperty("javafx.platform", "Desktop");
System.setProperty("http.agent", "Gluon Mobile/1.0.1");
StorageService storageService = new StorageService() {
#Override
public Optional<File> getPrivateStorage() {
return Optional.of(new File(System.getProperty("user.home")));
}
#Override
public Optional<File> getPublicStorage(String s) {
return getPrivateStorage();
}
#Override
public boolean isExternalStorageWritable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canWrite();
}
#Override
public boolean isExternalStorageReadable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canRead();
}
};
ServiceFactory<StorageService> storageServiceServiceFactory = new ServiceFactory<>() {
#Override
public Class<StorageService> getServiceType() {
return StorageService.class;
}
#Override
public Optional<StorageService> getInstance() {
return Optional.of(storageService);
}
};
Services.registerServiceFactory(storageServiceServiceFactory);
}
}
api.java:
package api;
import javafx.application.Platform;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Api {
private static final String baseUrl = "https://api.um.warszawa.pl/api/action/";
private static final String apikey = "95904037-5fdc-48d5-bd7f-c9f8d0b28947";
private static final String pathToLocalisationCache = "./.cache/stop-localisation.json";
private static HttpURLConnection getConnection(String urlString){
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
assert url != null;
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
//Współrzędne przystanków
public static List<Map<String,String>> getLocalization() {
File cacheFile = new File(pathToLocalisationCache);
String data;
if(!cacheFile.exists()){
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
data = Api.readData(connection);
} else{
data = readLocalisationFromCache();
}
List<Map<String,String>> list = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
Map<String, String> map = new HashMap<>();
for(int i = 0; i < arr1.length();i++){
String value = arr1.getJSONObject(i).getString("value");
String key = arr1.getJSONObject(i).getString("key");
map.put(key, value);
}
list.add(map);
}
return list;
}
public static void saveLocalisationToCache(){
File file = new File(pathToLocalisationCache);
if (file.exists()) return;
try{
boolean fileCreated = true;
if (!file.getParentFile().exists()) fileCreated = file.getParentFile().mkdir();
if (!fileCreated) throw new IOException("Unable to create cache directory");
fileCreated = file.createNewFile();
if (!fileCreated) throw new IOException("Unable to create file");
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = setParameters(getConnection(url));
InputStreamReader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()), StandardCharsets.UTF_8.newDecoder());
OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8.newEncoder());
in.transferTo(out);
in.close(); out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String readLocalisationFromCache(){
try{
BufferedReader reader = new BufferedReader(new FileReader(pathToLocalisationCache));
StringBuilder dataSB = new StringBuilder();
reader.lines().forEach(dataSB::append);
reader.close();
return dataSB.toString();
} catch (IOException e){e.printStackTrace();}
return null;
}
//id przystanku po nazwie
public static List<String> getId(String n) {
StringBuilder name = new StringBuilder();
try {
String[] testStrings = {n};
for (String s : testStrings) {
String encodedString = URLEncoder.encode(s, StandardCharsets.UTF_8);
name.append(encodedString);
}
} catch(Exception e){e.printStackTrace();}
String url = baseUrl+"dbtimetable_get?id=b27f4c17-5c50-4a5b-89dd-236b282bc499&name="+name+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
// Zwraca liste linii dla konkretnego przystanku i nr slupka
public static List<String> getLines(String idPrzystanku, String nrSlupka) {
String url = baseUrl+"dbtimetable_get?id=88cd555f-6f31-43ca-9de4-66c479ad5942&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
//Zwraca listę czas dla danego przystanku i linii
public static List<String> getTimes(String idPrzystanku, String nrSlupka, String line) {
String url = baseUrl+"dbtimetable_get?id=e923fa0e-d96c-43f9-ae6e-60518c9f3238&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&line="+line+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
List<String> times = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
JSONObject obj2 = arr1.getJSONObject(5);
times.add(obj2.getString("value"));
}
return times;
}
//Odczytuje dane
public static String readData(HttpURLConnection connection) {
InputStream inStream;
try {
inStream = new BufferedInputStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
Scanner in = new Scanner(inStream, StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
sb.append(in.next());
}
return sb.toString();
}
//Ustala parametry połączenia
public static HttpURLConnection setParameters(HttpURLConnection
connection) {
try {
connection.setRequestMethod("GET");
connection.setDoInput(true);
} catch (ProtocolException e) {
e.printStackTrace();
}
connection.setRequestProperty("Authorization", "Token " + apikey);
try {
if (connection.getResponseCode() != 200) {
System.out.println("Response code: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
Platform.exit(); // ze względu na javafx
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
I have no idea how to do it and I will be very grateful if someone will help me.
Based on my work experience on map libraries with JavaFX, I can share an approach you can take here. You can simply add a Mouse click event handler on the MapView and in that event you can catch the coordinates/Point where the user clicks on the screen. Then you can compare that point clicked by the user with one of the location Map points you want your user to click and see if it matches (by checking a distance between the user click position and the map coordinate of the bus stop). I have applied this approach in a different map library but similar can be applied here with some tweaks and adjustments.
List<Map<String, String>> pointList = Api.getLocalization();
mapView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
Point2D clickedMapCoordinates = mapView.screenToLocal(new Point2D(mouseEvent.getX(), mouseEvent.getY()));
for (Map<String, String> stop: pointList){
MapPoint stopPoint = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
Point2D mapStopPoint = new Point2D(stopPoint.getLongitude(), stopPoint.getLatitude());
// if user clicked on map near the position(lat,lng) of a stop
// then trigger the logic, you can change the distance threshold value according to your need
if(mapStopPoint.distance(clickedMapCoordinates) < 0.0001)
{
// perform your logic here about the stop point point...
}
}
}
});
Another approach which I suppose you can take is put a click event handler on the Circle object for the bus stop point and then check if the user's clicked circle matches the coordinates of a bus stop point.
Circle circle = new Circle(3, Color.RED);
circle.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getSource() instanceof Circle)
{
Circle clickedCircle = (Circle) mouseEvent.getSource();
Point2D clickedPoint = mapView.screenToLocal(clickedCircle.getCenterX(), clickedCircle.getCenterY())
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
if(clickedPoint.getX() == point.getLongitude() && clickedPoint.getY() == point.getLatitude())
{
// this is the clicked map point (bus stop point)
// perform your logic here
}
}
}
}
});
If the second approach doesn't work, try debugging and checking the clicked point and bus stop point coordinates values and adjust them. Hope this helps you in some way.
I create a class with 3 parameters so as to populate and display a gridview.
this object is composed like this : string, string, list.
I managed to display the first and the second parameter, but not the third one, like this :
enter image description here
This is my main code :
protected void Page_Load(object sender, EventArgs e)
{
// Process principal
try
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
Liste_template = new List<TemplateObject>();
// Tant que le DataReader lit des informations.
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newTemplate = new TemplateObject(temp_id, temp_name, liste_id_form("Content", sdr));
Liste_template.Add(newTemplate);
}
}
gv.DataSource = Liste_template;
gv.DataBind();
}
finally
{
connect.Close();
}
}
// Méthode pour délimiter chaque chaque chaine de caractères à partir des symboles dans le tableau delimiterChars.
public string[] RecupChaines(string chaine)
{
char[] delimiterChars = { ';', '&', '=', '"' };
string[] words = chaine.Split(delimiterChars);
return words;
}
// Méthode de récupération des Id des Form dans le champs Content de la table Template.
public List<String> liste_id_form(string field, SqlDataReader sdr)
{
List<string> listIdForm = new List<string>();
// enregistrement du contenu du champs Content dans une variable
string content = sdr[field].ToString();
// Tentative de séparation des deux parties de la chaine de caracteres
string chaineACouper = "<Property Name=\"Description\" Value=\"\" />";
string[] chaineArrive = content.Split(new string[] { chaineACouper }, StringSplitOptions.None);
chaineArrive[0] += chaineACouper;
// Séparation des deux parties.
string stringPartOne = chaineArrive[0];
string stringPartTwo = chaineArrive[1];
// Récuperation de la liste des valeurs des FormId de la chaine de caractères
string[] words = RecupChaines(stringPartTwo);
for (int i = 0; i < words.Length; i++)
{
if (words[i].Equals("FormId"))
{
listIdForm.Add(words[i + 5]);
}
}
return listIdForm;
}
}
I don't know how to loop on list_id_form, so as to display it on my gridview. For information, my class has an id, a name, and a list of datas.
I have to work with strings, because the datas from the database is not correctly stored. I don't have hand on this and i can't modify this.
I would like to store some datas from a database to a list of a class.
Unfortunatly, my webpage is totally blank and totally emply...
This my code :
CODE BEHIND :
protected void Page_Load(object sender, EventArgs e)
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Process principal
try
{
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
sdr.Read();
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
List<TemplateObject> Liste_template = new List<TemplateObject>()
{
new TemplateObject(temp_id,temp_name)
};
}
GridView1.DataSource = Liste_template;
GridView1.DataBind();
}
finally
{
connect.Close();
}
}
Code from the Class i created :
public class TemplateObject
{
string Id_template { get; set; }
string Name_template { get; set; }
public TemplateObject(string id, string name)
{
this.Id_template = id;
this.Name_template = name;
}
}
I would like to store and display an object which is composed of one TemplateObject and one FormObject, composed with two parameters (as TemplateObject) : id and name. I d'ont create the FormObject, because i'm starting with one at first.
I have to store my datas like this, beacause the datasource is a bit weird and i only work with strings.
You need a loop
create the list before that loop
fill the list in the loop
List<TemplateObject> Liste_template = new List<TemplateObject>()
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newObject = new TemplateObject(temp_id,temp_name);
Liste_template.Add(TemplateObject)
}
Now you can assign it as DataSource of the GridView:
GridView1.DataSource = Liste_template;
GridView1.DataBind();
I'm trying to connect to wordpress' woocommerce.com rest api.
I managed to get everything to work with postman but can't seem to get it to work with visual basic this is the code I have so far:
Public Class OAuth1
Shared oauth_consumer_key As String = "blah"
Shared oauth_consumer_Secret As String = "Blah"
Shared Sub wooproductcreate(ByVal json)
Dim token = Form1.TextBox1.Text
Dim resource_url As String = "http://store.example.com/wp-json/wc/v2/products"
Dim oauth_version As String = "1.0"
Dim oauth_signature_method As String = "HMAC-SHA256"
Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim oauth_signature As String = GeneraOAuthSignature(resource_url, _
oauth_nonce, _
oauth_signature_method, _
oauth_timestamp, _
oauth_version)
Dim headerFormat As String = "OAuth oauth_consumer_key=""{0}"",oauth_signature_method=""{1}"",oauth_timestamp=""{2}"",oauth_nonce=""{3}"",oauth_version=""{4}"",oauth_signature=""{5}"""
Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_version), Uri.EscapeDataString(oauth_signature))
ServicePointManager.Expect100Continue = False
Dim req As WebRequest
Dim res As HttpWebResponse
Dim streamReader As StreamReader
Dim contenidoRespuesta As String = ""
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim bytee = Encoding.UTF8.GetBytes(json)
req = WebRequest.Create(resource_url)
req.Timeout = -1
req.Headers.Add("Authorization", authHeader)
req.ContentType = "application/json"
req.Method = "POST"
req.ContentLength = bytee.Length
Dim stream = req.GetRequestStream()
stream.Write(bytee, 0, bytee.Length)
stream.Close()
res = DirectCast(req.GetResponse(), HttpWebResponse)
streamReader = New StreamReader(res.GetResponseStream(), encode)
While True
contenidoRespuesta = streamReader.ReadLine()
End While
'==========================
'CIERRE DE STREAMS Y COMUNICACIONES
'Abort is needed or streamReader.Close() will hang
req.Abort()
streamReader.Close()
streamReader = Nothing
res.Close()
res = Nothing
End Sub
Shared Function GeneraOAuthSignature(ByVal stream_url As String, _
ByVal oauth_nonce As String, _
ByVal oauth_signature_method As String, _
ByVal oauth_timestamp As String, _
ByVal oauth_version As String) As String
Dim baseFormat = "oauth_consumer_key={0}&oauth_signature_method={1}&oauth_timestamp={2}" & _
"&oauth_nonce={3}&oauth_version={4}"
Dim baseString As String = String.Format(baseFormat, _
oauth_consumer_key, _
oauth_signature_method, _
oauth_timestamp, _
oauth_nonce, _
oauth_version)
baseString = String.Concat("POST&", Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
'Using this base string, we then encrypt the data using a composite of the secret keys and the HMAC-SHA1 algorithm.
Dim compositeKey As String = String.Concat(Uri.EscapeDataString(oauth_consumer_Secret))
Dim oauth_signature As String
Dim hasher As HMACSHA256 = New HMACSHA256(ASCIIEncoding.ASCII.GetBytes(compositeKey))
Using hasher
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Return oauth_signature
End Function
End Class
The problem is that I get the response "The remote server returned an error: (401) Unauthorized."
I'm not sure what I need to do to over come this problem.
I'm thinking it has to be how the signature is generated maybe it spitting out a invalid signature...
Wireshark outputs this from the code:
POST /wp-json/wc/v2/products HTTP/1.1
Authorization: OAuth oauth_consumer_key="key",oauth_signature_method="HMAC-SHA256",oauth_timestamp="1506468745",oauth_nonce="NjM2NDIwNTExNDUxOTkyMjEy",oauth_version="1.0",oauth_signature="sig"
Content-Type: application/json
Host: example.com
Content-Length: 890
Connection: Keep-Alive
{
"name": "Premium Quality",
"type": "simple",
"regular_price": "21.99",
"description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
"short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
"categories": [
{
"id": 9
},
{
"id": 14
}
],
"images": [
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg",
"position": 0
},
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg",
"position": 1
}
]
}HTTP/1.1 401 Unauthorized
Date: Tue, 26 Sep 2017 23:32:24 GMT
Server: Apache
X-Powered-By: PHP/5.5.38
X-Robots-Tag: noindex
Link: <http://example.com/wp-json/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Access-Control-Allow-Headers: Authorization, Content-Type
Vary: Accept-Encoding,User-Agent
Keep-Alive: timeout=5
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
89
{"code":"woocommerce_rest_authentication_error","message":"Invalid signature - provided signature does not match.","data":{"status":401}}
0
When I use the postman I get a response that works and creates the product with no problem
POST /wp-json/wc/v2/products HTTP/1.1
Host: example.com
Connection: keep-alive
Content-Length: 890
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Content-Type: application/json
Authorization: OAuth oauth_consumer_key="key",oauth_signature_method="HMAC-SHA256",oauth_timestamp="1506468730",oauth_nonce="HJVzFL",oauth_version="1.0",oauth_signature="sig"
Postman-Token: 95240347-868c-03d0-55a9-d2fb7c51b8e2
Accept: */*
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: woocommerce_items_in_cart=1; woocommerce_cart_hash=some hash; wp_woocommerce_session_d0d4322f0d3b54c7984c1c37276328=somenumbers
{
"name": "Premium Quality",
"type": "simple",
"regular_price": "21.99",
"description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
"short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
"categories": [
{
"id": 9
},
{
"id": 14
}
],
"images": [
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg",
"position": 0
},
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg",
"position": 1
}
]
}HTTP/1.1 201 Created
Date: Tue, 26 Sep 2017 23:32:09 GMT
Server: Apache
X-Powered-By: PHP/5.5.38
X-Robots-Tag: noindex
Link: <http://example.com/wp-json/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Access-Control-Allow-Headers: Authorization, Content-Type
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Allow: GET, POST
Access-Control-Allow-Origin:
Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE
Access-Control-Allow-Credentials: true
Vary: Origin,Accept-Encoding,User-Agent
Set-Cookie: woocommerce_items_in_cart=1; path=/
Set-Cookie: woocommerce_cart_hash=some hash; path=/
Set-Cookie: wp_woocommerce_session_d0d4322f0d3b545798c1cb7276328=some hash; expires=Thu, 28-Sep-2017 16:25:49 GMT; Max-Age=147217; path=/
Location: http://example.com/wp-json/wc/v2/products/1066
Content-Encoding: gzip
Content-Length: 1041
Keep-Alive: timeout=5
Connection: Keep-Alive
Content-Type: application/json; charset=UTF-8
...........V.n#7...a
........
P...Rt..u1.5.X.....#...hn..i.....X").:.!...u.^.WW..pM.....e.......bR...(\...u..%T.....B....7..<D.i.....IG!/)... .7s.m.D..g.7s..y.Jx..r+....i....>.V...z.|fT5:>5\^<5...;.....U...2JAj.(..yL!...J.=D;d.|...*...<re.. .....u.nZ.5.......?...R.L.p....VFn"..o%.^.(.".!..."3./.....9..9...!.'.l.......r.........z.v...#; .MXR.%$.'..E...AF... '...,.`...[.v..N...U.Tf.W....o-.x.v3.;O..s...H......)...(.......w...v..6!^.~.!..r1[....$.}.\..|...fM..w..bm.R/(.J|A.....O.!.}.*..........8Z.*j...7.l..M&?]....o...=.q....V....]\..........W.......{.x&.:..Q. Ik.6....G...Hm.FY<.... ..O...VJj ...3..;.O...#y.x...Q.)Fd......W#....Y..E......`h...U..#..[.w.!.`.]x....5.....\Rq.......3Y......A.#J.F..d...QKM&.$..P. M.w.....~<...%....<.%.F.2......g.<.Uy...".I...u...t...<..A9+...v_.\..y.v|9.xr......".S....8....U.......X/.?.y...FZy.0...^.P...(.;..7....V...^|.0>...h. .<..K.y.......c.........g...w.V\.5.,.~........;.Z............=T...Dj...... .g...v...z.?p....8..o....O.^
.....m.c
.
h.N[.... .......v_...`
.b3?,.O9...!.|%a1.Ew.o.........[..
..
I've tried a few different things and have improved the code. However I still can't seem to get the signature to generate correctly it's always saying it doesn't match.
Imports RestSharp Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Shared oauth_consumer_key As String = "ck_xxx"
Shared oauth_consumer_Secret As String = "cs_XXX"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim resource_url As String = "http://example.com/wp-json/wc/v2/products"
Dim oauth_signature_method As String = "HMAC-SHA256"
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim oauth_version As String = "1.0"
Dim oauth_signature As String = GeneraOAuthSignature(resource_url, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_version)
Dim auth As String = "oauth_consumer_key=""" & oauth_consumer_key & """,oauth_signature_method=""" & oauth_signature_method & """,oauth_timestamp=""" & oauth_timestamp & """,oauth_nonce=""" & oauth_nonce & """,oauth_version=""" & oauth_version & """,oauth_signature=""" & oauth_signature & """"
MsgBox(auth)
Dim client = New RestClient(resource_url)
Dim request = New RestRequest(Method.POST)
request.AddHeader("cache-control", "no-cache")
request.AddHeader("content-type", "application/json")
request.AddHeader("authorization", "OAuth " & auth)
request.AddParameter("application/json", TextBox1.Text, ParameterType.RequestBody)
Dim response As IRestResponse = client.Execute(request)
MsgBox(response.Content)
End Sub
Shared Function GeneraOAuthSignature(ByVal stream_url As String, ByVal oauth_nonce As String, ByVal oauth_signature_method As String, ByVal oauth_timestamp As String, ByVal oauth_version As String) As String
'The next step is to generate an encrypted oAuth signature which will be use to validate the request.
'To do this, all of the request data is concatenated into a particular format as follows
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&oauth_timestamp={3}&oauth_version={4}"
Dim baseString As String = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_version)
baseString = String.Concat("POST&", Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
MsgBox(baseString)
Dim compositeKey As String = Uri.EscapeDataString(oauth_consumer_Secret)
'Using this base string, we then encrypt the data using a composite of the secret keys and the HMAC-SHA1 algorithm.
Dim oauth_signature As String
Dim hasher As HMACSHA256 = New HMACSHA256(ASCIIEncoding.ASCII.GetBytes(compositeKey))
Using hasher
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Return oauth_signature
End Function
End Class
You don't need all that code that you wrote, it's easier than you think.
Read the Usage section at the XiaoFaye/WooCommerce.NET github repo.
Also, you can install the WooCommerceNet from the NuGets:
VS > Tools > NuGet Package Manager > Manage NuGet
Im a pure newbie. I made my table by adding the columns from database with iteration:
public void captureDataSuper() {
Connection c;
ObservableList<ObservableList> data;
data = FXCollections.observableArrayList();
try {
c = KonekDB.createConnection();
//SQL FOR SELECTING ALL OF CUSTOMER
String SQL = "SELECT * from adminsupervisor";
//ResultSet
ResultSet rs = c.createStatement().executeQuery(SQL);
/**
* ********************************
* TABLE COLUMN ADDED DYNAMICALLY * ********************************
*/
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
//We are using non property style for making dynamic table
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
//now its editable
col.setCellFactory(TextFieldTableCell.<Adminsupervisor>forTableColumn());
//trying to make effect on database after edited with setOnEditCommit
col.setOnEditCommit(
new EventHandler<CellEditEvent<Adminsupervisor, String>>() {
public void handle(CellEditEvent<Adminsupervisor, String> t) {
((Adminsupervisor) t.getTableView().getItems().get(
t.getTablePosition().getRow())).set(j, t.getNewValue());
}
}
);
col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
supervisorTable.getColumns().addAll(col);
System.out.println("Column [" + i + "] ");
}
/**
* ******************************
* Data added to ObservableList * ******************************
*/
while (rs.next()) {
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
//Iterate Column
row.add(rs.getString(i));
}
System.out.println("Row [1] added " + row);
data.add(row);
}
//FINALLY ADDED TO TableView
supervisorTable.setItems(data);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
As you can see, my setOnEditCommit was completely non sense:
col.setOnEditCommit(
new EventHandler<CellEditEvent<Adminsupervisor, String>>() {
public void handle(CellEditEvent<Adminsupervisor, String> t) {
((Adminsupervisor) t.getTableView().getItems().get(
t.getTablePosition().getRow())).set(j, t.getNewValue());
}
}
);
This is the model class Adminsupervisor:
public class Adminsupervisor {
private String id;
private String username;
private String password;
private String userType;
public String getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getUserType() {
return userType;
}
public void setId(String id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserType(String userType) {
this.userType = userType;
}
void set(int j, String newValue) {
for (j = 0; j < 4; j++) {
if (j == 0) {
setId(newValue);
}
if (j == 2) {
setPassword(newValue);
}
if (j == 3) {
setUserType(newValue);
}
if (j == 1) {
setUsername(newValue);
}
}
try {
Connection c = KonekDB.createConnection();
String SQL = "UPDATE adminsupervisor SET "
+ "username=" + username + ","
+ "password=" + password + ","
+ "userType=" + userType + " WHERE id=" + id + "";
//ResultSet
c.createStatement().executeUpdate(SQL);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}}
I got this stack trace:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: com.sun.javafx.collections.ObservableListWrapper cannot be cast to AdminSide.Adminsupervisor
at AdminSide.PanelAdmin$1.handle(PanelAdmin.java:275)
at AdminSide.PanelAdmin$1.handle(PanelAdmin.java:272)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.control.TableCell.commitEdit(TableCell.java:349)
at javafx.scene.control.cell.CellUtils.lambda$createTextField$615(CellUtils.java:248)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at com.sun.javafx.scene.control.behavior.TextFieldBehavior.fire(TextFieldBehavior.java:179)
at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callAction(TextInputControlBehavior.java:178)
at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(BehaviorBase.java:218)
at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callActionForEvent(TextInputControlBehavior.java:127)
at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda$new$74(BehaviorBase.java:135)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:197)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:147)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$353(GlassViewEventHandler.java:228)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:227)
at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
at com.sun.glass.ui.View.notifyKey(View.java:966)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
So my cell wouldnt do anything after edit commited.
data is declared as ObservableList<ObservableList> data; and you fill it with ObservableLists:
while (rs.next()) {
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
...
data.add(row);
}
In the onEditCommit handler you do this however:
public void handle(CellEditEvent<Adminsupervisor, String> t) {
((Adminsupervisor) t.getTableView().getItems().get(
t.getTablePosition().getRow())).set(j, t.getNewValue());
}
t.getTableView().getItems().get(index) returns a ObservableList, which you try to cast to Adminsupervisor which for obvious reasons doesn't work...
You need to use the same type for items and in the handler. Whether you want to use ObservableList or Adminsupervisor is up to you...
Note: Add type parameters to the TableView and the TableColumn, and the compiler should complain about this. By using raw types however, you prevent the compiler from doing those checks (you may get a warning about raw types though).
Furthermore
for (j = 0; j < 4; j++) {
if (j == 0) {
setId(newValue);
}
if (j == 2) {
setPassword(newValue);
}
if (j == 3) {
setUserType(newValue);
}
if (j == 1) {
setUsername(newValue);
}
}
should be rewrittern as
setId(newValue);
setUsername(newValue);
setPassword(newValue);
setUserType(newValue);
j = 4; // not really neccessary since there is no read access to j
At least that achieves the same effect. (But maybe you just added the for loop around those ifs for no reason and it should be removed.)
And also consider removing j as parameter from the Adminsupervisor.set method since the value is never used in method (in the original version it's overwritten with 0 before any read access happens in for (j = 0; j < 4; j++) and in the improved version it's not read at all).
Furthermore the ObservableValue returned by your cellValueFactory will never trigger an update. If you use ObservableList as item type, you could use the Bindings class to get a ObservableValue for a specific index:
col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return Bindings.stringValueAt(param.getValue(), j);
}
});