How to correctly use the widthProperty() for data from textField?
widthRectangle.textProperty().bindBidirectional(rectangleObj.getWidthRectangleValue());
rectangle.widthProperty().bind(rectangleObj.getWidthRectangleValue());
The above does not work. Maybe I'll find somewhere how to use it properly?
Edit:
public class RectangleObj {
private StringProperty widthRectangleValue = new SimpleStringProperty();
private StringProperty heightRectangleValue = new SimpleStringProperty();
public StringProperty getWidthRectangleValue(){
return widthRectangleValue;
}
public void setWidthRectangleValue(StringProperty widthRectangleValue){
this.widthRectangleValue = widthRectangleValue;
}
public StringProperty getHeightRectangleValue(){
return heightRectangleValue;
}
public void setHeightRectangleValue(StringProperty heightRectangleValue){
this.heightRectangleValue = heightRectangleValue;
}
}
.
public class ControllerParametersForRectangle implements Initializable {
#FXML
Rectangle rectangle;
#FXML
TextField widthRectangle;
#FXML
TextField heightRectangle;
RectangleObj rectangleObj = new RectangleObj();
#Override
public void initialize(URL location, ResourceBundle resources) {
widthRectangle.textProperty().bindBidirectional(rectangleObj.getWidthRectangleValue());
rectangle.widthProperty().bind(rectangleObj.getWidthRectangleValue());
}
}
Do not bind the value to a StringProperty. Use a TextFromatter to convert the TextField's text to another type instead.
Example:
#Override
public void start(Stage primaryStage) {
Rectangle rect = new Rectangle(100, 100);
StringConverter<Double> converter = new DoubleStringConverter();
TextField xTextField = new TextField();
TextFormatter<Double> xFromatter = new TextFormatter<>(converter);
xTextField.setTextFormatter(xFromatter);
TextField widthTextField = new TextField();
TextFormatter<Double> widthFromatter = new TextFormatter<Double>(converter);
widthTextField.setTextFormatter(widthFromatter);
xFromatter.valueProperty().bindBidirectional(rect.xProperty().asObject());
widthFromatter.valueProperty().bindBidirectional(rect.widthProperty().asObject());
Scene scene = new Scene(new VBox(10, xTextField, widthTextField, new Pane(rect)), 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
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 have been working on JavaFX and trying figure out how to connect classes contained withing the package. I want the "text1btn" button from MainController class to send a text from "scene1TextField" also in MainController class to TextArea in LeftTextArea class. I would appreciate any comments on that. Thank you.
package sample;
public class Main extends Application {
public static BorderPane root = new BorderPane();
public static BorderPane getRoot() {
return root;
}
#Override
public void start(Stage primaryStage) throws Exception {
URL url1 = getClass().getResource("../view/MainView.fxml");
BorderPane bp1 = FXMLLoader.load(url1);
URL url2 = getClass().getResource("../view/LeftTextArea.fxml");
AnchorPane bp2 = FXMLLoader.load(url2);
root.setTop(bp1);
root.setCenter(bp2);
primaryStage.setScene(new Scene(root, 500, 400));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
package Controller;
public class MainController {
#FXML
Button scene1btn;
#FXML
Button scene2btn;
#FXML
TextField scene1TextField;
#FXML
TextField scene2TextField;
#FXML
Button text1btn;
#FXML
Button text2btn;
#FXML
TextArea mainViewTextArea;
#FXML
public void initialize() {
}
#FXML
public void text1btnClicked() {
}
#FXML
public void text2btnClicked() {
}
#FXML
private void scene1btnClicked() {
try {
URL url1 = getClass().getResource("../view/LeftTextArea.fxml");
AnchorPane bp1 = FXMLLoader.load(url1);
BorderPane border = Main.getRoot();
border.setCenter(bp1);
} catch (IOException e) {
e.printStackTrace();
}
}
#FXML
private void scene2btnClicked() {
try {
URL url2 = getClass().getResource("../view/RightTextArea.fxml");
AnchorPane bp2 = FXMLLoader.load(url2);
BorderPane border = Main.getRoot();
border.setCenter(bp2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package Controller;
public class LeftTextArea {
#FXML
public TextArea leftTextArea;
}
A quick and simple approach is just to expose a StringProperty in the MainController, and when it changes call a method in the LeftTextArea:
public class MainController {
private final StringProperty text = new SimpleStringProperty();
public StringProperty textProperty() {
return text ;
}
// existing code ...
#FXML
public void text1btnClicked() {
textProperty().set(scene1TextField.getText());
}
// ...
}
In LeftTextArea do
public class LeftTextArea {
#FXML
public TextArea leftTextArea;
public void setText(String text) {
leftTextArea.setText(text);
}
}
And then you can tie it all together with
#Override
public void start(Stage primaryStage) throws Exception {
URL url1 = getClass().getResource("../view/MainView.fxml");
FXMLLoader loader1 = new FXMLLoader(url1);
BorderPane bp1 = loader1.load();
MainController mainController = loader1.getController();
URL url2 = getClass().getResource("../view/LeftTextArea.fxml");
FXMLLoader loader2 = new FXMLLoader(url2);
AnchorPane bp2 = loader2.load();
LeftTextArea leftTextArea = loader2.getController();
mainController.textProperty().addListener((obs, oldText, newText) ->
leftTextArea.setText(newText));
root.setTop(bp1);
root.setCenter(bp2);
primaryStage.setScene(new Scene(root, 500, 400));
primaryStage.setResizable(false);
primaryStage.show();
}
If you end up needing multiple properties like this that are essentially shared between controllers, you probably need to define a "model" class to encapsulate them all in one place, and pass the model to the controllers. See, e.g. JavaFX controller to controller - access to UI Controls or Applying MVC With JavaFx
If you want to set any field in the class LeftTextArea just simply create a public setter method in Class LeftTextArea like
public void setTextArea(Text text){
//do what you want to do
}
Then call the method from MainController class with the object of LeftTextArea class. like
LeftTextArea leftTextArea = new LeftTextArea();
leftTextArea.setTextArea(text); //text is the desired you want to send
I'm new to JavaFX and I've been at this code for about 8 hours now and I've become a bit delusional with the code. My two main problems are:
Can't add new items to the TableView using my popUp box display().
Feels messy and unorganized. Any tips for better communication between FXML and Controllers? (Again I'm new so it could be that I've stared too long at it)
My main class
public class Main extends Application {
public static Stage primaryStage;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage window) throws Exception {
try {
primaryStage = new Stage();
window = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("Fissto.fxml"));
Scene scene = new Scene(root);
window.setTitle("Fissto - the File Storage App!");
window.setScene(scene);
window.show();
}catch(Exception e){
e.printStackTrace();
}
// C.setLibraryStage();
}
}
My main Controller class (I have two sub ones that connect in the Fissto.fxml)
public class Controller implements Initializable{
Main main;
#FXML LibraryController libraryController = new LibraryController();
#FXML MergePageController mergePageController = new MergePageController();
private AddImageController addImageController = new AddImageController();
#FXML public void initialize(URL location, ResourceBundle resources){
System.out.println("View is now loaded!");
main = new Main();
libraryController.init(this);
mergePageController.init(this);
addImageController.init(this);
}
//Interface Initialization
public void setMergeStage() throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Controllers/MergePage.fxml"));
Scene scene = new Scene(root);
main.primaryStage.setScene(scene);
}
public void setLibraryStage() throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Controllers/LibraryPage.fxml"));
Scene scene = new Scene(root);
main.primaryStage.setScene(scene);
}
//Closing a window
public void closeWindow(){
main.primaryStage.close();
}
}
And finally the controller for the page that holds the TableView
public class LibraryController {
private Controller main;
//Library TableView Controllers
#FXML public TableView<Image> library;
#FXML private TableColumn<Image, String> NameColumn = new TableColumn<>();
#FXML private TableColumn<Image, ArrayList<String>> TagsColumn = new TableColumn<>();
#FXML private TableColumn<Image, String> CommentsColumn = new TableColumn<>();
#FXML private TableColumn<Image, String> FileLocationColumn = new TableColumn<>();
#FXML private TableColumn<Image, Integer> PointsColumn = new TableColumn<>();
public void init(Controller main){
System.out.println("LibraryPage Loading");
this.main = main;
addDataToColumns();
library = new TableView<>();
library.getItems().setAll(getImages());
System.out.println("LibraryPage Loaded");
}
//Initializes the column titles
private void addDataToColumns(){
NameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
TagsColumn.setCellValueFactory(new PropertyValueFactory<>("tags")); //TODO Convert to String format
CommentsColumn.setCellValueFactory(new PropertyValueFactory<>("comments"));
FileLocationColumn.setCellValueFactory(new PropertyValueFactory<>("filelocation"));
PointsColumn.setCellValueFactory(new PropertyValueFactory<>("points"));
}
//Gets all of the images
private ObservableList<Image> getImages() {
//TODO: Add where to actually get the data from
ObservableList<Image> images = FXCollections.observableArrayList();
String s = "Dog, Cat, Jumping Jack,";
ArrayList<String> list = Image.getTagOrganizer(',', s);
images.add(new Image("Test", list, "Comment", "No File Location, yet!", 10));
String k = "Calculus, Complex Numbers, Hard dude,";
ArrayList<String> list2 = Image.getTagOrganizer(',', k);
images.add(new Image("Number2", list2, "I love MathClub", "No File Location, yet!", -10));
return images;
}
This last class is the popup menu that takes in input to put in the GridPane
public class AddImageController {
private Controller main;
public void init(Controller main){
System.out.println("ImagePage Loaded");
this.main = main;
}
//Submitting an image to the library from the AddImagePage
public TextField nameInput;
public TextField tagsInput;
public TextField commentInput;
public TextField pointsInput;
public Label errorMessage;
/** TODO: Make it so that it writes to file then theoretically, the main controller should read from file every so often
* Main functionality for adding the information from the form to the database */
public void submitImage(){
if(!(nameInput.getText().trim().isEmpty()) && !(tagsInput.getText().trim().isEmpty()) && !(pointsInput.getText().trim().isEmpty())) {
if (isInt(pointsInput)) {
// System.out.print("Sent to database, *whoosh!*");
LibraryController c = new LibraryController();
ArrayList<String> s = Image.getTagOrganizer(',', tagsInput.getText());
Image image = new Image(nameInput.getText(), s, commentInput.getText(),"Location Needed", Integer.parseInt(pointsInput.getText()));
c.library.getItems().add(image);
clearInputs();
}
}else {
errorMessage.setText("Fill every field");
}
}
//Clears the input fields in the AddImagePage
public void clearInputs(){
nameInput.clear();
tagsInput.clear();
commentInput.clear();
pointsInput.clear();
errorMessage.setText("");
}
//Submission format verifiers
private boolean isInt(TextField input){
try{
int i = Integer.parseInt(input.getText());
errorMessage.setText("");
return true;
}catch (NumberFormatException e){
System.out.println("Oh no: " + input.getText() + " is not an integer");
errorMessage.setText("Points must be a number");
return false;
}
}
//Image Selection Handler
public void imageSelectionHandler(){
}
}
I understand it may be hard to read, so any feedback on how to make it easier to read in the future is much appreciated.
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!