I am trying to run a method in a controller class specified to a particular task, once a specified key is pressed using KeyListener. But i'm unable to detect the keypress and invoke the java.awt.event keyPressed method. My code is as follows :
public class POSController implements KeyListener {
#Override
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == com.sun.glass.events.KeyEvent.VK_F1) {
try {
paymentAction();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
What could have gone wrong? Thanks in advance.
Here is the minimal executable example of the problem.
public class POSController implements KeyListener {
#FXML
private TableView<Product> productTableView;
#FXML
private TableView<Item> listTableView;
#FXML
private MenuItem logoutItem, profile;
#FXML
private javafx.scene.image.ImageView backImage;
#FXML
private MenuButton menuButton;
#FXML
private TableColumn<Item, String> itemColumn;
#FXML
private ComboBox<String> clientId, paymentMethod;
#FXML
private TableColumn<Item, Double> priceColumn, totalColumn, discountPercentageColumn, amountColumn;
#FXML
private TableColumn<Item, Integer> quantityColumn;
#FXML
private TableColumn<Product, String> productColumn;
#FXML
private TextField searchField,discountPercentage,productField,priceField,quantityField,vatPercentage,subTotalField,discountField,totalVatField,vatField,netPayableField,totalDiscountField;
#FXML
private TextField ;
#FXML
private TextField ;
#FXML
private TextField ;
#FXML
private TextField ;
#FXML
private TextArea descriptionArea;
#FXML
private Button addButton, removeButton, paymentButton, resetTableButton, resetButton;
#FXML
private Label quantityLabel, errorLabel, userName, backLabel;
#FXML
private ObservableList<Item> ITEMLIST;
public static Scene paymentScene;
private double xOffset = 0;
private double yOffset = 0;
public static double finalNetPayablePrice = 0.0;
public static double finalSubTotalPrice = 0.0;
public static double finalVat = 0.0;
public static double finalDiscount = 0.0;
public static String clientName = null;
public static String selectedPaymentMethod = null;
public static List<String> itemNames = new ArrayList<>();
public static List<Double> itemDiscounts = new ArrayList<>();
public static List<String> prices = new ArrayList<>();
public static List<String> quantities = new ArrayList<>();
public static List<String> subTotals = new ArrayList<>();
public static ObservableList<Item> itemList;
public static List<String> columnItemData = new ArrayList<>();
public static List<String> columnQuantityData = new ArrayList<>();
#FXML
private void initialize() throws SQLException, ClassNotFoundException, IOException {
ObservableList<Product> productsData = ProductDAO.searchGoodProducts(app.values.getProperty("STATUS_TYPE1"));
populateProducts(productsData);
}
#FXML
private void populateProducts(ObservableList<Product> productData) throws ClassNotFoundException {
productTableView.setItems(productData);
}
#Override
public void keyTyped(java.awt.event.KeyEvent e) {
}
#Override
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_F1) {
try {
paymentAction();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void keyReleased(java.awt.event.KeyEvent e) {
}
#FXML
public void paymentAction() throws Exception {
if (validateInputsForPayment()) {
Payment payment = new Payment();
FXMLLoader loader = new FXMLLoader((getClass().getResource(app.values.getProperty("INVOICE_VIEW_LOCATION"))));
Parent root = loader.load();
Stage stage = new Stage();
root.setOnMousePressed((MouseEvent e) -> {
xOffset = e.getSceneX();
yOffset = e.getSceneY();
});
root.setOnMouseDragged((MouseEvent e) -> {
stage.setX(e.getScreenX() - xOffset);
stage.setY(e.getScreenY() - yOffset);
});
Scene scene = new Scene(root);
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setScene(scene);
this.paymentScene = scene;
stage.showAndWait();
}
}
You shouldn't be using java.awt.event.KeyListener for a JavaFX application. JavaFX has its own set of event API.
Assuming that POSController is a controller class for a particular FXML:
public class POSController {
#FXML private BorderPane root; // Or any other Node from FXML file
#FXML private void initialize() {
javafx.event.EventHandler<javafx.scene.input.KeyEvent> handler = event -> {
if (event.getCode() == javafx.scene.input.KeyCode.F1) {
try {
paymentAction();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
// I'm using root to get scene, but any node would be fine
if (root.getScene() != null) {
root.getScene().addEventHandler(javafx.scene.input.KeyEvent.KEY_PRESSED, handler);
}
else {
root.sceneProperty().addListener((obs, oldScene, newScene) -> {
if (newScene != null) {
root.getScene().addEventHandler(javafx.scene.input.KeyEvent.KEY_PRESSED, handler);
}
});
}
}
}
This will add the key event to the Scene. If you do not need to apply this event scene-wide, then you can add the event handler at other appropriate nodes.
Update
If there are any input controls in the scene, then you may need to use setEventFilter() instead of setEventHandler(). This is because those controls are probably going to consume the key event during the event bubbling phase.
Related
Let's say I've got 3 views and 3 controllers:
LogInController, LogInView
MainMenuController, MainMenuView
ListOfPatientsInternalMedicineController, ListOfPatientsInternalMedicineView.
An internalMedicineButtonClicked method change my scene to another (with some other content) but in this new scene, I want to have a button which allows me to go back to MainMenu (goBacktoMainMenuButtonClicked() method). And here occures my problem. How am I able to get reference to MainMenuController (the one which is corresponding with fxml file, created in LogInController) to fill setController() method.
public class LogInController {
MainMenuController mainMenuController = new MainMenuController();
#FXML
private JFXTextField logInTextField;
#FXML
private JFXButton logInButton;
#FXML
private JFXPasswordField passwordTextField;
#FXML
void logInButtonClicked(ActionEvent event) throws IOException {
LogInDAO logInDAO = new LogInDAO();
if(logInDAO.checkIfLoginAndPasswordIsCorrect(logInTextField.getText(),passwordTextField.getText()))
{
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/MainMenu.fxml"));
Window window = logInButton.getScene().getWindow();
Stage stage = (Stage) window;
loader.setController(mainMenuController); // here i'm passing original controller corresponding with fmxl
stage.setScene(new Scene(loader.load()));
}
else
{
(...)
}
}
}
MainMenuCotroller class:
public class MainMenuController {
ContentOfPatientTableView patientTableViewModel = new ContentOfPatientTableView();
(..)
#FXML
void internalMedicineButtonClicked(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/ListOfPatientsInternalMedicineView.fxml"));
Button button = (Button) event.getSource();
Scene scene = button.getScene();
Stage stage = (Stage) scene.getWindow();
loader.setController(new ListOfPatientsInternalMedicineController(patientTableViewModel));
stage.setScene(new Scene(loader.load()));
}
And ListOfPatientsInternalMedicineController class;
public class ListOfPatientsInternalMedicineController {
IPatientDAO patientDAO = new PatientDAO();
ContentOfPatientTableView patientTableViewModel;
public ListOfPatientsInternalMedicineController(ContentOfPatientTableView content) {
patientTableViewModel=content;
}
#FXML
public void goBacktoMainMenuButtonClicked(ActionEvent event)
{
FXMLLoader loader = new FXMLLoader(MainMenuController.class.getResource("/fxml/MainMenuView.fxml");
loader.setController(?????????); // Here if I will pass new MainController() i will create new instance, not this which is corresponding with fxml file. How am I able to refer to instance MainController created in LogInController ?
}
}
Consider using another model to represent the current view. You could implement this along the following lines:
public class ViewState {
private final ContentOfPatientTableView patientTableViewModel ;
private final ReadOnlyObjectWrapper<Parent> currentView = new ReadOnlyObjectWrapper<>();
private Parent logInView ;
private Parent mainMenuView ;
private Parent listOfPatientsMainMedicineView ;
public ViewState(ContentOfPatientTableView patientTableViewModel) {
this.patientTableViewModel = patientTableViewModel ;
}
public ReadOnlyObjectProperty<Parent> currentViewProperty() {
return currentView.getReadOnlyProperty();
}
public void showLogIn() {
if (logInView == null) {
try {
FXMLLoader loader = new FXMLLoader("/fxml/LogIn.fxml");
loader.setController(new LogInController(this));
logInView = loader.load();
} catch (IOException exc) {
// fatal...
throw new UncheckedIOException(exc);
}
}
currentView.set(logInView);
}
public void showMainMenu() {
// similarly...
}
public void showListOfPatientsMainMedicineView() {
// ...
}
}
Now your LogInController can do:
public class LogInController {
private final ViewState viewState ;
#FXML
private JFXTextField logInTextField;
#FXML
private JFXButton logInButton;
#FXML
private JFXPasswordField passwordTextField;
public LogInController(ViewState viewState) {
this.viewState = viewState ;
}
#FXML
void logInButtonClicked(ActionEvent event) {
LogInDAO logInDAO = new LogInDAO();
if(logInDAO.checkIfLoginAndPasswordIsCorrect(logInTextField.getText(),passwordTextField.getText()))
{
viewState.showMainMenu();
}
else
{
(...)
}
}
}
Similarly,
public class MainMenuController {
private final ViewState viewState ;
public MainMenuController(ViewState viewState) {
this.viewState = viewState ;
}
#FXML
void internalMedicineButtonClicked(ActionEvent event) throws IOException {
viewState.showListOfPatientsMainMedicineView();
}
}
and similarly for the other controller.
Note that you are instantiating each controller in ViewState, so just give that class access to each of the other models it may need.
Finally, you boot all this up with
public class MyApp extends Application {
#Override
public void start(Stage primaryStage) {
ViewState viewState = new ViewState(/* pass models here...*/);
viewState.showLogIn();
Scene scene = new Scene(viewState.currentViewProperty().get());
scene.rootProperty().bind(viewState.currentViewProperty());
primaryStage.setScene(scene);
primaryStage.show();
}
}
Ok, so I'm building this tiny JavaFX app and one of the things that have
bugged me was that while some of my stages would have that "enlarge-then-fade-out" animation on triggering close().
The close in particular is the last line of code in this code block:
#FXML
public void logout() throws SQLException {
Stage stage = ((Stage) logout_button.getScene().getWindow());
stage.close();
Main.loginStage.show();
}
Main.loginStage.close();
Here is that method's class
public class ListController {
#FXML private ImageView profImg;
#FXML private Button logout_button;
#FXML private TableView<Child> table;
#FXML private TableColumn col_name;
#FXML private TableColumn col_picture;
//TO BE MOVED TO EXTERNAL CLASS
private static Database db;
#FXML
public void initialize() {
db = new Database();
try {
initTable();
} catch (SQLException e){
System.out.println("loading failed");
}
initAvatar();
disableReorder();
}
private void initAvatar() {
profImg.setClip(ImageUtils.getAvatarCircle());
Image value = new Image("file:///" + GlobalInfo.getCurrProfImg().getAbsolutePath());
profImg.setImage(value);
}
public void initTable() throws SQLException {
db.init();
table.setRowFactory(new Callback<TableView<Child>, TableRow<Child>>() {
#Override
public TableRow<Child> call(TableView<Child> param) {
TableRow<Child> row = new TableRow<>();
row.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
System.out.println(row.getItem().getId());
}
});
return row;
}});
table.setItems(db.getChildren());
col_picture.setCellValueFactory(new PropertyValueFactory<Child, File>("image"));
col_picture.setCellFactory(new Callback<TableColumn<Child, File>, TableCell<Child, File>>() {
#Override
public TableCell call(TableColumn param) {
return new TableCell<Child, File>() {
ImageView imageView = new ImageView();
Image childImage;
#Override
protected void updateItem(File item, boolean empty) {
if (item != null) {
childImage = new Image("file:///" + item.getAbsolutePath());
imageView.setImage(childImage);
imageView.setClip(ImageUtils.getAvatarCircle());
imageView.setFitHeight(65);
imageView.setFitWidth(65);
HBox hBox = new HBox(imageView);
hBox.setAlignment(Pos.CENTER);
setGraphic(hBox);
}
}
};
}
});
col_name.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Child, String>, ObservableValue>() {
#Override
public ObservableValue call(TableColumn.CellDataFeatures<Child, String> param) {
Child child = param.getValue();
String firstName = child.getfName();
String lastName = child.getlName();
String nickname = child.getNickname();
String placeholder = "PLACEHOLDER"; //Place holder for adding nickname if exists
String complete = firstName + placeholder + lastName;
//place nickname between first and last name if exists
if (nickname.length() != 0){
String nicknameString = " \"" + nickname + "\" ";
complete = complete.replace(placeholder, nicknameString);
//if nickname does not exist
} else {
complete = complete.replace(placeholder, "");
}
return new SimpleStringProperty(complete);
}
});
col_name.setCellFactory(new Callback<TableColumn<Child, String>, TableCell<Child, String>>() {
#Override
public TableCell call(TableColumn<Child, String> param) {
return new TableCell<Child, String>() {
#Override
protected void updateItem(String item, boolean empty) {
setText(item);
setAlignment(Pos.CENTER);
}
};
}
});
}
private void disableReorder() {
table.widthProperty().addListener((observable, oldValue, newValue) -> {
TableHeaderRow row = ((TableHeaderRow) table.lookup("TableHeaderRow"));
row.reorderingProperty().addListener((observable1, oldValue1, newValue1) -> row.setReordering(false));
}); //Fuck you oracle
}
#FXML
public void logout() throws SQLException {
Stage stage = ((Stage) logout_button.getScene().getWindow());
stage.close();
Main.loginStage.show();
}
#FXML
public void showSettings() throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/settings.fxml"));
SettingsStage stage = new SettingsStage();
stage.setOnHidden((event) -> {
SettingsStage settingsStage = ((SettingsStage) event.getSource());
if (settingsStage.getChange()) {
initialize();
}
});
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.setTitle("Settings");
stage.initModality(Modality.APPLICATION_MODAL);
stage.showAndWait();
}
#FXML
public void showChildForm(ActionEvent actionEvent) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/childForm.fxml"));
Parent root = loader.load();
ChildFormController controller = loader.getController();
controller.setListController(this);
Scene scene = new Scene(root, 575, 675);
scene.getStylesheets().add(getClass().getResource("/css/persistent-prompt.css").toExternalForm());
Stage stage = new Stage();
stage.setResizable(false);
stage.setScene(scene);
stage.setTitle("Add child");
stage.initModality(Modality.APPLICATION_MODAL);
stage.showAndWait();
}
}
However, I have some form stages which do not display this "animation" upon calling close() instead they simply disappear from the window, which I have found jarring.
Here is the code run to close one of these faulty stages, with its respective class further below:
#FXML
public void cancel(ActionEvent actionEvent) {
Stage stage = ((Stage) submitBtn.getScene().getWindow());
stage.close();
}
public class ChildFormController extends FormHelper {
#FXML
private ImageView childImage;
#FXML
private Label imageName;
#FXML
private PersistentPromptTextField firstNameInput;
#FXML
private PersistentPromptTextField lastNameInput;
#FXML
private PersistentPromptTextField nickNameInput;
#FXML
private PersistentPromptTextField birthPlaceInput;
#FXML
private PersistentPromptTextField referrerInput;
#FXML
private DatePicker birthDateInput;
#FXML
private DatePicker admissionDateInput;
#FXML
private Button submitBtn;
#FXML
private ComboBox childStatus;
//TWO SCOOPS TWO GENDERS TWO TERMS
#FXML
private ToggleGroup genderToggleGroup;
#FXML
private TextArea childDescInput;
#FXML
private Label warnEmptyLabel;
private FileInputStream slctdImgStrm;
private String pathRef;
private Parent nextParent;
private ChildParentsController childParentsController;
private ListController listController;
#FXML
public void initialize() throws FileNotFoundException {
//Init gender choice buttons and scene ref
//OMG MY PATRIARCHY
genderToggleGroup.getToggles().get(0).setSelected(true);
childStatus.getSelectionModel().selectFirst();
//Init default image for child
File defaultFile = new File("src\\main\\resources\\imgs\\default_avatar.png");
updateChosenImage(defaultFile);
//Init submit/next btn
initNextBtn();
childStatus.getSelectionModel().selectedIndexProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.intValue() == 2) {
initSubmitBtn();
} else if (newValue.intValue() != 2 && oldValue.intValue() == 2) {
initNextBtn();
}
});
birthDateInput.valueProperty().addListener((observable, oldValue, newValue) -> {
if (admissionDateInput.getValue() != null) {
if (newValue.isAfter(admissionDateInput.getValue())) {
birthDateInput.setValue(admissionDateInput.getValue());
}
}
});
admissionDateInput.valueProperty().addListener(((observable, oldValue, newValue) -> {
if (birthDateInput.getValue() != null) {
if (admissionDateInput.getValue().isBefore(birthDateInput.getValue())) {
admissionDateInput.setValue(birthDateInput.getValue());
}
}
}));
}
private void initNextBtn() {
submitBtn.setText("Next");
submitBtn.getStyleClass().remove("submit");
submitBtn.getStyleClass().add("default");
submitBtn.setOnAction(event -> initParentForm());
}
private void initParentForm() {
if (formIsIncomplete())
return;
try {
if (nextParent == null) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/childParentsForm.fxml"));
Parent root = loader.load();
childParentsController = loader.getController();
setNextParent(root);
}
submitBtn.getScene().setRoot(nextParent);
childParentsController.setPrevRoot(submitBtn.getParent());
childParentsController.setChildFormController(this);
} catch (IOException e) {
e.printStackTrace();
DialogUtils.displayExceptionError(e, "Severe error!");
}
}
private void initSubmitBtn() {
submitBtn.setText("Submit");
submitBtn.getStyleClass().remove("default");
submitBtn.getStyleClass().add("submit");
submitBtn.setOnAction(event -> submit(true));
}
#FXML
public void cancel(ActionEvent actionEvent) {
Stage stage = ((Stage) submitBtn.getScene().getWindow());
stage.close();
}
/**
* Submits the child with all of its respecitve information
* #param active if this controller's scene is active
* #return id of child submitted, negative number if submission has failed
*/
public int submit(boolean active) {
if (formIsIncomplete())
return -1;
//Fetch first part of user input
String firstName = firstNameInput.getText();
String lastName = lastNameInput.getText();
String nickName = nickNameInput.getText();
String place_of_birth = birthPlaceInput.getText();
String childDesc = childDescInput.getText();
String referrer = referrerInput.getText();
int gender = genderToggleGroup.getToggles().indexOf(genderToggleGroup.getSelectedToggle());
int status = childStatus.getSelectionModel().getSelectedIndex();
//Get child's birthdate and admission_date date
LocalDate birthDate = birthDateInput.getValue();
LocalDate admissionDate = admissionDateInput.getValue();
//Fire up db helper and insert new child record
Database db = new Database();
//Retrieve record's ID for later use
int id;
try {
//Add record for child and retrieve its id
db.init();
db.addNewChild(firstName, lastName, nickName, place_of_birth, birthDate, childDesc, gender, referrer, status, admissionDate);
//Retrieve id for use in storing img
id = db.getChildIDOf(firstName, lastName, nickName, place_of_birth, birthDate, childDesc, gender, referrer, status, admissionDate);
if (id == -89) throw new SQLException();
File strgReg = new File(pathRef.replace("id", String.valueOf(id)));
//Store img file for child avatar
if (!(strgReg.exists() && strgReg.isFile())) {
strgReg.getParentFile().mkdirs();
strgReg.createNewFile();
}
Files.copy(slctdImgStrm, Paths.get(strgReg.getPath()), StandardCopyOption.REPLACE_EXISTING);
db.updateImageOf(id, strgReg.getPath(), table_children.name);
} catch (SQLException e) {
e.printStackTrace();
DialogUtils.displayError("Error saving child data", "There was an error in saving all child data. Please try again!");
return -1;
} catch (IOException e) {
e.printStackTrace();
DialogUtils.displayError("Error saving image", "There was an error saving the image of the child. " +
"All other data besides the image has been saved. Please attempt to add the child image in its own page.");
return -1;
}
refreshList();
if (active) {
firstNameInput.getScene().getWindow().hide();
}
return id;
}
private boolean formIsIncomplete() {
//Clear warning labels
warnEmptyLabel.setStyle("-fx-text-fill: transparent");
//Indicates that form is incomplete
boolean incomplete = false;
//Fetches textfield nodes from root
try {
List<Node> textFields = NodeUtils.getAllNodesOf(childImage.getParent(), new ArrayList<>(),
"javafx.scene.control.TextInputControl");
//Go mark each incomplete form
for (Node n : textFields) {
TextInputControl text = ((TextInputControl) n);
String[] ids;
if (text.getId() == null) {
ids = new String[] {"birthDateWarning", "admissionDateWarning"};
} else {
ids = new String[] {text.getId().replace("Input", "Warning")};
}
//Manipulate warning label if current node is NOT nickname textfield
if (!ids[0].contains("nick")) {
for (int i = 0; i < ids.length; i++) {
Label warning = ((Label) childImage.getParent().lookup("#" + ids[i]));
if (text.getText().isEmpty()) {
warning.setStyle("-fx-text-fill: red");
incomplete = true;
} else {
warning.setStyle("-fx-text-fill: transparent ");
}
}
}
}
//Notify user that form is incomplete
if (incomplete) warnEmptyLabel.setStyle("-fx-text-fill: red");
} catch (ClassNotFoundException e) {
e.printStackTrace();
DialogUtils.displayExceptionError(e, "An error has occurred! Please contact the developer for assistance!");
}
return incomplete;
}
#FXML
public void changeChildImg(ActionEvent actionEvent) {
FileChooser chooser = new FileChooser();
File chosen = chooser.showOpenDialog(firstNameInput.getScene().getWindow());
if (chosen == null) return;
try {
updateChosenImage(chosen);
} catch (IOException e) {
DialogUtils.displayError("File error", "There was an error selecting your chosen file, please try again");
e.printStackTrace();
}
}
private void updateChosenImage(File chosen) throws FileNotFoundException {
slctdImgStrm = new FileInputStream(chosen);
childImage.setImage(new Image(slctdImgStrm));
imageName.setText(chosen.getName());
pathRef = GlobalInfo.getChildrenImgDir() + "\\"+ chosen.getName();
slctdImgStrm = new FileInputStream(chosen);
}
private void refreshList() {
try {
listController.initTable();
} catch (SQLException e) {
DialogUtils.displayError("Synchronization error!", "There was an error synchronizing the data of the new child!");
e.printStackTrace();
}
}
public void setNextParent(Parent nextParent) {
this.nextParent = nextParent;
}
public void setListController(ListController listController) {
this.listController = listController;
}
Does anybody have any idea on what's causing this problem? Any searches on SO yield questions about fading the stage in and out which is not what I want.
All it's ok when i open light weight's pages but when i wan't to open some bigger the GUI blocks and not responding until the site load's. I try to give it to background thread but it's not working.
MainWindowController:
WebControl webcontroller = new WebControl();
DatabaseControl datacontroller;
#FXML
private ToggleButton PowypadkoweBt;
#FXML
private ToggleButton UszkodzoneBt;
#FXML
private ToggleButton MailBt;
#FXML
private ToggleButton SMSBt;
#FXML
private Button SendBt;
#FXML
private ScrollPane WynikiScroll;
#FXML
private TableView DoneTable;
#FXML
private TableColumn CheckCol, OpisCol, LoginCol;
#FXML
private TextArea MessageArea;
#FXML
private WebView WebControl;
#FXML
private Button NEXT;
#FXML
private Button PREVIOUS;
#FXML
private Label PAGE;
#Override
public void initialize(URL url, ResourceBundle rb) {
this.CheckCol.setCellValueFactory(
new Callback<CellDataFeatures<UsedTableRow, Boolean>, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(CellDataFeatures<UsedTableRow, Boolean> param) {
return param.getValue().getCheckedProperty();
}
});
this.CheckCol.setCellFactory(CheckBoxTableCell.forTableColumn(this.CheckCol));
this.CheckCol.setEditable(false);
this.CheckCol.setMinWidth(50);
this.CheckCol.setMaxWidth(50);
this.OpisCol.setCellValueFactory(new PropertyValueFactory<UsedTableRow, String>("Description"));
this.LoginCol.setCellValueFactory(new PropertyValueFactory<UsedTableRow, String>("Login"));
ObservableList<UsedTableRow> data = FXCollections.observableArrayList();
try {
datacontroller = new DatabaseControl();
data.addAll(datacontroller.getRowsFromEntity());
} catch (ClassNotFoundException ex) {
Alert alert = new Alert(AlertType.WARNING);
alert.setContentText("Nie udało się nawiązać połączenia z bazą danych. Błąd klasy.");
alert.setHeaderText("Błąd klasy.");
alert.setTitle("Błąd");
alert.show();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.WARNING);
alert.setHeaderText("Błąd SQL.");
alert.setContentText("Nie udało się nawiązać połączenia z bazą danych. Błąd SQL.");
alert.setTitle("Błąd");
alert.show();
}
this.DoneTable.setItems(data);
this.WebControl.getEngine().load("http://otomoto.pl");
this.PAGE.setText((this.webcontroller.getIteratorAuctions() + this.webcontroller.getIteratorItems() - 10) + " z " + this.webcontroller.getItemsIds().size());
// loadNewSite();
this.WebControl.autosize();
this.WebControl.widthProperty().addListener(new ChangeListener<Object>() {
public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) {
Double width = (Double) newValue;
WebControl.setPrefWidth(width);
WebControl.autosize();
}
});
this.WebControl.requestLayout();
this.WebControl.setContextMenuEnabled(false);
this.WebControl.getEngine().setJavaScriptEnabled(true);
this.WebControl.getEngine().setUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36");
this.PowypadkoweBt.setSelected(true);
this.UszkodzoneBt.setSelected(true);
}
#FXML
private void PowypadkoweAction(ActionEvent event) {
if (this.PowypadkoweBt.isSelected()) {
this.webcontroller.refresh(true);
} else {
this.webcontroller.refresh(false);
}
loadNewSite();
}
#FXML
private void UszkodzoneAction(ActionEvent event) {
}
#FXML
private void SMSAction(ActionEvent event) {
}
#FXML
private void MailAction(ActionEvent event) {
}
#FXML
private void SendAction(ActionEvent event) {
}
#FXML
private void PREVIOUSAction(ActionEvent event) {
webcontroller.previousAuction();
loadNewSite();
}
#FXML
private void NEXTAction(ActionEvent event) {
webcontroller.nextAuction();
loadNewSite();
this.WebControl.autosize();
}
private void updateDoneTable() {
ObservableList<UsedTableRow> data = FXCollections.observableArrayList();
data.addAll(datacontroller.getRowsFromEntity());
this.DoneTable.getItems().clear();
this.DoneTable.setItems(data);
}
private void loadNewSite() {
Service<Void> service = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
//Background work
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
WebControl.getEngine().load(webcontroller.getSelectedURL());
PAGE.setText((webcontroller.getIteratorAuctions() + webcontroller.getIteratorItems() - 10) + " z " + webcontroller.getItemsIds().size());
} finally {
latch.countDown();
}
}
});
latch.await();
//Keep with the background work
return null;
}
};
}
};
service.start();
/* Task task = new Task(new Runnable() {
#Override
public void run() {
WebControl.getEngine().load(webcontroler.getSelectedURL());
}
});
tr.run();
this.PAGE.setText((this.webcontroler.getIteratorAuctions() + this.webcontroler.getIteratorItems() - 10) + " z " + this.webcontroler.getItemsIds().size());
*/
}}
CInsurance Application class :
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/cinsurance/MainWindow.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("/cinsurance/mainwindow.css").toExternalForm());
primaryStage.setTitle("Aplikacja Ubezpieczeniowa CInsurance");
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException ex) {
Logger.getLogger(CInsurance.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}}
Thanks for any help.
After i lost a lot of time on thinking why , i just continue to code modules for this application and i add some multithreading into initialize method of controller and ... it was very strange . Everything is working ok , even when i'm loading heavy page's. I still don't know why multithreading unlocks the blockade... but it can be also the change of JDK because i must change it to 32 bit form 64 bit. After all it is strange.
I'm having having trouble getting a correct output from tableview. I'm using a button to set one item from tableview to a label. However, it prints "StringProperty [Value pineapples]" where I would like it to be just "pineapples".
The tableview gives them correctly.
public class ProductListController implements Initializable {
#FXML public TableView<Model> tableview ;
#FXML private TableColumn<Model, Number> ProductID;
#FXML private TableColumn<Model, String> ProductName;
#FXML private TableColumn<Model, Number> ProductPrice;
#FXML private Label lblProduct;
#FXML private Label lblPrice;
#FXML
private void btnActionShow(ActionEvent event) {
assert tableview !=null : " ";
ProductID.setCellValueFactory(cellData -> cellData.getValue().ProductIDProperty());
ProductName.setCellValueFactory(cellData -> cellData.getValue().ProductNameProperty());
ProductPrice.setCellValueFactory(cellData -> cellData.getValue().ProductPriceProperty());
buildData();
}
private ObservableList<Model> data;
public void buildData(){
data = FXCollections.observableArrayList();
try{
Connection conn = DriverManager.getConnection
("jdbc:derby://localhost:1527/Stock", "*****", "*****");
Statement stmt = conn.createStatement();
String SQL = "SELECT * FROM PRODUCTS";
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
Model mod = new Model();
mod.ProductID.set(rs.getInt("ID"));
mod.ProductName.set(rs.getString("NAME"));
mod.ProductPrice.set(rs.getInt("SELL_PRICE"));
data.add(mod);
}
tableview.setItems(data);
}
catch ( SQLException err) {
System.out.println(err.getMessage() );
}
}
//Button to fetch data from Tableview. Sets the data not the way I want.
#FXML
private void btnConfirmAction(ActionEvent event) {
Model model = tableview.getSelectionModel().getSelectedItem();
String prd;
prd = model.getProductName().toString();
lblProduct.setText(prd);
}
#FXML
private void btnNextAction(ActionEvent event) {
try{
FXMLLoader loader = new FXMLLoader(getClass().getResource("/appl/Discount.fxml"));
Parent parent = loader.load();
DiscountController discountcontr = loader.getController();
discountcontr.setProduct(tableview.getSelectionModel().getSelectedItem().getProductName().toString());
Stage stage = new Stage();
Scene scene = new Scene(parent);
stage.setScene(scene);
stage.show();
}
catch(IOException e){
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
}
Model
public class Model {
public SimpleIntegerProperty ProductID = new SimpleIntegerProperty();
public SimpleStringProperty ProductName = new SimpleStringProperty ();
public SimpleIntegerProperty ProductPrice = new SimpleIntegerProperty();
private final SimpleBooleanProperty Checked = new SimpleBooleanProperty(false);
public SimpleBooleanProperty checkedProperty() {
return this.Checked;
}
public java.lang.Boolean getChecked() {
return this.checkedProperty().get();
}
public void setChecked(final java.lang.Boolean checked) {
this.checkedProperty().set(checked);
}
public SimpleIntegerProperty getProductID() {
return ProductID;
}
public SimpleStringProperty getProductName() {
return ProductName;
}
public SimpleIntegerProperty getProductPrice() {
return ProductPrice;
}
Since getProductName() returns a SimpleStringProperty, you need to retrieve the String from it using the get(). Just use :
String prd = model.getProductName().get();
Your model is implemented incorrectly. You should use the following pattern:
public class Model {
private SimpleStringProperty productName = new SimpleStringProperty();
public SimpleStringProperty productNameProperty() {
return productName ;
}
public final String getProductName() {
return productNameProperty().get();
}
public final void setProductName(String productName) {
productNameProperty().set(productName);
}
}
and similarly for the other properties.
If you use the e(fx)clipse plugin, you can generate the methods automatically from the property definition by right-clicking, choosing "Source" and then "Generate JavaFX Getters and Setters". I think NetBeans has similar functionality.
I have the following problem. When I press the Button, I execute a Service that parses an html page and puts the results in a table. When I click on the table, while the Service is running, the Service will be terminated.
Can someone help me with this problem?
Here is my controller class:
public class ProxySearchController implements Initializable {
private Scene scene;
#FXML
private Button btn_refresh;
#FXML
private TableView<ProxyResult> tbl_results;
#FXML
private ProgressBar pb_search;
#FXML
private TableColumn<ProxyResult, String> column_ip;
#FXML
private TableColumn<ProxyResult, Integer> column_port;
#FXML
private TableColumn<ProxyResult, Locale> column_locale;
#FXML
private TableColumn<ProxyResult, String> column_anonymity;
#FXML
private TableColumn<ProxyResult, Boolean> column_google;
#FXML
private TableColumn<ProxyResult, Boolean> column_https;
#FXML
private TableColumn<ProxyResult, String> column_lastchecked;
#FXML
private TableColumn<ProxyResult, Long> column_response;
private ObservableList<ProxyResult> data = FXCollections.observableArrayList();
/*
* (non-Javadoc)
*
* #see javafx.fxml.Initializable#initialize(java.net.URL, java.util.ResourceBundle)
*/
#Override
public void initialize(URL location, ResourceBundle resources) {
tbl_results.setItems(data);
tbl_results.getSelectionModel().setCellSelectionEnabled(true);
Clipboard clipboard = Clipboard.getSystemClipboard();
// add listner to your tableview selecteditemproperty
tbl_results.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ProxyResult>() {
#Override
public void changed(ObservableValue observable, ProxyResult oldValue, ProxyResult newValue) {
ObservableList<TablePosition> posList = tbl_results.getSelectionModel().getSelectedCells();
int old_r = -1;
StringBuilder clipboardString = new StringBuilder();
for (TablePosition p : posList) {
int r = p.getRow();
int c = p.getColumn();
Object cell = tbl_results.getColumns().get(c).getCellData(r);
if (cell == null)
cell = "";
if (old_r == r)
clipboardString.append('\t');
else if (old_r != -1)
clipboardString.append('\n');
clipboardString.append(cell);
old_r = r;
}
final ClipboardContent content = new ClipboardContent();
content.putString(clipboardString.toString());
Clipboard.getSystemClipboard().setContent(content);
}
});
column_ip.setCellValueFactory(new PropertyValueFactory<ProxyResult, String>("ip"));
column_port.setCellValueFactory(new PropertyValueFactory<ProxyResult, Integer>("port"));
column_locale.setCellValueFactory(new PropertyValueFactory<ProxyResult, Locale>("locale"));
column_anonymity.setCellValueFactory(new PropertyValueFactory<ProxyResult, String>("anonymity"));
column_google.setCellValueFactory(new PropertyValueFactory<ProxyResult, Boolean>("google"));
column_https.setCellValueFactory(new PropertyValueFactory<ProxyResult, Boolean>("https"));
column_lastchecked.setCellValueFactory(new PropertyValueFactory<ProxyResult, String>("lastChecked"));
column_response.setCellValueFactory(new PropertyValueFactory<ProxyResult, Long>("responseTime"));
}
public void handleSearchButton(ActionEvent event) {
Service<Void> searchWorker = new SearchProxyWorker(pb_search, data);
searchWorker.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Tadaaa");
}
});
searchWorker.start();
}
/**
* Set the current scene.
*
* #param scene A scene
*/
public void setScene(Scene scene) {
this.scene = scene;
}
}