I am trying to develop a wizard using the new ControlsFX 8.20.7 release. I have taken a look at the following example: BitBucket ControlsFX, and especially the method
showLinearWizard()
I simply can't understand how to use this API, can anyone help me get going or link to some examples?
This is my code right now, full of errors:
public class WizardTest extends Application {
private final ComboBox<StageStyle> styleCombobox = new ComboBox<>();
private final ComboBox<Modality> modalityCombobox = new ComboBox<>();
private final CheckBox cbUseBlocking = new CheckBox();
private final CheckBox cbCloseDialogAutomatically = new CheckBox();
private final CheckBox cbShowMasthead = new CheckBox();
private final CheckBox cbSetOwner = new CheckBox();
private final CheckBox cbCustomGraphic = new CheckBox();
private Stage stage;
#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) {
showLinearWizard();
}
});
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);
}
private void showLinearWizard() {
// define pages to show
Wizard wizard = new Wizard();
wizard.setTitle("Linear Wizard");
// --- page 1
int row = 0;
GridPane page1Grid = new GridPane();
page1Grid.setVgap(10);
page1Grid.setHgap(10);
page1Grid.add(new Label("First Name:"), 0, row);
TextField txFirstName = createTextField("firstName");
wizard.getValidationSupport().registerValidator(txFirstName, Validator.createEmptyValidator("First Name is mandatory"));
page1Grid.add(txFirstName, 1, row++);
page1Grid.add(new Label("Last Name:"), 0, row);
TextField txLastName = createTextField("lastName");
wizard.getValidationSupport().registerValidator(txLastName, Validator.createEmptyValidator("Last Name is mandatory"));
page1Grid.add(txLastName, 1, row);
WizardPane page1 = new WizardPane();
page1.setHeaderText("Please Enter Your Details");
page1.setContent(page1Grid);
// --- page 2
final WizardPane page2 = new WizardPane() {
#Override
public void onEnteringPage(Wizard wizard) {
String firstName = (String) wizard.getSettings().get("firstName");
String lastName = (String) wizard.getSettings().get("lastName");
setContentText("Welcome, " + firstName + " " + lastName + "! Let's add some newlines!\n\n\n\n\n\n\nHello World!");
}
};
page2.setHeaderText("Thanks For Your Details!");
// --- page 3
WizardPane page3 = new WizardPane();
page3.setHeaderText("Goodbye!");
page3.setContentText("Page 3, with extra 'help' button!");
ButtonType helpDialogButton = new ButtonType("Help", ButtonData.HELP_2);
page3.getButtonTypes().add(helpDialogButton);
Button helpButton = (Button) page3.lookupButton(helpDialogButton);
helpButton.addEventFilter(ActionEvent.ACTION, actionEvent -> {
actionEvent.consume(); // stop hello.dialog from closing
System.out.println("Help clicked!");
});
// create wizard
wizard.setFlow(new LinearFlow(page1, page2, page3));
System.out.println("page1: " + page1);
System.out.println("page2: " + page2);
System.out.println("page3: " + page3);
// show wizard and wait for response
wizard.showAndWait().ifPresent(result -> {
if (result == ButtonType.FINISH) {
System.out.println("Wizard finished, settings: " + wizard.getSettings());
}
});
}
private TextField createTextField(String id) {
TextField textField = new TextField();
textField.setId(id);
GridPane.setHgrow(textField, Priority.ALWAYS);
return textField;
}
}
The problem was that I forgot to add the
openjfx-dialogs.jar
Related
I ask for your understanding, I am a beginner;)
I'm trying to build a simple application using JavaFX. The problem is that when I open the window the first time it goes well, but if I want to change the scene it throws an error...
Exception in thread "JavaFX Application Thread"
java.lang.IllegalArgumentException:
AnchorPane#1809546[styleClass=root]is already set as root of another
scene#
Main class
public class Main extends Application{
//private Stage primaryStage;
#Override
public void start(Stage primaryStage) {
Login login = new Login();
Scene scene = login.okno();
primaryStage.setTitle("Komunikator sieciowy JAVA");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
//public Stage getPrimaryStage() {
// return this.primaryStage;
//}
public static void main(String[] args) {
launch(args);
}
}
Login
public class Login {
private GridPane grid;
private Scene scene;
private Text title;
private Label nick;
private Button wejdzBtn;
private TextField userName;
//private Alert oknoDlg;
public Login() {
grid = new GridPane();
grid.setAlignment (Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25,25,25,25));
scene = new Scene (grid, 300, 150);
utworzBtn();
utworzLogin();
utworzTekst();
utworzNick();
//oknoDialogowe();
}
//private void oknoDialogowe() {
//Alert oknoDlg = new Alert(Alert.AlertType.CONFIRMATION);
//oknoDlg.setTitle("Informacja");
//oknoDlg.setContentText("test");
// oknoDlg.setHeaderText(null);
//oknoDlg.showAndWait();
//}
private void utworzBtn() {
wejdzBtn = new Button("Zaloguj si\u0119");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment (Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(wejdzBtn);
grid.add(hbBtn, 1, 2);
//wejdzBtn.setDisable(true);
wejdzBtn.setOnAction(e -> {
Messages mess = new Messages();
grid.getScene().setRoot(mess.messa());;
});
}
private void utworzLogin() {
nick = new Label("Nick:");
grid.add(nick, 0, 1);
}
private void utworzNick() {
userName = new TextField();
grid.add(userName,1,1);
// informacja w polu tekstowym
userName.setPromptText("Max 15 znak\u00f3w");
userName.setFocusTraversable(false);
//maksymalna ilość znaków
final int maxLength = 15;
userName.setOnKeyTyped(t -> {
if (userName.getText().length() > maxLength)
{
int pos = userName.getCaretPosition();
userName.setText(userName.getText(0, maxLength));
userName.positionCaret(pos);
}
});
}
private void utworzTekst() {
title = new Text ("Dzień dobry!");
title.setFont(Font.font("Calibri", FontWeight.NORMAL, 20));
grid.add(title, 0, 0, 2, 1);
}
public Scene okno() {
return scene;
}
}
and and a little another class that I'm trying to change with button from login.java
public class Messages {
private AnchorPane anchor;
private Scene scena;
//private Label nick;
private Button sendBtn;
private TextField poleDoWpisywania;
private TextArea poleDoWyswietlania, pobierzNick;
public Messages() {
anchor = new AnchorPane();
scena = new Scene(anchor, 700, 600);
pobierzNick();
poleDoWpisywania();
poleDoWyswietlania();
utworzPrzycisk();
}
private void utworzPrzycisk() {
sendBtn = new Button("Wy\u015Blij");
sendBtn.setDisable(true);
}
private void pobierzNick(){
pobierzNick = new TextArea();
pobierzNick.setEditable(false);
pobierzNick.setWrapText(true);
}
private void poleDoWpisywania() {
poleDoWpisywania = new TextField();
}
private void poleDoWyswietlania() {
poleDoWyswietlania = new TextArea();
poleDoWyswietlania.setEditable(false);
poleDoWyswietlania.setWrapText(true);
}
public Pane messa() {
return anchor;
}
}
could I ask you to show the right way to fix the bug?
JavaFX defines a scene graph which is a tree data structure that has a single root node. For your application (i.e. the code you posted), the root node is the primaryStage (this is the parameter in method start() in class Main). The primaryStage can have several Scenes. Each Scene must have its own root node.
The error message you are getting means that a Scene's root cannot also be the root of another Scene. In other words anchor is the root for scena in class Messages which means it can't be set as the root for scene in class Login.
Apart from that, if you want to change Scene's you need to call method setScene() of class Stage. Here is your Login class and Messages class with changes that solve the run-time error you are getting and perform the scene change when the user clicks on wejdzBtn button.
Login.java
(I only changed the lambda expression in method utworzBtn().)
public class Login {
private GridPane grid;
private Scene scene;
private Text title;
private Label nick;
private Button wejdzBtn;
private TextField userName;
public Login() {
grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25,25,25,25));
scene = new Scene(grid, 300, 150);
utworzBtn();
utworzLogin();
utworzTekst();
utworzNick();
}
private void utworzBtn() {
wejdzBtn = new Button("Zaloguj si\u0119");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment (Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(wejdzBtn);
grid.add(hbBtn, 1, 2);
wejdzBtn.setOnAction(e -> {
Messages mess = new Messages();
Window w = scene.getWindow();
if (w instanceof Stage) {
Stage s = (Stage) w;
s.setScene(mess.getScena());
}
});
}
private void utworzLogin() {
nick = new Label("Nick:");
grid.add(nick, 0, 1);
}
private void utworzNick() {
userName = new TextField();
grid.add(userName,1,1);
userName.setPromptText("Max 15 znak\u00f3w");
userName.setFocusTraversable(false);
final int maxLength = 15;
userName.setOnKeyTyped(t -> {
if (userName.getText().length() > maxLength)
{
int pos = userName.getCaretPosition();
userName.setText(userName.getText(0, maxLength));
userName.positionCaret(pos);
}
});
}
private void utworzTekst() {
title = new Text ("Dzień dobry!");
title.setFont(Font.font("Calibri", FontWeight.NORMAL, 20));
grid.add(title, 0, 0, 2, 1);
}
public Scene okno() {
return scene;
}
}
Messages.java
(I added method getScena().)
public class Messages {
private AnchorPane anchor;
private Scene scena;
private Button sendBtn;
private TextField poleDoWpisywania;
private TextArea poleDoWyswietlania, pobierzNick;
public Messages() {
anchor = new AnchorPane();
scena = new Scene(anchor, 700, 600);
pobierzNick();
poleDoWpisywania();
poleDoWyswietlania();
utworzPrzycisk();
}
private void utworzPrzycisk() {
sendBtn = new Button("Wy\u015Blij");
sendBtn.setDisable(true);
}
private void pobierzNick() {
pobierzNick = new TextArea();
pobierzNick.setEditable(false);
pobierzNick.setWrapText(true);
}
private void poleDoWpisywania() {
poleDoWpisywania = new TextField();
}
private void poleDoWyswietlania() {
poleDoWyswietlania = new TextArea();
poleDoWyswietlania.setEditable(false);
poleDoWyswietlania.setWrapText(true);
}
public Scene getScena() {
return scena;
}
public Pane messa() {
return anchor;
}
}
Thanks a lot Abra, I've been thinking about it for the last 6 hours and haven't noticed this problem. I have also removed
public Pane messa ();
return anchor;
I do not need it ;)
I am trying to handle event inside controller. How can i make "Create Profile" button work inside controller. Here are my classes:
main class
public class ApplicationLoader extends Application {
private OptionsModuleChooserRootPane view;
#Override
public void init() {
StudentProfile model = new StudentProfile();
view = new OptionsModuleChooserRootPane();
new OptionsModuleChooserController(view, model);
}
#Override
public void start(Stage stage) throws Exception {
stage.setMinWidth(530);
stage.setMinHeight(550);
stage.setTitle("Final Year Module Chooser Tool");
stage.setScene(new Scene(view));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Main View
public class OptionsModuleChooserRootPane extends BorderPane {
Menu fileMenu;
Menu helpMenu;
MenuBar menuBar;
TabPane tabPane;
List<Tab> tabs;
public CreateProfileTab profilePane;
public SelectModulesTab modulesPane;
public OverviewSelectionPane overviewPane;
public OptionsModuleChooserRootPane() {
fileMenu = new Menu("File");
helpMenu = new Menu("Help");
menuBar = new MenuBar();
tabPane = new TabPane();
tabs = new ArrayList<>();
//------------------ File menu ----------------------------
fileMenu.getItems().add(new MenuItem("Load Student Data"));
fileMenu.getItems().add(new MenuItem("Save Student Data"));
fileMenu.getItems().add(new MenuItem("Exit"));
//----------------- Help menu -----------------------------
helpMenu.getItems().add(new MenuItem("About"));
//----------------- MenuBar containing all menus ---------
menuBar.getMenus().addAll(fileMenu,helpMenu);
this.setTop(menuBar);
profilePane = new CreateProfileTab();
modulesPane = new SelectModulesTab();
overviewPane = new OverviewSelectionPane();
//-------------------------------- Tabs -----------------------------------------------------
tabs.add(addNewTab(tabPane, "Create Profile", profilePane, false));
tabs.add(addNewTab(tabPane, "Select Modules", modulesPane, false));
tabs.add(addNewTab(tabPane, "Overview Selection", overviewPane, false));
this.setCenter(tabPane);
}
private Tab addNewTab(final TabPane tabPane, String newTabName, Pane newTabContent, boolean isCloseable) {
Tab newTab = new Tab(newTabName);
newTab.setContent(newTabContent);
newTab.setClosable(isCloseable);
tabPane.getTabs().add(newTab);
return newTab;
}
}
I have created separate files for all three tabs. Here is the "Create Profile" tab class which has the button i am trying to handle event of.
public class CreateProfileTab extends GridPane {
private Label lSelectCousrse;
private ComboBox<Course> cboCourses;
private Label lPNumber;
private TextField tfPNumber;
private Label lFirstName;
private TextField tfFirstName;
private Label lSurname;
private TextField tfSurname;
private Label lEmail;
private TextField tfEmail;
private Label lDate;
private DatePicker datePicker;
private HBox hboxDate;
private Button btnCreateProfile;
private StudentProfile student = null;
private Name name;
public CreateProfileTab(){
this.setMinSize(400, 200);
this.setPadding(new Insets(10, 10, 10, 10));
this.setVgap(15);
this.setHgap(20);
this.setAlignment(Pos.CENTER);
lSelectCousrse = new Label("Select course:");
cboCourses = new ComboBox<Course>();
lPNumber = new Label("Input P number:");
tfPNumber = new TextField();
lFirstName = new Label("Input first name:");
tfFirstName = new TextField();
lSurname = new Label("Input surname");
tfSurname = new TextField();
lEmail = new Label("Input email:");
tfEmail = new TextField();
lDate = new Label("Input date:");
datePicker = new DatePicker();
hboxDate = new HBox(datePicker);
btnCreateProfile = new Button("Create Profile");
this.add(lSelectCousrse, 0, 0);
GridPane.setHalignment(lSelectCousrse, HPos.RIGHT);
this.add(cboCourses, 1, 0);
this.add(lPNumber, 0, 1);
GridPane.setHalignment(lPNumber, HPos.RIGHT);
this.add(tfPNumber, 1, 1);
this.add(lFirstName,0,2);
GridPane.setHalignment(lFirstName, HPos.RIGHT);
this.add(tfFirstName,1,2);
this.add(lSurname,0,3);
GridPane.setHalignment(lSurname, HPos.RIGHT);
this.add(tfSurname,1,3);
this.add(lEmail,0,4);
GridPane.setHalignment(lEmail, HPos.RIGHT);
this.add(tfEmail,1,4);
this.add(lDate,0,5);
GridPane.setHalignment(lDate, HPos.RIGHT);
this.add(hboxDate,1,5);
this.add(btnCreateProfile,1,6);
}
public void populateComboBoxWithCourses(Course[] courses) {
cboCourses.getItems().addAll(courses);
cboCourses.getSelectionModel().select(0);
}
public Button getButton(){
return this.btnCreateProfile;
}
}
And here is my controller
public class OptionsModuleChooserController implements EventHandler<ActionEvent> {
private OptionsModuleChooserRootPane view;
private StudentProfile model;
public OptionsModuleChooserController(OptionsModuleChooserRootPane view, StudentProfile model) {
this.model = model;
this.view = view;
this.view.profilePane.populateComboBoxWithCourses(setupAndRetrieveCourses());
}
private Course[] setupAndRetrieveCourses() {
.......
}
#Override
public void handle(ActionEvent event) {
final Object source = event.getSource();
if (source.equals(this.view.profilePane.getButton())) {
System.out.println("Button has been pressed!");
}
}
}
I am building a JavaFx application and I want to create a method that receives a GridPane and a Node[] with the amount of items being added to the pane. However, when I call the method I get a NoSuchMethodException.
As a test, I tried to create a simple method private String helloWorld() that would return "Hello World";. This method does work, but when I try to run gridLogin = buildForm(gridLogin, items);, I get the Exception in thread "main" java.lang.NoSuchMethodException error.
Application.java
public class DesktopApplication extends Application {
#Override
public void start(Stage primaryStage) {
BuildGraphicalUserInterface ui = new BuildGraphicalUserInterface();
ui.initStage(primaryStage);
}
}
BuildGraphicalUserInterface.java
package com.fenrir.desktop.UserInterface;
import ...;
public class BuildGraphicalUserInterface {
private final String APP_TITLE = "Fenrir Desktop App";
private final String LOGIN_HEADER = "FENRIR secure";
Stage stage;
Scene sceneLogin, sceneMain, sceneRegister;
GridPane gridLogin, gridMain, gridRegister;
long startTime, endTime;
boolean authorized;
Optional<String> result;
public void initStage(Stage primaryStage) {
stage = primaryStage;
// Set global ui options
stage.setTitle(APP_TITLE);
stage.setResizable(false);
// Setup every screen in application
initScenes(stage);
}
private void initScenes(Stage stage) {
startTime = System.nanoTime();
sceneLogin = buildLoginScreen();
endTime = System.nanoTime();
System.out.println("login:\t" + (endTime - startTime));
startTime = System.nanoTime();
sceneMain = buildMainScreen();
endTime = System.nanoTime();
System.out.println("main:\t" + (endTime - startTime));
startTime = System.nanoTime();
sceneRegister = buildRegisterScreen();
endTime = System.nanoTime();
System.out.println("register:\t" + (endTime - startTime));
stage.setScene(sceneLogin);
stage.show();
}
// BUILD OF SCREENS
private Scene buildLoginScreen() {
gridLogin = new GridPane();
gridLogin.setAlignment(Pos.CENTER);
gridLogin.setVgap(10);
gridLogin.setHgap(10);
Text loginTitle = new Text(LOGIN_HEADER);
loginTitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
Label usernameLabel = new Label("Username:");
final TextField usernameTextField = new TextField();
Label companyLabel = new Label("Company:");
final TextField companyTextField = new TextField();
Button loginButton = new Button("Login");
Hyperlink registerLink = new Hyperlink();
registerLink.setText("Register");
registerLink.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
stage.setScene(sceneRegister);
}
});
loginButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
UserAuthentication auth = new UserAuthentication(usernameTextField.getText(), companyTextField.getText());
try {
// check if user exists
auth.authenticate();
// show token pop up
promptTokenAlert();
if (result.isPresent()) {
if (auth.verifyToken(result.get())) {
authorized = true;
stage.setScene(sceneMain);
}
else
wrongTokenAlert();
}
} catch (IOException e1) {
userNotFoundAlert();
usernameTextField.setText("");
companyTextField.setText("");
}
}});
Node[] items = new Node[6];
items[0] = loginTitle;
items[1] = usernameLabel;
items[2] = usernameTextField;
items[3] = companyLabel;
items[4] = companyTextField;
items[5] = loginButton;
items[6] = registerLink;
gridLogin = buildForm(gridLogin, items);
sceneLogin = new Scene(gridLogin, 300, 200);
return sceneLogin;
}
private Scene buildMainScreen() {
gridMain = new GridPane();
final Label authorizedLabel = new Label("Authorized!");
Button logoutButton = new Button("Logout");
logoutButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
authorized = false;
stage.setScene(sceneLogin);
}});
gridMain.add(authorizedLabel, 0, 0);
gridMain.add(logoutButton, 0, 1);
sceneMain = new Scene(gridMain, 800, 600);
return sceneMain;
}
private Scene buildRegisterScreen() {
gridRegister = new GridPane();
gridRegister.setAlignment(Pos.CENTER);
gridRegister.setVgap(10);
gridRegister.setHgap(10);
sceneRegister = new Scene(gridRegister, 300, 200);
Label userName = new Label("Username:");
final TextField userTextField = new TextField();
Label company = new Label("Company:");
final TextField companyTextField = new TextField();
Label phoneNumber = new Label("Phone nr.:");
final TextField phoneNumberTextField = new TextField();
Button registerButton = new Button("Register");
Hyperlink returnLabel = new Hyperlink();
returnLabel.setText("Go back");
returnLabel.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
stage.setScene(sceneLogin);
}
});
registerButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
/**
* register response
* 1 - user already exists
* 2 - incorrect username
* 3 - incorrect phonenumber
* 4 - unknown error
* 0 - success
*/
int registerResponse;
UserRegistration userReg = new UserRegistration(userTextField.getText(), companyTextField.getText(), phoneNumberTextField.getText());
try {
registerResponse = userReg.Register();
} catch (IOException e) {
registerResponse = 4;
e.printStackTrace();
}
if (registerResponse == 0) {
userRegisteredConfirmation();
stage.setScene(sceneLogin);
} else {
userRegistrationErrorAlert(registerResponse);
}
}
});
gridRegister.add(userName, 0, 1);
gridRegister.add(userTextField, 1, 1);
gridRegister.add(company, 0, 2);
gridRegister.add(companyTextField, 1, 2);
gridRegister.add(phoneNumber, 0, 3);
gridRegister.add(phoneNumberTextField, 1, 3);
gridRegister.add(registerButton, 1, 4);
gridRegister.add(returnLabel, 0, 4);
return sceneRegister;
}
/**
* Builds a form with items received (items should be sorted)
* #param grid
* #param items
* #return
*/
private GridPane buildForm(GridPane grid, Node[] items) {
int row = 0;
for (int i = 0; i < items.length; i++) {
grid.add(items[i], i, row);
if (i % 2 == 0)
row++;
}
return grid;
}
// ALERTS
/**
* Alert is shown when service returns no user
* #return
*/
private Alert userNotFoundAlert() {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("FENRIR security");
alert.setHeaderText("Error");
alert.setContentText("User not recognized");
alert.showAndWait();
return alert;
}
/**
* Alert is shown when user should enter token
* #return
*/
private TextInputDialog promptTokenAlert() {
TextInputDialog alert = new TextInputDialog("");
alert.setTitle("FENRIR security");
alert.setHeaderText("Token requested");
result = alert.showAndWait();
return alert;
}
/**
* Alert is shown when entered token is wrong
* #return
*/
private Alert wrongTokenAlert() {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("FENRIR security");
alert.setHeaderText("Token incorrect");
alert.showAndWait();
return alert;
}
/**
* Confirmation is shown when registration is completed
* #return
*/
private Alert userRegisteredConfirmation() {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("FENRIR security");
alert.setHeaderText("Success");
alert.setContentText("Registration completed");
alert.showAndWait();
return alert;
}
/**
* Alert is shown when an error occurs during registration
* #param errorCode
* #return
*/
private Alert userRegistrationErrorAlert(int errorCode) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("FENRIR security");
alert.setHeaderText("Error");
String errorMessage;
switch (errorCode) {
case 1: errorMessage = "User already exists.";
break;
case 2: errorMessage = "Incorrect username. Username should be at least 2 characters.";
break;
case 3: errorMessage = "Incorrect phone number. Should be 8 characters and only numbers.";
break;
default: errorMessage = "Unknown error. Contact administrator.";
}
alert.setContentText(errorMessage);
alert.showAndWait();
return alert;
}
}
Stack trace
Exception in Application start method
Exception in thread "main" java.lang.NoSuchMethodException: com.fenrir.desktop.DesktopApplication.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1786)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)
Process finished with exit code 1
This will solve your problem, install e(fx)clipse this plugin for eclise but i dont know for intellij ,or add facet for your application as javafx application, if you add facet you dont need main method , or use like this
public class DesktopApplication extends Application {
#Override
public void start(Stage primaryStage) {
BuildGraphicalUserInterface ui = new BuildGraphicalUserInterface();
ui.initStage(primaryStage);
}
public static void main(String[] args) {
launch(args);
}
}
I'm a really new programmer so idk if this question sounds really stupid but..
This is my main:
package culminating;
import javafx.application.Application;
& all other necessary imports...
public class CulminatingMAIN extends Application {
//Set Global variables
int count = 0;
String name;
String gender = "Boy";
Label testLabel = new Label(gender + " has been selected");
#Override
public void start(Stage primaryStage) throws Exception {
/**
* ************************ SCENE 1 WORK *************************
*/
TextField nameTextField = new TextField();
nameTextField.setMaxWidth(100);
Label nameLabel = new Label("Please enter your name.");
Label genderLabel = new Label();
Label titleLabel = new Label("Math Adventure!");
titleLabel.setFont(Font.font("Arial", FontWeight.BOLD, 30));
Rectangle titleRectangle = new Rectangle();
titleRectangle.setFill(Color.TOMATO);
titleRectangle.setWidth(280);
titleRectangle.setHeight(60);
titleRectangle.setStroke(Color.BLACK);
titleRectangle.setStrokeWidth(2.0);
StackPane root = new StackPane(titleRectangle, titleLabel);
//Set VBox properties
VBox vbox1 = new VBox(25);
vbox1.setAlignment(Pos.TOP_CENTER);
vbox1.setPadding(new Insets(60, 0, 0, 0));
vbox1.setStyle("-fx-background-color: lightskyblue");
HBox genderBtnBox = new HBox(25);
genderBtnBox.setAlignment(Pos.CENTER);
//Set Scene 1 buttons
Button enterNameBtn = new Button("Enter");
Button goToScene2Btn = new Button("Continue");
//Set Radio Button functionality here
final ToggleGroup genderGroup = new ToggleGroup();
RadioButton rb1 = new RadioButton("Boy");
rb1.setToggleGroup(genderGroup);
rb1.setUserData("Boy");
rb1.setSelected(true);
RadioButton rb2 = new RadioButton("Girl");
rb2.setToggleGroup(genderGroup);
rb2.setUserData("Girl");
//Add panes, labels and buttons to the VBox
vbox1.getChildren().addAll(root, nameLabel, nameTextField, enterNameBtn, genderLabel, genderBtnBox);
Scene scene = new Scene(vbox1, 500, 500);
primaryStage.setScene(scene);
primaryStage.setTitle("Culminating Project");
primaryStage.show();
/**
* ************************ SCENE 2 WORK *************************
*/
//THIS IS ROUGH WORK SO FAR
//Here, testing out new scene to see that it loads properly (and it does)
Circle testCircle = new Circle();
testCircle.setRadius(30);
testCircle.setFill(Color.YELLOW);
StackPane testPane = new StackPane(testCircle, testLabel);
Scene scene2 = new Scene(testPane, 500, 500);
/**
* ************************ EVENTS *************************
*/
//Stores user-entered name and prompts for user gender. Adds Continue button
enterNameBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if ((count < 1) && (!nameTextField.getText().isEmpty())) {
name = nameTextField.getText();
genderLabel.setText("Hi " + name + "! Please select whether you are a boy or girl.");
genderBtnBox.getChildren().addAll(rb1, rb2);
vbox1.getChildren().add(goToScene2Btn);
count++;
}
}
});
//When pressed, changes the scene so that scene 2 is set instead
goToScene2Btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
primaryStage.setScene(scene2);
}
});
//Radio button selection is stored in gender variable
genderGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
#Override
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (genderGroup.getSelectedToggle() != null) {
gender = genderGroup.getSelectedToggle().getUserData().toString();
testLabel.setText(gender + " has been selected");
}
}
});
if (gender.equals("boy")){
{
}
}
else if (gender.equals("girl")){
{
}
}
}
public static void main(String[] args) {
launch(args);
}
}
Now I have another class called CharacterGraphic, which I want to call and make the graphic I created in it appear.
package culminating;
& all the other imports
public class CharacterGraphic extends Culminating_JavaFX {
public void start(Stage primaryStage) throws Exception {
String gender = "boy";
Pane pane = new Pane();
pane.setStyle("-fx-background-color: LIGHTBLUE");
pane.setPrefSize(200, 200);
Circle head = new Circle();
head.setRadius(50);
head.setCenterX(240);
head.setCenterY(120);
head.setFill(Color.BURLYWOOD);
etc etc (all other graphics i made)
How do I do this???? And where would I do this?? Any answers really, really appreciated!
I am trying to get clicked value in my textbox, i have added listener but not getting the adjact output. Please suggest me how to do.
ObservableList<String> data5 = FXCollections.observableArrayList(smooth);
listView.setItems(data5);
listView.getSelectionModel().selectedItemProperty().addListener(
new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> ov,
String old_val, String new_val)
{
System.out.println("********"+new_val);
txtCustomerName.textProperty();
txtCustomerName.setText(new_val);
}
});
public class FillForm extends Application {
Text addressOne;
Text addressTwo;
Text mobileOne;
Text email;
#Override
public void start(Stage stage) throws Exception {
Label companyNameLbl = new Label("Company Name");
ComboBox<String> companyName = new ComboBox<String>();
companyName.setEditable(true);
populateCompanyName(companyName);
addComboListener(companyName);
HBox companyHbox = new HBox(25);
companyHbox.getChildren().addAll(companyNameLbl, companyName);
Label addressOneLbl = new Label("Address One");
addressOne = new Text();
HBox addressOneHbox = new HBox();
addressOneHbox.getChildren().addAll(addressOneLbl, addressOne);
Label addressTwoLbl = new Label("Address two");
addressTwo = new Text();
HBox addressTwoHbox = new HBox();
addressTwoHbox.getChildren().addAll(addressTwoLbl, addressTwo);
Label mobileLbl = new Label("Company Name");
mobileOne = new Text();
HBox mobileHbox = new HBox();
mobileHbox.getChildren().addAll(mobileLbl, mobileOne);
Label emailLbl = new Label("Company Name");
email = new Text();
HBox emailHbox = new HBox();
emailHbox.getChildren().addAll(emailLbl, email);
VBox form = new VBox(20);
form.getChildren().addAll(companyHbox, addressOneHbox, addressTwoHbox,
mobileHbox, emailHbox);
Scene scene = new Scene(form);
stage.setScene(scene);
scene.getStylesheets().add("/comboStyles.css");
stage.show();
}
private void addComboListener(final ComboBox<String> combo) {
combo.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
if (combo.getValue().equals("Apple")) {
addressOne.setText("\t Apple address one");
addressTwo.setText("\t Apple address two");
mobileOne.setText("\t Apple mobile number");
email.setText("\t Apple email");
}
}
});
}
public void populateCompanyName(ComboBox<String> combo) {
combo.getItems().add("Intel");
combo.getItems().add("Apple");
combo.getItems().add("Microsoft");
}
public static void main(String[] args) {
launch(args);
}
}
comboStyles.css
.combo-box .arrow, .combo-box .arrow-button{
-fx-background-color: transparent;
}
output:
I have made a rough example without using proper layouts. You use the appropriate layout for your UI. Populate the combobox with your data5 list and in the action listener of the combo box check for the selected value and fill other fields.
Update
Since you have to use only text box as your company said, the below links guide you in that. You have to create a customized text box by extending the Text class of Javafx.
https://github.com/privatejava/javafx-autocomplete-field
http://blog.ngopal.com.np/2011/07/04/autofill-textbox-with-filtermode-in-javafx-2-0-custom-control/
Autofill text field jars:
https://code.google.com/p/jfx-autocomplete-textfield/