Error : Running array of objects in JavaFX with same method - javafx

Here's the code :
Main File :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testobjectarray;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
*
*/
public class TestObjectArray extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application. main() serves only as fallback in case the application can not be launched through deployment artifacts, e.g., in IDEs
* with limited FX support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
myClass[] c = new myClass[5];
c[2].myMethod();
}
}
Class declared outside :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testobjectarray;
/**
*
*
*/
public class myClass {
public void myMethod(){
System.out.println("Inside myMethod");
}
}
Problem, I get errors when I compile i.e. initializing an array of objects and invoking the method. If I have just one object, it works great. Any help appreciated.

The problem with your code is you are initialising an array of size 5, but you never add values to it. Try the following code
myClass[] c = new myClass[5];
c[0] = new myClass();
c[1] = new myClass(); // and so on till c[4]
//now you can call the methods
c[1].myMethod();

Related

Netbeans 9 0 Java FX 10

Try creating a JavaFX application.
Don't add or modify any code.
Run the Project. It does not find the MAIN.
If you run the File, then it works.
However, create JavaFX FXML application. As mentioned earlier, don't make any change to the code.
Run the Package.... it WORKS.
Does anyone know why? I tried to report the problem, but that looked more complicated than writing the code. :)
I am enclosing generated code for a JAVAFX APPLICATION
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package forsubmission;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* #author Hornigold
*/
public class ForSubmission extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Thanks,
Gold

Javafx - populating table with xml file

I am fairly new to javafx and have been following a tutorial (http://code.makery.ch/library/javafx-8-tutorial/) where all my code has come from.
I am having an issue with populating a table with an xml file which I believe is because I want to switch scene first and then display the table on this new scene. In the guide they do it on just the first scene that loads, which if I do I can get to work fine, but when I want the table data to be viewable on a different scene, it doesn't seem to work. All I did was change where some of the code was located within the class to try to reflect this as I didn't want it on my first scene but now it won't display.
LibraryApp
package libraryapp;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import libraryapp.model.Book;
import libraryapp.model.BookListWrapper;
import libraryapp.view.HomeOverviewController;
import libraryapp.view.RootLayoutController;
public class LibraryApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
/**
* The data as an observable list of Books.
*/
private ObservableList<Book> bookData = FXCollections.observableArrayList();
/**
* Constructor
*/
public LibraryApp() {
// Add some sample data
bookData.add(new Book("Hans", "Muster"));
bookData.add(new Book("Ruth", "Mueller"));
bookData.add(new Book("Heinz", "Kurz"));
bookData.add(new Book("Cornelia", "Meier"));
bookData.add(new Book("Werner", "Meyer"));
bookData.add(new Book("Lydia", "Kunz"));
bookData.add(new Book("Anna", "Best"));
bookData.add(new Book("Stefan", "Meier"));
bookData.add(new Book("Martin", "Mueller"));
}
/**
* Returns the data as an observable list of Books.
* #return
*/
public ObservableList<Book> getBookData() {
return bookData;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("LibraryApp");
initRootLayout();
showHomeOverview();
}
/**
* Initializes the root layout and tries to load the last opened
* person file.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// Give the controller access to the main app.
RootLayoutController controller = loader.getController();
controller.setLibraryApp(this);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
// Try to load last opened person file.
File file = getBookFilePath();
if (file != null) {
loadBookDataFromFile(file);
}
}
/**
* Shows the book overview inside the root layout.
*/
public void showHomeOverview() {
try {
// Load home overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/HomeOverview.fxml"));
AnchorPane homeOverview = (AnchorPane) loader.load();
// Set home overview into the center of root layout.
rootLayout.setCenter(homeOverview);
// Give the controller access to the main app.
HomeOverviewController controller = loader.getController();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the main stage.
* #return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
/**
* Returns the book file preference, i.e. the file that was last opened.
* The preference is read from the OS specific registry. If no such
* preference can be found, null is returned.
*
* #return
*/
public File getBookFilePath() {
Preferences prefs = Preferences.userNodeForPackage(LibraryApp.class);
String filePath = prefs.get("filePath", null);
if (filePath != null) {
return new File(filePath);
} else {
return null;
}
}
/**
* Sets the file path of the currently loaded file. The path is persisted in
* the OS specific registry.
*
* #param file the file or null to remove the path
*/
public void setBookFilePath(File file) {
Preferences prefs = Preferences.userNodeForPackage(LibraryApp.class);
if (file != null) {
prefs.put("filePath", file.getPath());
// Update the stage title.
primaryStage.setTitle("LibraryApp - " + file.getName());
} else {
prefs.remove("filePath");
// Update the stage title.
primaryStage.setTitle("LibraryApp");
}
}
/**
* Loads book data from the specified file. The current book data will
* be replaced.
*
* #param file
*/
public void loadBookDataFromFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(BookListWrapper.class);
Unmarshaller um = context.createUnmarshaller();
// Reading XML from the file and unmarshalling.
BookListWrapper wrapper = (BookListWrapper) um.unmarshal(file);
bookData.clear();
bookData.addAll(wrapper.getBooks());
// Save the file path to the registry.
setBookFilePath(file);
} catch (Exception e) { // catches ANY exception
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not load data");
alert.setContentText("Could not load data from file:\n" + file.getPath());
alert.showAndWait();
}
}
/**
* Saves the current book data to the specified file.
*
* #param file
*/
public void saveBookDataToFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(BookListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping our book data.
BookListWrapper wrapper = new BookListWrapper();
wrapper.setBooks(bookData);
// Marshalling and saving XML to the file.
m.marshal(wrapper, file);
// Save the file path to the registry.
setBookFilePath(file);
} catch (Exception e) { // catches ANY exception
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
}
HomeOverViewController
package libraryapp.view;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import libraryapp.view.BrowseController;
public class HomeOverviewController implements Initializable {
#FXML
private AnchorPane homePane;
#FXML
private void goToBrowse(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("Browse.fxml"));
homePane.getChildren().setAll(pane);
}
#FXML
private void goToManageAccount(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("ManageAccount.fxml"));
homePane.getChildren().setAll(pane);
}
#FXML
public void logout(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("Login.fxml"));
homePane.getChildren().setAll(pane);
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
BrowseController
package libraryapp.view;
import java.io.File;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import libraryapp.LibraryApp;
import libraryapp.model.Book;
public class BrowseController {
#FXML
private TableView<Book> bookTable;
#FXML
private TableColumn<Book, String> titleColumn;
#FXML
private Label titleLabel;
#FXML
private Label authorLabel;
#FXML
private Label isbnLabel;
#FXML
private Label quantityLabel;
#FXML
private AnchorPane browsePane;
// Reference to the main application.
private LibraryApp libraryApp;
/**
* The constructor.
* The constructor is called before the initialize() method.
*/
public BrowseController() {
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
#FXML
private void initialize() {
// Initialize the book table
titleColumn.setCellValueFactory(
cellData -> cellData.getValue().titleProperty());
// Clear person details.
showBookDetails(null);
// Listen for selection changes and show the person details when changed.
bookTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> showBookDetails(newValue));
}
/**
* Is called by the main application to give a reference back to itself.
*
* #param libraryApp
*/
public void setLibraryApp(LibraryApp libraryApp) {
this.libraryApp = libraryApp;
// Add observable list data to the table
bookTable.setItems(libraryApp.getBookData());
}
private void showBookDetails(Book book) {
if (book != null) {
// Fill the labels with info from the book object.
titleLabel.setText(book.getTitle());
authorLabel.setText(book.getAuthor());
isbnLabel.setText(book.getIsbn());
quantityLabel.setText(Integer.toString(book.getQuantity()));
} else {
// Book is null, remove all the text.
titleLabel.setText("");
authorLabel.setText("");
isbnLabel.setText("");
quantityLabel.setText("");
}
}
/**
* Called when the user clicks on the borrow button.
*/
#FXML
private void handleDeleteBook() {
int selectedIndex = bookTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
bookTable.getItems().remove(selectedIndex);
} else {
// Nothing selected.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(libraryApp.getPrimaryStage());
alert.setTitle("No Selection");
alert.setHeaderText("No book Selected");
alert.setContentText("Please select a book.");
alert.showAndWait();
}
}
#FXML
public void logout(ActionEvent event) throws IOException {
File bookFile = libraryApp.getBookFilePath();
libraryApp.saveBookDataToFile(bookFile);
AnchorPane pane = FXMLLoader.load(getClass().getResource("Login.fxml"));
browsePane.getChildren().setAll(pane);
}
}
The idea is that I want to press a button which calls goToBrowse which will load the Browse scene and then populate the table there with the data from the xml file. It goes to browse scene fine but does not populate the table.
Please excuse any messy code and any bad naming conventions as I am pretty new to this javafx stuff and have been trying to follow the tutorial that was mentioned before and tweak it to what I thought would be correct.
I believe it is the setLibraryApp that I want to be calling in the BrowseController, but what I have tried doesn't seem to work.

JavaFX - Turning off possible focus on TextArea

I have TextArea and TextField in my app. I have managed to give focus to TextField on the start and made TextArea impossible to edit. I want to also somehow turn off possibility to focus it with forexample mouse click or TAB cycling.
Is there any suitable way to do it?
You need to use:
textArea.setFocusTraversable(false);
textArea.setMouseTransparent(true);
Example demonstration :
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
* #author StackOverFlow
*
*/
public class Sample2 extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane pane = new BorderPane();
// Label
TextArea textArea1 = new TextArea("I am the focus owner");
textArea1.setPrefSize(100, 50);
// Area
TextArea textArea2 = new TextArea("Can't be focused ");
textArea2.setFocusTraversable(false);
textArea2.setMouseTransparent(true);
textArea2.setEditable(false);
// Add the items
pane.setLeft(textArea1);
pane.setRight(textArea2);
// Scene
Scene scene = new Scene(pane, 200, 200);
primaryStage.setScene(scene);
// Show stage
primaryStage.show();
}
/**
* Application Main Method
*
* #param args
*/
public static void main(String[] args) {
launch(args);
}

JavaFX don't send me to next scene

I want to move to next stage after Timer but when I run the page is frozen.
I want some help please to resolve this problem, I'm new in JavaFX .
I want to go to next screen after a specific time that I choose because this screen is a load screen
this is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chapitreapp;
import ressources.FadeInLeftTransition;
import ressources.FadeInRightTransition;
import ressources.FadeInTransition;
import ressources.config;
import ressources.config2;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.springframework.beans.*;
import org.springframework.context.*;
/**
* FXML Controller class
*
* #author anas
*/
public class LoadController implements Initializable {
#FXML
private Text lblWelcome;
#FXML
private Text lblRudy;
#FXML
private VBox vboxBottom;
#FXML
private Label lblClose;
Stage stage;
#FXML
private ImageView imgLoading;
/**
* Initializes the controller class.
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
longStart();
lblClose.setOnMouseClicked((MouseEvent event) -> {
Platform.exit();
System.exit(0);
});
// TODO
}
private void longStart() {
Service<ApplicationContext> service = new Service<ApplicationContext>() {
#Override
protected Task<ApplicationContext> createTask() {
return new Task<ApplicationContext>() {
#Override
protected ApplicationContext call() throws Exception {
ApplicationContext appContex = config.getInstance().getApplicationContext();
int max = appContex.getBeanDefinitionCount();
updateProgress(0, max);
for (int k = 0; k < max; k++) {
try
{
Thread.sleep(50);
updateProgress(k+1, max);
}
catch(InterruptedException e)
{
System.exit(0);
}
}
return appContex;
}
};
}
};
service.start();
service.setOnRunning((WorkerStateEvent event) -> {
new FadeInLeftTransition(lblWelcome).play();
new FadeInRightTransition(lblRudy).play();
new FadeInTransition(vboxBottom).play();
});
service.setOnSucceeded((WorkerStateEvent event) -> {
config2 config = new config2();
config.newStage(stage, lblClose, "/chapitreapp/FXMLDocument.fxml", "Sample Apps", true, StageStyle.UNDECORATED, false);
});
}
}
where did I go wrong?
Something along these lines, in your onSucceeded event handler, or a method that it calls...
try {
URL url = this.getClass().getResource("nextScene.fxml");
if (url != null) {
FXMLLoader loader = new FXMLLoader(url);
Parent root = loader.load(url);
Scene newScene = new Scene(root);
this.getStage().setScene(newScene);
} else {
System.out.println("URL was null");
}
} catch (Exception e) {
System.out.println(e);
}
In your controller, you will need to have some means of setting the stage, either via a constructor that accepts the Stage object or via a setStage() method. I've used a getStage() method above to access the Stage and set the new Scene object on it.
You could also use the static FXMLLoader load method: Parent root = FXMLLoader.load(url);
This may also be of benefit: https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx1

how know pressed key is character only in javafx

how know pressed key from Key Board is character only in javafx.
i want to handle following condition
if(event.isControlDown() && event.getCode().ISCHARACTERKEY()){
// some Code
}
ISCHARACTERKEY() include A-Z or a-z only.
is Javafx provide ISCHARACTERKEY() type of inbuilt method?
Yes, it does:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package keycodetester;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* #author ottp
*/
public class KeyCodeTester extends Application {
#Override
public void start(Stage primaryStage) {
TextField tf = new TextField();
tf.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if(event.isAltDown() && event.getCode().isLetterKey()) {
System.out.println("Character");
}
}
});
StackPane root = new StackPane();
root.getChildren().add(tf);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
event.getCode().isLetterKey() is your method..
Patrick

Resources