I'm creating a JavaFX FXML application and haven't been able to use the setSelected()
method to set one of two radio buttons by default in a toggle group. The toggle group is functioning normally, so it appears the radio button variables are being set correctly. However, radio1
is not selected as expected.
Following are the relevant sections of my application.
System Information
Product Version: NetBeans IDE 8.1 (Build 201510222201)
Updates: NetBeans IDE is updated to version NetBeans 8.1 Patch 1
Java: 1.8.0_171; Java HotSpot(TM) 64-Bit Server VM 25.171-b11
Runtime: Java(TM) SE Runtime Environment 1.8.0_171-b11
System: Mac OS X version 10.13.4 running on x86_64; UTF-8; en_US (nb)
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.ToggleGroup?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="400.0"
xmlns="http://javafx.com/javafx/8.0.141"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="inventory.view.AddPartController">
<fx:define>
<ToggleGroup fx:id="toggleGroup" />
</fx:define>
<children>
<RadioButton fx:id="radio1" mnemonicParsing="false"
onAction="#handleRadio1" prefHeight="30.0" prefWidth="100.0"
text="radio1" toggleGroup="$toggleGroup"
AnchorPane.rightAnchor="125.0" AnchorPane.topAnchor="25.0" />
<RadioButton fx:id="radio2" mnemonicParsing="false"
onAction="#handleRadio2" prefHeight="30.0" prefWidth="100.0"
text="radio2" toggleGroup="$toggleGroup"
AnchorPane.rightAnchor="25.0" AnchorPane.topAnchor="25.0" />
</children>
</AnchorPane>
Controller
package inventory.view;
import inventory.InventorySystem;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
public class AddPartController {
@FXML
private ToggleGroup toggleGroup;
@FXML
private RadioButton radio1;
@FXML
private RadioButton radio2;
@FXML
private void initialize() {
toggleGroup = new ToggleGroup();
radio1 = new RadioButton();
radio1.setToggleGroup(toggleGroup);
radio1.setSelected(true);
radio2 = new RadioButton();
radio2.setToggleGroup(toggleGroup);
}
}
Where am I going wrong?
You are reinitializing the radio button. The FXML will inject the reference, you are then overriding it. You also define the toggle group in your FXML - so you don't need that either.
Change your code to look like this:
@FXML
private void initialize() {
radio1.setSelected(true);
}