How can I check a radio button by default in JavaFX? [duplicate] - java

This question already has answers here:
Passing Parameters JavaFX FXML
(10 answers)
javafx 8 compatibility issues - FXML static fields
(1 answer)
Closed 3 years ago.
I'm building a rock, scissors, paper application as a college homework. I should use radio-buttons and since it's a game, it should allows one selected button at a time.
I tried to create ToggleGroups and set one of the buttons as selected by default, but it's not working! When I run the application, it still allows me to choose more than one button :(
What am I missing?
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("../view/QuilometrosPorLitroView.fxml"));
primaryStage.setTitle("Pedra, Papel, Tesoura");
primaryStage.setScene(new Scene(root, 428, 336));
primaryStage.setResizable(false);
primaryStage.show();
Controller.selectButtonDefault();
}
public static void main(String[] args) {
launch(args);
}
}
public class Controller {
#FXML
public static
RadioButton tesoura = new RadioButton();
#FXML
public static
RadioButton pedra = new RadioButton();
#FXML
public static
RadioButton papel = new RadioButton();
public static void selectButtonDefault() {
ToggleGroup group = new ToggleGroup();
tesoura.setToggleGroup(group);
tesoura.setSelected(true);
pedra.setToggleGroup(group);
papel.setToggleGroup(group);
}

This
#FXML public static RadioButton tesoura = new RadioButton();
#FXML public static RadioButton pedra = new RadioButton();
#FXML public static RadioButton papel = new RadioButton();
Should be changed into
#FXML private RadioButton tesoura;
#FXML private RadioButton pedra;
#FXML private RadioButton papel;

Related

How to display user interface in JavaFX [duplicate]

This question already has answers here:
How to Fix NoClassDefFoundError in JavaFX?
(1 answer)
I'm encounter a java.lang.NoClassDefFoundError and I don't know why it's occuring [duplicate]
(1 answer)
Closed 5 months ago.
I am working on a JavaFX project, and I am having trouble displaying the user interface. I keep getting this error:
Error: Could not find or load main class Main.SongApp
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application
I am confused because my directory has no files named 'application' or 'Application.'
I have these three files and I am not sure why this code does not run. This is the main file that I try to display the user interface from:
SongApp.java
public class SongApp extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
// create FXML loader
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/SongLibraryProject/ControllerTing/SongLib.fxml"));
// load fxml, root layout manager in fxml file is GridPane
AnchorPane root = (AnchorPane)loader.load();
// set scene to root
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This file has my front end code from Scene Builder and the anchor table I am trying to display: SongLib.fxml
<AnchorPane minHeight="400.0" minWidth="747.0" prefHeight="400.0" prefWidth="747.0" style="-fx-background-color: #263238;" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SongLibrary.View.Controller">
//front end(scenebuilder code)
</AnchorPane>
This is the the controller file: SongLibController.java
public class SongLibController {
#FXML ListView<Song> songList;
#FXML Button add;
#FXML Button edit;
#FXML Button delete;
#FXML Text name;
#FXML Text artist;
#FXML Text album;
#FXML Text year;
#FXML TextField nameField;
#FXML TextField artistField;
#FXML TextField albumField;
#FXML TextField yearField;
private ObservableList<String> obsList;
public void add(ActionEvent e) {
System.out.println("add");
}
public void edit(ActionEvent e) {
System.out.println("edit");
}
public void delete(ActionEvent e) {
System.out.println("delete");
}
}

Struggling to get JavaFx app working, objects stop existing?

So i'm working on a pet project, essentially a digitalisation of a do it yourself role playing adventure book.
I switched to using Scenebuilder because of the freedom it allows when crafting a GUI.
I'm having trouble binding the data to the screen. It seems the objects I am calling either stop existing or are not the ones i need.
I am using a SQLite database for my data, and that seems to work fine.
I am using Maven to import the things i need, this also seems to work fine however this requires me to use
public class DdAppLauncher {
public static void main(String[] args) {
DdApp2.main(args);
}
}
into ->
public class DdApp2 extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/mainWindow.fxml"));
stage.setTitle("Deathtrap Dungeon");
stage.setScene(new Scene (root, 800,600));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This brings up the titlescreen that contains a start button which is handled by the following controller.
public class MainController {
LocationsPool loc;
Location currentLocation;
#FXML
private ListView<String> inventory;
#FXML
private Text locationDescription;
#FXML
private Text descrA;
#FXML
private Text descrB;
#FXML
private Text descrC;
#FXML
private Text descrD;
#FXML
private Text descrE;
#FXML
private Text descrF;
#FXML
public void startButtonClicked(ActionEvent event){
try {
System.out.println("Starting game");
Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
// Swap screen
Parent root = FXMLLoader.load(getClass().getResource("/fxml/gameWindow.fxml"));
stage.setScene(new Scene(root,800,600));
} catch (IOException e) {
e.printStackTrace();
}
//Setup
loc = new LocationsPool();
currentLocation = loc.getLocation(1);
System.out.println(currentLocation.getDescription());
locationDescription = new Text(currentLocation.getDescription());
System.out.println(locationDescription.getText());
System.out.println(locationDescription);
}
#FXML
public void handleButtonA(){
System.out.println(currentLocation==null);
}
}
Output on console ->
starting game
The clamour... (works)
The clamour... (works)
On button press ->
True
So it seems the app "forgets" fields when it runs? or is it the controller that stop existing and is remade?
Furthermore when trying to bind data to fields with fx:id, it doesn't seem to link those fields to anything until i press that button.
Am i structuring this all wrong? What am i not getting?
The final product should have the description loaded and all the choices loaded for that location.
Then on a selection should load up a new location and new choices so the text needs to be updated.
Thanks in advance.
Kev

How to use same method in two different classes (JavaFX with Scenebuilder)?

I am currently experimenting with JavaFX and SceneBuilder in eclipse to create and design my own program. In my first class "StartController" I am using a method called makeFadeIn. Basically, when I click a button another page loads up with a fade effect.
This is the code from StartController.java (notice makeFadeIn):
public class StartController {
#FXML
private AnchorPane rootPane;
private void makeFadeIn() {
FadeTransition fadeTransition = new FadeTransition();
fadeTransition.setDuration(Duration.millis(1000));
fadeTransition.setNode(rootPane);
fadeTransition.setFromValue(0);
fadeTransition.setToValue(1);
fadeTransition.play();
}
#FXML
private void loadSecondPage(ActionEvent event) throws IOException {
AnchorPane startPage = FXMLLoader.load(getClass().getResource("SecondController.fxml"));
rootPane.getChildren().setAll(startPage);
makeFadeIn();
}
Next, my other class loads up called "SecondController.java". In this class, I'm using the exact same method makeFadeIn (but I had to write it twice since it didn't let me run the program).
This is the code from SecondController.java:
public class SecondController {
#FXML
private AnchorPane rootPane;
private void makeFadeIn() {
FadeTransition fadeTransition = new FadeTransition();
fadeTransition.setDuration(Duration.millis(1000));
fadeTransition.setNode(rootPane);
fadeTransition.setFromValue(0);
fadeTransition.setToValue(1);
fadeTransition.play();
}
#FXML
private void loadFirstPage(ActionEvent event) throws IOException {
AnchorPane startPage = FXMLLoader.load(getClass().getResource("StartController.fxml"));
rootPane.getChildren().setAll(startPage);
}
My question is: can I somehow call the makeFadeIn method from the first class so I don't have to write it in my second class? I guess I need to inherit it in some way but I'm not sure how. I tried declaring it public instead of private but that did not help much.
You could move this functionality to a base class:
public class BaseController {
#FXML
private AnchorPane rootPane;
protected AnchorPane getRootPage() {
return rootPane;
}
protected void makeFadeIn() {
FadeTransition fadeTransition = new FadeTransition();
fadeTransition.setDuration(Duration.millis(1000));
fadeTransition.setNode(rootPane);
fadeTransition.setFromValue(0);
fadeTransition.setToValue(1);
fadeTransition.play();
}
}
And then have the other controllers extend it:
public class StartController extends BaseController {
#FXML
private void loadSecondPage(ActionEvent event) throws IOException {
AnchorPane startPage =
FXMLLoader.load(getClass().getResource("SecondController.fxml"));
getRootPane().getChildren().setAll(startPage);
makeFadeIn();
}
}
public class SecondController extends BaseController {
#FXML
private void loadFirstPage(ActionEvent event) throws IOException {
AnchorPane startPage =
FXMLLoader.load(getClass().getResource("StartController.fxml"));
getRootPane().getChildren().setAll(startPage);
}
}

Change label text in a new scene which was entered in different scene (javafx)

I'm trying to change a text in a label, a text which was entered in a text field in a different scene.
I made 2 FXML files, the first one contains a textfield and "ok" button, the second one contains a label(with the text "Label").
My goal is to enter a text in the textfield, and when I press "ok"-> open the new scene and the label will change it's text to the text I entered in the text field.
I easily changed the label text when the label, the textfield and the ok button were all in the same scene, but when I do it while opening a new scene I fail...
After some research, I made a controller for each FXML file, and a "MainController" that will communicate between them.
This is my main class:
public class MainBanana extends Application {
#Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("view/Welcome.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("MokaApp");
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setResizable(false);
}
public static void main(String[] args) {
launch(args);
}
}
my first scene controller:
public class WelcomeController {
#FXML
public TextField nameField;
#FXML
private Button okButton;
private MainController main;
#FXML
public void okClicked(ActionEvent event) throws IOException{
Parent root = FXMLLoader.load(getClass().getResource("Person.fxml"));
okButton.getScene().setRoot(root);
System.out.println(nameField.getText());
main.setLblFromTf(nameField.getText());
}
public void init(MainController mainController) {
main=mainController;
}
}
second scene controller:
public class PersonController {
#FXML
public Label nameLabel;
private MainController main;
public void init(MainController mainController) {
main=mainController;
}
}
When I launch the program, The Welcome scene is opened, I enter a text to the textfield, but whenever I press the "ok" button, the scene changes to the second scene, but the label text stays the same(label) and I get a nullpointerexception error on this line(located in WelcomeController): main.setLblFromTf(nameField.getText());
Sorry for the long post..
You don't need the references to MainController all over the place.
The easiest way is:
public class PersonController {
#FXML
private Label nameLabel ;
public void setName(String name) {
nameLabel.setText(name);
}
}
Then you can do
public class WelcomeController {
#FXML
private TextField textField ;
#FXML
private Button okButton ;
#FXML
public void okClicked() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Person.fxml"));
Parent root = loader.load();
PersonController personController = loader.getController();
personController.setName(textField.getText());
okButton.getScene().setRoot(root);
}
}

Managing the runtime behavior of a JavaFX MenuBar

I have a BorderPane, onto which I placed a MenuBar. At the center of the BorderPane I display differnt AnchorPanes depending on the MenuItem selected. So far so good.
Now, how do I make sure that the Menus change behavior in response to the item selected in the child AnchorPane? So for example if the user selects "Edit", there will be a different action depending on whether the item currently higlighted is a user account, a file etc.
So far I made something along these lines:
The BorderPane controller:
public class MenuTest implements Initializable{
#FXML
private BorderPane borderPaneMain;
#FXML
private AnchorPane anchorPaneMain;
#FXML
private Menu menuEdit;
#FXML
private MenuItem itemEdit;
static String menuMode;
static String entityName;
public MenuTest(){
menuMode ="";
entityName = "";
}
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
AnchorPane anchor;
try {
anchor = (AnchorPane) new FXMLLoader().load(getClass().getResource("views/MainView.fxml"));
borderPaneMain.setCenter(anchor);
} catch (IOException e) {
e.printStackTrace();
}
}
protected static void setMenuMode(String menuMd, String entityNm){
entityName = entityNm;
menuMode = menuMd;
}
#FXML
private void onEditClick(){
if(entityName.equals(AnchorTest.FILE)){
//Launches correct edit view
new FXMLLoader().load(getClass().getResource("views/EditFile.fxml"));
//Passes the name of the entity so that the controller can retrieve its data
FileEditController.setFile(entityName);
}else if(entityName.equals(AnchorTest.PERSON)){
new FXMLLoader().load(getClass().getResource("views/EditPerson.fxml"));
PersonEditController.setFile(entityName);
}
}
}
The child AnchorPane controller:
public class AnchorTest implements Initializable{
public static final String PERSON = "PERSON";
public static final String FILE = "FILE";
ObservableList<String> peopleList;
ObservableList<String> fileList;
#FXML
private ListView<String> listPeople;
#FXML
private ListView<String> listFiles;
#Override
public void initialize(URL location, ResourceBundle resources) {
peopleList = FXCollections.observableArrayList("Frank","Matin","Anne");
fileList = FXCollections.observableArrayList("hello.txt","holiday.jpg","cv.doc");
listPeople.setItems(peopleList);
listFiles.setItems(fileList);
}
#FXML
private void personSelected(){
MenuTest.setMenuMode(this.PERSON, listPeople.getSelectionModel().getSelectedItem());
}
#FXML
private void fileSelected(){
MenuTest.setMenuMode(this.FILE, listFiles.getSelectionModel().getSelectedItem());
}
}
However I'm not sure that it's the best solution, especially considering the if/elseif statement will need to be altered whenever I add a new element type and its corresponding edit options. So is there any way that I can do this better?
I think if your application has only a few (2-4) different types of "things" that are represented by a AnchorPane, then your approach is totally fine. An alternative to your approach is the state pattern. In that case, your currently selected "item type" would be your state.

Categories

Resources