I took the sample code from How to create custom components in JavaFX 2.0 using FXML?. the code working fine in jdk7 but the checkbox and combo box values are not working in jdk8. I am not able to click the check box even and select the dropdown.
Please guide me for the same.
Please find the sample code below
Package structure
com.example.javafx.choice
ChoiceCell.java
ChoiceController.java
ChoiceModel.java
ChoiceView.fxml
com.example.javafx.mvc
FxmlMvcPatternDemo.java
MainController.java
MainView.fxml
MainView.properties
ChoiceCell.java
package com.example.javafx.choice;
import java.io.IOException;
import java.net.URL;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
public class ChoiceCell extends ListCell<ChoiceModel>
{
#Override
protected void updateItem(ChoiceModel model, boolean bln)
{
super.updateItem(model, bln);
if(model != null)
{
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try
{
Node root = (Node)fxmlLoader.load(location.openStream());
ChoiceController controller = (ChoiceController)fxmlLoader.getController();
controller.setModel(model);
setGraphic(root);
}
catch(IOException ioe)
{
throw new IllegalStateException(ioe);
}
}
}
}
ChoiceController.java
package com.example.javafx.choice;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
public class ChoiceController
{
private final ChangeListener<String> LABEL_CHANGE_LISTENER = new ChangeListener<String>()
{
public void changed(ObservableValue<? extends String> property, String oldValue, String newValue)
{
updateLabelView(newValue);
}
};
private final ChangeListener<Boolean> IS_SELECTED_CHANGE_LISTENER = new ChangeListener<Boolean>()
{
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue)
{
updateIsSelectedView(newValue);
}
};
private final ChangeListener<Boolean> IS_VISIBILITY1_CHANGE_LISTENER = new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue) {
updateIsVisibleView1(newValue);
}};
#FXML
private Label labelView;
#FXML
private CheckBox isSelectedView;
#FXML
ComboBox isVisible1;
private ChoiceModel model;
public ChoiceModel getModel()
{
return model;
}
public void setModel(ChoiceModel model)
{
if(this.model != null)
removeModelListeners();
this.model = model;
setupModelListeners();
updateView();
}
private void removeModelListeners()
{
model.labelProperty().removeListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().removeListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().removeListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().unbindBidirectional(model.isSelectedProperty());
}
private void setupModelListeners()
{
model.labelProperty().addListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().addListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().addListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().bindBidirectional(model.isSelectedProperty());
}
private void updateView()
{
updateLabelView();
updateIsSelectedView();
updateIsVisibleView1();
}
private void updateLabelView(){ updateLabelView(model.getLabel()); }
private void updateLabelView(String newValue)
{
labelView.setText(newValue);
}
private void updateIsSelectedView(){ updateIsSelectedView(model.isSelected()); }
private void updateIsSelectedView(boolean newValue)
{
isSelectedView.setSelected(newValue);
}
private void updateIsVisibleView1() {
updateIsVisibleView1(model.isVisible1());
}
private void updateIsVisibleView1(boolean newValue) {
isVisible1.setVisible(newValue);
}
}
ChoiceModel.java
package com.example.javafx.choice;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ChoiceModel
{
private final StringProperty label;
private final BooleanProperty isSelected;
private final BooleanProperty isVisible1;
public ChoiceModel(String label, boolean isSelected, boolean isVisible1)
{
this.label = new SimpleStringProperty(label);
this.isSelected = new SimpleBooleanProperty(isSelected);
this.isVisible1 = new SimpleBooleanProperty(isVisible1);
}
public String getLabel(){ return label.get(); }
public void setLabel(String label){ this.label.set(label); }
public StringProperty labelProperty(){ return label; }
public boolean isSelected(){ return isSelected.get(); }
public void setSelected(boolean isSelected){ this.isSelected.set(isSelected); }
public BooleanProperty isSelectedProperty(){ return isSelected; }
public boolean isVisible1()
{
return isVisible1.get();
}
public void setVisible1(boolean isVisible1)
{
this.isVisible1.set(isVisible1);
}
public BooleanProperty isVisibleProperty1()
{
return isVisible1;
}
}
ChoiceView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.example.javafx.choice.ChoiceController">
<children>
<CheckBox fx:id="isSelectedView" />
<Label fx:id="labelView" />
<ComboBox id="isVisible1" fx:id="isVisible1" value="last 7 digits" visible="false">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="last 10 digits" />
<String fx:value="last 9 digits" />
<String fx:value="last 8 digits" />
<String fx:value="last 7 digits" />
<String fx:value="last 6 digits" />
<String fx:value="last 5 digits" />
<String fx:value="last 4 digits" />
<String fx:value="last 3 digits" />
</FXCollections>
</items>
</ComboBox>
</children>
</HBox>
FxmlMvcPatternDemo.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceController;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FxmlMvcPatternDemo extends Application
{
public static void main(String[] args) throws ClassNotFoundException
{
Application.launch(FxmlMvcPatternDemo.class, args);
}
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load
(
FxmlMvcPatternDemo.class.getResource("MainView.fxml"),
ResourceBundle.getBundle(FxmlMvcPatternDemo.class.getPackage().getName()+".MainView")/*properties file*/
);
ChoiceController controller = new ChoiceController();
stage.setScene(new Scene(root));
stage.show();
}
}
MainController.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceCell;
import com.example.javafx.choice.ChoiceModel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
public class MainController implements Initializable
{
#FXML
private ListView<ChoiceModel> choicesView;
#Override
public void initialize(URL url, ResourceBundle rb)
{
choicesView.setCellFactory(new Callback<ListView<ChoiceModel>, ListCell<ChoiceModel>>()
{
public ListCell<ChoiceModel> call(ListView<ChoiceModel> p)
{
return new ChoiceCell();
}
});
choicesView.setItems(FXCollections.observableArrayList
(
new ChoiceModel("Tiger", true, false),
new ChoiceModel("Shark", false, true),
new ChoiceModel("Bear", false, true),
new ChoiceModel("Wolf", true, true)
));
}
#FXML
private void handleForceChange(ActionEvent event)
{
if(choicesView != null && choicesView.getItems().size() > 0)
{
boolean isSelected = choicesView.getItems().get(0).isSelected();
choicesView.getItems().get(0).setSelected(!isSelected);
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.mvc.MainController"
prefWidth="300"
prefHeight="400"
fillWidth="false"
>
<children>
<Label text="%title" />
<ListView fx:id="choicesView" />
<Button text="Force Change" onAction="#handleForceChange" />
</children>
</VBox>
MainView.proprties
title=JavaFX 2.0 FXML MVC demo
I didn't dig deeper but refactoring like as following should suffice. Double check for correct executions of attached and removed listeners.
public class ChoiceCell extends ListCell<ChoiceModel> {
private Node root;
private ChoiceController controller;
public ChoiceCell() {
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try {
root = (Node) fxmlLoader.load(location.openStream());
controller = (ChoiceController) fxmlLoader.getController();
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
#Override
protected void updateItem(ChoiceModel model, boolean bln) {
super.updateItem(model, bln);
if (model != null) {
controller.setModel(model);
setGraphic(root);
} else {
setGraphic(null);
}
}
}
Related
I am new to stackoverflow and to Java. I am trying to fetch the data from the database then display it in a JSF page.
For the table I have a model : BusesInfo.java that contains getters and setters for the attributes of the table.
then I also have BusesDao that fetches the data from DB and stores it in an array list. BusesInfoBean that links these data to the JSF page. The connection to the database is success. the JSF page contains a table that calls BusesInfobean.busesInfo in the columns i call BusesInfo.attribute
Please I need your help! Below you can find sample codes:
package beans;
import daos.BusesDao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import models.BusesInfo;
#ViewScoped
public class BusesInfoBean implements Serializable {
private final BusesDao busesDao = new BusesDao();
private ArrayList<BusesInfo> busesInfo;
public BusesInfoBean(){}
#PostConstruct
public void init(){
try {
busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(ManageEventsBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<BusesInfo> getBusesInfo() {
return busesInfo;
}
public void setBusesInfo(ArrayList<BusesInfo> busesInfo) {
this.busesInfo = busesInfo;
}
}
BusesDao.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import models.BusesInfo;
import java.util.logging.Logger;
import java.util.logging.Level;
public class BusesDao extends ConnectionDao {
public ArrayList<BusesInfo> buildBusesInfo() throws Exception {
ArrayList<BusesInfo> list = new ArrayList<>();
Connection conn = getConnection();
try {
String sql = "SELECT * FROM BUSES_INFO";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(populateBusesInfo(rs));
}
rs.close();
ps.close();
return list;
} catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
private BusesInfo populateBusesInfo(ResultSet rs) throws SQLException {
BusesInfo busesInfo = new BusesInfo();
busesInfo.setBusID(rs.getInt("BUS_ID"));
busesInfo.setDriverID(rs.getInt("DRIVER_ID"));
busesInfo.setDepartureTime(rs.getString("DEPARTURE_TIME"));
busesInfo.setArrivalTime(rs.getString("ARRIVAL_TIME"));
busesInfo.setRouteEn(rs.getString("ROUTE_EN"));
busesInfo.setRouteAr(rs.getString("ROUTE_AR"));
busesInfo.setLicensePlate(rs.getString("LICENSE_PLATE"));
busesInfo.setCapacity(rs.getInt("CAPACITY"));
return busesInfo;
}
public static void main(String [] args){
try {
BusesDao busesDao = new BusesDao();
ArrayList<BusesInfo> busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(EventsDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
the model class BusesInfo only contains getters and setters:
public class BusesInfo implements Serializable {
private int busID;
private int driverID;
private String departureTime;
private String arrivalTime;
private String routeEn;
private String routeAr;
private String licensePlate;
private int capacity;
public BusesInfo(){}
/**
*
* #param busID
* #param driverID
* #param departureTime
* #param arrivalTime
* #param routeEn
* #param routeAr
* #param licensePlate
* #param capacity
*/
public BusesInfo(int busID, int driverID, String departureTime, String arrivalTime, String routeEn, String routeAr, String licensePlate, int capacity) {
this.busID = busID;
this.driverID = driverID;
this.departureTime = departureTime;
this.arrivalTime = arrivalTime;
this.routeEn = routeEn;
this.routeAr = routeAr;
this.licensePlate = licensePlate;
this.capacity = capacity;
}
public int getBusID() {
return busID;
}
public void setBusID(int busID) {
this.busID = busID;
}
public int getDriverID() {
return driverID;
}
public void setDriverID(int driverID) {
this.driverID = driverID;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getRouteEn() {
return routeEn;
}
public void setRouteEn(String routeEn) {
this.routeEn = routeEn;
}
public String getRouteAr() {
return routeAr;
}
public void setRouteAr(String routeAr) {
this.routeAr = routeAr;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
JSF page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>#{msgs.buses}</title>
</h:head>
<h:body>
<div>
<ui:decorate template="/app_templates/app_template.xhtml">
<h:form id="bus_info_form">
<p:dataTable
id="bus_info_tbl"
value = "#{busesInfoBean.busesInfo}"
class = "dataTable"
var="event"
rows="2"
dir="#{langBean.dir}"
emptyMessage="#{msgs.no_buses}"
paginator="true"
paginatorPosition="top"
paginatorTemplate="#{langBean.isEnglish? '{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}' : '{RowsPerPageDropdown} {LastPageLink} {NextPageLink} {PageLinks} {PreviousPageLink} {FirstPageLink}'}"
>
<p:ajax event="rowSelectRadio"
update=":bus_info_form:bus_info_tbl"/>
<f:facet name="header" id="header">
#{msgs.buses}
</f:facet>
<p:column selectionMode="single" style="width:5%"/>
<p:column headerText="#{msgs.bus_id}"
style="width:15%"
sortBy="#{busesInfo.busID}">
<h:outputText value="#{busesInfo.busID}"/>
</p:column>
<p:column headerText="#{msgs.driver_id}"
style="width:15%"
sortBy="#{busesInfo.driverID}">
<h:outputText value="#{busesInfo.driverID}"/>
</p:column>
<p:column headerText="#{msgs.departure_time}"
style="width:15%"
sortBy="#{busesInfo.departureTime}">
<h:outputText value="#{busesInfo.departureTime}"/>
</p:column>
<p:column headerText="#{msgs.arrival_time}"
style="width:15%"
sortBy="#{busesInfo.arrivalTime}">
<h:outputText value="#{busesInfo.arrivalTime}"/>
</p:column>
<p:column headerText="#{msgs.route}"
style="width:20%"
filterBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"
filterMatchMode="contains"
sortBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}">
<h:outputText value="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"/>
</p:column>
<p:column headerText="#{msgs.license_plate}"
style="width:15%"
sortBy="#{busesInfo.licensePlate}">
<h:outputText value="#{busesInfo.licensePlate}"/>
</p:column>
<p:column headerText="#{msgs.capacity}"
style="width:15%"
sortBy="#{busesInfo.capacity}">
<h:outputText value="#{busesInfo.capacity}"/>
</p:column>
</p:dataTable>
</h:form>
</ui:decorate>
</div>
</h:body>
</html>
I'm trying to find a way to use check boxes to allow the user to pick two things from a list of three, and then have the remaining check box become disabled until one of the others is un-selected. I have a ChangeListener attached to all three check boxes, so I can register when two have been selected, but I don't know how to target the "other" box/boxes to disable/enable them.
ChangeListener checkboxlistener = new ChangeListener() {
int i = 0;
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if((boolean) observable.getValue() == true) {
i++;
System.out.println(i);
} else {
i--;
System.out.println(i);
}
if(i == 2) {
//What should I put here, if anything?//
}
}
};
checkbox1.selectedProperty().addListener(checkboxlistener);
checkbox2.selectedProperty().addListener(checkboxlistener);
checkbox3.selectedProperty().addListener(checkboxlistener);
}
Keep a collection of selected check boxes and unselected check boxes. Add a listener to each check box's selectedProperty and make sure it is in the correct collections when the selection changes.
Then you can just observe the size of the collection of selected check boxes, and update the disable state of all the unselected check boxes accordingly.
Here's an example:
MultipleCheckBoxExampleController.java:
package multiplecheckbox;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
public class MultipleCheckBoxExampleController {
#FXML
private CheckBox checkBox1 ;
#FXML
private CheckBox checkBox2 ;
#FXML
private CheckBox checkBox3 ;
#FXML
private Button submitButton ;
private ObservableSet<CheckBox> selectedCheckBoxes = FXCollections.observableSet();
private ObservableSet<CheckBox> unselectedCheckBoxes = FXCollections.observableSet();
private IntegerBinding numCheckBoxesSelected = Bindings.size(selectedCheckBoxes);
private final int maxNumSelected = 2;
public void initialize() {
configureCheckBox(checkBox1);
configureCheckBox(checkBox2);
configureCheckBox(checkBox3);
submitButton.setDisable(true);
numCheckBoxesSelected.addListener((obs, oldSelectedCount, newSelectedCount) -> {
if (newSelectedCount.intValue() >= maxNumSelected) {
unselectedCheckBoxes.forEach(cb -> cb.setDisable(true));
submitButton.setDisable(false);
} else {
unselectedCheckBoxes.forEach(cb -> cb.setDisable(false));
submitButton.setDisable(true);
}
});
}
private void configureCheckBox(CheckBox checkBox) {
if (checkBox.isSelected()) {
selectedCheckBoxes.add(checkBox);
} else {
unselectedCheckBoxes.add(checkBox);
}
checkBox.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
unselectedCheckBoxes.remove(checkBox);
selectedCheckBoxes.add(checkBox);
} else {
selectedCheckBoxes.remove(checkBox);
unselectedCheckBoxes.add(checkBox);
}
});
}
}
MultipleCheckBoxExample.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="multiplecheckbox.MultipleCheckBoxExampleController"
alignment="center" spacing="5">
<padding>
<Insets top="10" bottom="10" left="10" right="10" />
</padding>
<CheckBox fx:id="checkBox1" text="Choice 1" />
<CheckBox fx:id="checkBox2" text="Choice 2" />
<CheckBox fx:id="checkBox3" text="Choice 3" />
<Button fx:id="submitButton" text="Submit" />
</VBox>
Main.java:
package multiplecheckbox;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
VBox root = FXMLLoader.load(getClass().getResource("MultipleCheckBoxExample.fxml"));
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
I'm trying to populate my TableView in JavaFX with data from my database.
I've been trying a lot of different methods to try and get something working. I've been changing a lot of things but ultimately I haven't gotten anywhere. I think it has something to do with the way I'm loading my FXML file.
My database has 3 columns, so I'm not sure if I have to define everything from the database in my Artist class and that's why it's giving me errors.
I built my GUI with SceneBuilder so I'll attach my FXML file.
My main class
package application;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
public class Main extends Application {
#Override
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(Main.class
.getResource("artistSelection.fxml"));
Group rootGroup = loader.load();
final artistSelectionController controller = loader.getController();
controller.setStage(stage);
Scene scene = new Scene(rootGroup,600,400);
stage.setScene(scene);
StageStyle stageStyle = StageStyle.TRANSPARENT;
scene.setFill(Color.TRANSPARENT);
stage.initStyle(stageStyle);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
My Controller Class
public class artistSelectionController{
#FXML
private Rectangle rect;
#FXML
private ImageView logo;
#FXML
private HBox buttons;
#FXML
private Button newArtist;
#FXML
private Button closeScreen;
private Stage stage;
private double dragAnchorX;
private double dragAnchorY;
private PreparedStatement preparedStatement;
public void setStage(Stage stage){
this.stage = stage;
}
#FXML
public void closeScreenHandler(ActionEvent e){
stage.close();
}
#FXML
public void mousePressedHandler(MouseEvent me) {
dragAnchorX = me.getScreenX() - stage.getX();
dragAnchorY = me.getScreenY() - stage.getY();
}
#FXML
public void mouseDraggedHandler(MouseEvent me) {
stage.setX(me.getScreenX() - dragAnchorX);
stage.setY(me.getScreenY() - dragAnchorY);
}
#FXML
private static TableView<Artist> artistTable;
#FXML
private TableColumn<Artist, String> artistName;
private DBConnect objDbClass;
private Connection con;
private Logger logger;
#FXML
void initialize(){
// assert artistTable != null : "fx:id=\"tableview\" was not injected: check your FXML file 'UserMaster.fxml'.";
artistName.setCellValueFactory(
new PropertyValueFactory<Artist,String>("Artist"));
objDbClass = new DBConnect();
try{
con = objDbClass.getConnection();
buildData();
}
catch(ClassNotFoundException ce){
logger.newInput(ce.toString());
}
catch(SQLException ce){
logger.newInput(ce.toString());
}
}
private ObservableList<Artist> data;
public void buildData(){
data = FXCollections.observableArrayList();
try{
String SQL = "Select Name from ARTIST";
ResultSet rs = con.createStatement().executeQuery(SQL);
while(rs.next()){
Artist cm = new Artist();
cm.name.set(rs.getString("name"));
data.add(cm);
}
artistTable.setItems(data);
}
catch(Exception e){
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
}
My POJO
package application;
import javafx.beans.property.SimpleStringProperty;
public class Artist {
public SimpleStringProperty name = new SimpleStringProperty();
public SimpleStringProperty genre = new SimpleStringProperty();
public String getName() {
return name.get();
}
public String getGenre() {
return genre.get();
}
}
My Database Connector
import java.sql.*;
public class DBConnect{
public Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost/myStudio","root","root");
}
}
And finally my FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.shape.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<Group fx:id="rootGroup" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application/artistSelectionController">
<children>
<Rectangle fx:id="rect" arcHeight="50.0" arcWidth="50.0" height="376.0" layoutX="13.0" layoutY="13.0" stroke="BLACK" strokeType="INSIDE" width="577.0">
<fill>
<LinearGradient cycleMethod="REPEAT" endX="1.0" endY="1.0" startY="1.0">
<stops>
<Stop color="#1b2f36" />
<Stop color="#1b2f36" offset="0.007662835249042145" />
<Stop color="#15596e" offset="1.0" />
</stops>
</LinearGradient>
</fill>
</Rectangle>
<ImageView fx:id="logo" fitHeight="411.0" fitWidth="606.0" layoutX="13.0" layoutY="13.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#../../../../Downloads/myStudio.png" />
</image>
</ImageView>
<TableView fx:id="artistTable" layoutX="316.0" layoutY="143.0" prefHeight="223.0" prefWidth="241.0">
<columns>
<TableColumn fx:id="artistName" editable="false" prefWidth="240.0" resizable="false" text="Artists" />
</columns>
</TableView>
<HBox fx:id="buttons" layoutX="65.0" layoutY="339.0" prefHeight="100.0" prefWidth="200.0" spacing="20.0">
<children>
<Button fx:id="newArtist" mnemonicParsing="false" prefWidth="75.0" text="New Artist" />
<Button fx:id="closeScreen" mnemonicParsing="false" prefWidth="75.0" text="Close" />
</children>
</HBox>
</children>
</Group>
Thanks
There seem to be many errors in your code.
First, you have made artistTable static. Don't do this - it makes no sense at all, and static fields won't be injected by the FXMLLoader. This is why you are getting the null pointer exception.
Second, the value you pass to the PropertyValueFactory ("Artist") does not match the name of any property in your model class Artist. (I.e. there is no ArtistProperty() method and no getArtist() method).
You probably want
artistName.setCellValueFactory(
new PropertyValueFactory<Artist,String>("name"));
which will tie the value for the column to the getName() method. See the PropertyValueFactory documentation for a description of how it works.
(You should probably define your POJO according to the JavaFX Property pattern described here. However just having a get...() method will work.)
my code is working to 90% I think.
The Output is right, but not all columns are shown in the tableview.
I don't know where the problem is.
The fx:id is right, the code too, I believe.
Here's a picture of the openend program. I will give you also my output an my controller an table-code. The launching code isn't important.
Picture:
http://www.directupload.net/file/d/3791/aitj4rff_png.htm
Output:
*** Loaded Oracle-Driver ***
*** Connected with Database ***
Film: Hugo Gesehen: JA
Film: FAST and FURIOS 6 Gesehen: JA
Film: Emil Gesehen: NEIN
Film: DAS_BOOT Gesehen: JA
*** Database data saved to Observable List named 'data'
*** Table Items setted ***
table_controller:
package controller;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import oracle.jdbc.*;
import model.filmtable_data;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
#SuppressWarnings("unused")
public class table_controller implements Initializable {
private ObservableList<filmtable_data> filmData = FXCollections.observableArrayList();
#FXML
private TableView<filmtable_data> FilmTable;
#FXML
private TableColumn<filmtable_data, String> Filmtitel_Col;
#FXML
private TableColumn<filmtable_data, Integer> ID_Col;
#FXML
private TableColumn<filmtable_data, String> Gesehen_Col;
#Override
public void initialize(URL location, ResourceBundle resources) {
// Observable List
ID_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, Integer>("rID"));
Filmtitel_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, String>("rFilmtitel"));
Gesehen_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, String>("rGesehen"));
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("*** Loaded Oracle-Driver ***");
} catch (ClassNotFoundException e1) {
System.out.println("Driver-Loading failed.");
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:lukas/1234#10.140.79.39:1521:OTTO");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("SELECT FILMTITEL, GESEHEN FROM LUKA1");
String filmtitel = "empty";
String gesehen = "empty";
int zaehler = 1;
System.out.println("*** Connected with Database ***");
while (resultset.next()) {
filmtitel = resultset.getString("FILMTITEL");
gesehen = resultset.getString("GESEHEN");
System.out.println("Film: " + filmtitel + "\t\t\tGesehen: " + gesehen);
filmtable_data entry = new filmtable_data(zaehler, filmtitel, gesehen);
filmData.add(entry);
zaehler++;
}
System.out.println("*** Database data saved to Observable List named 'data'");
FilmTable.setItems(filmData);
System.out.println("*** Table Items setted ***");
statement.close();
} catch (SQLException e) {
System.out.println("Login fehlgeschlagen.");
e.printStackTrace();
}
}
}
filmtable_data:
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class filmtable_data {
private final SimpleIntegerProperty rID;
private final SimpleStringProperty rFilmtitel;
private final SimpleStringProperty rGesehen;
public filmtable_data (Integer sID, String sFilmtitel, String sGesehen) {
this.rID = new SimpleIntegerProperty(sID);
this.rFilmtitel = new SimpleStringProperty(sFilmtitel);
this.rGesehen = new SimpleStringProperty(sGesehen);
}
public Integer getRID() {
return rID.get();
}
public void setRID(int set) {
rID.set(set);
}
public String getRFilmtitel() {
return rFilmtitel.get();
}
public void setRFilmtitel(String set) {
rFilmtitel.set(set);
}
public String setRGesehen() {
return rGesehen.get();
}
public void setRGesehen(String set) {
rGesehen.set(set);
}
}
the fx-file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="366.0" prefWidth="268.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.table_controller">
<children>
<TableView fx:id="FilmTable" prefHeight="366.0" prefWidth="425.0">
<columns>
<TableColumn fx:id="ID_Col" minWidth="-Infinity" prefWidth="43.0" text="ID" />
<TableColumn fx:id="Filmtitel_Col" prefWidth="137.0" text="Filmtitel" />
<TableColumn fx:id="Gesehen_Col" prefWidth="137.0" text="Gesehen" />
</columns>
</TableView>
</children>
</AnchorPane>
You have a typo in your POJO class, and there is not getter:
This is wrong:
public String setRGesehen() {
return rGesehen.get();
}
It should be:
public String getRGesehen() {
return rGesehen.get();
}
Notice you should add also the property methods, like:
public StringProperty rGesehenProperty() {
return rGesehen;
}
Even with the wrong getter, as the PropertyValueFactory looks first for the property, it would have worked.
I have this problem and I'm really going crazy without having a result.
I have a form and all fields are required through validator.xml
My form contains a field for the upload image (required)
When I click the submit button present a paggina waiting through (execAndWait configured in struts.xml).
my big problem is this:
the waiting page always redirect to my form page with text (the file field and mandatory).
Here is the code:
/register.jsp
<!-- al submit chiama l'action register -->
<action name="register" class="action.Register" method="execute" >
<interceptor-ref name="defaultStack" />
<interceptor-ref name="fileUpload">
<param name="maximumSize">10000000</param>
<param name="allowedTypes">image/jpeg,image/gif,image/jpg</param>
</interceptor-ref>
<interceptor-ref name="params"></interceptor-ref>
<interceptor-ref name="execAndWait">
</interceptor-ref>
<result name="success">index.jsp</result>
<result name="input">/register.jsp</result>
<result name="wait">/test.jsp</result>
</action>
waiting page:
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />"/>
</head>
<body>
<p>your request is processing...</p>
<img src="images/indicator.gif"/>
my form:
<s:form method="post" action="register" validate="false" enctype="multipart/form-data">
<s:textfield key="utenteBean.nome" name="utenteBean.nome" value="a" />
<s:textfield key="utenteBean.nickname" name="utenteBean.nickname" value="a" />
<sj:datepicker key="utenteBean.nato" name="utenteBean.nato"
showButtonPanel="true" displayFormat="dd/mm/yy" value="25/09/1983"/>
<s:textfield key="utenteBean.professione" name="utenteBean.professione" value="a"/>
<s:textfield key="utenteBean.eta" name="utenteBean.eta" value="3"/>
<s:textfield key="utenteBean.dj_preferito" name="utenteBean.dj_preferito" value="a" />
<s:textfield key="utenteBean.rave_fatti" name="utenteBean.rave_fatti" value="3" />
<s:textfield key="utenteBean.sito_preferito" name="utenteBean.sito_preferito" value="a" />
<s:textfield key="utenteBean.come_siveste" name="utenteBean.come_siveste" value="a" />
<s:textarea key="utenteBean.messaggio" name="utenteBean.messaggio" value="a"/>
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
really thanks for your help
I suppose that you have put wrong field name for the file tag. Can you show us your action class? Regarding to that instead of:
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
try to use:
<s:file label="file" name="utenteBean.file" requiredLabel="true"" ></s:file>
or just check in your action class the name of the file property.
yes sure ... below my Action class:
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private File file;
private String fileContentType;
private String fileFileName;
private String filesPath;
private ServletContext context;
Map<String, Object> session;
public String execute(){
if (file != null) {
File file = this.file;
// /System.out.println(file.getName());
try {
Util.saveFile(file, fileFileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate(){
if(this.fileFileName==null){
this.addFieldError("file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
Thank you so much for your help ...
I solved it by putting my bean in session. I could not find a better solution after many hours of work.
If other people have the same problem I can see the changes I made in my. Action
package action;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import Bean.UtenteBeanAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import Utility.Util;
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private ServletContext context;
Map<String, Object> session;
public String execute(){
session.put("utente", utenteBean);
if (utenteBean.getFile() != null) {
File file = utenteBean.getFile();
// /System.out.println(file.getName());
try {
Util.saveFile(file, utenteBean.getFileFileName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate() {
if (session.get("utente") != null) {
this.utenteBean = (UtenteBeanAction) session.get("utente");
}
if (this.utenteBean.getFileFileName() == null) {
this.addFieldError("utenteBean.file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
I hope I can be of help.
Thanks for the support.