Setting Combobox value when switching screens - javafx

I want to switch between FXML-Files with Radiobuttons without losing the Combobox-Selection. "secSelectionModel()" seems to add a Selection, but its not visually shown.
public class Controller {
static SingleSelectionModel cbxSelection;
#FXML private ComboBox<String> cbx = new ComboBox<>();
#FXML private RadioButton radio1 = new RadioButton();
#FXML private RadioButton radio2 = new RadioButton();
#FXML private void cbxFill(){
cbx.getItems().setAll("eins","zwei");
}
#FXML private void screenSwitch() throws IOException {
Stage stage;
Parent root;
if(radio1.isSelected()){
stage=(Stage) radio1.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("sample.fxml"));
//cbxFill();
cbx.setSelectionModel(cbxSelection);
}
else{
stage=(Stage) radio2.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("sample2.fxml"));
//cbxFill();
cbx.setSelectionModel(cbxSelection);
}
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
#FXML private void getcbxSelection(){
cbxSelection=cbx.getSelectionModel();
}
}
If Radio2 is selected, I want to switch to Screen2 without losing the Entered Selection in the Combobox.

Related

JavaFX BorderPane

i'm trying to set on top of a borderpane an fxml hbox, the borderpane is inside another borderpane that contains all.
The containers are in this form:
Stage-> PincipalBorderPane -> Vbox(Center of MainMenuBorderPane)-> ContentBorderPane(in bottom of Vbox).
Also in the left of my PrincipalBorderPane, I have a sidebar menu that contains buttons, I want to set on the top of ContentBorderPane an fxml document that will be like an small menu to show buttons that would set on the bottom of ContentMenu different panes. The problem is that I don't know how to set an fxml to a borderpane that is inside another borderpane.
public class MenuContentController implements Initializable {
private boolean flag = true;
private boolean flagsc = true;
#FXML
private JFXButton Minbtn;
#FXML
private JFXButton Maxbtn;
#FXML
private JFXButton Closebtn;
#FXML
private JFXButton Sidebarbtn;
#FXML
private JFXTextField Searchtxt;
#FXML
private JFXButton Ingressbtn;
#FXML
private JFXButton Egressbtn;
#FXML
private JFXButton Statusbtn;
#FXML
private BorderPane ContentTools;
#FXML
private void open_sidebar(ActionEvent event) throws IOException {
BorderPane border_pane = (BorderPane) ((Node) event.getSource()).getScene().getRoot();
if (flag) {
//Revisar animación más adelante
Parent sidebar = FXMLLoader.load(getClass().getResource("/app/fxml/Sidebar.fxml"));
sidebar.translateXProperty();
//
border_pane.setLeft(sidebar);
//
Timeline timeline = new Timeline();
KeyValue kv = new KeyValue(sidebar.translateXProperty(),0,Interpolator.EASE_IN);
KeyFrame kf = new KeyFrame(Duration.seconds(10), kv);
timeline.getKeyFrames().add(kf);
timeline.play();
flag = false;
} else {
border_pane.setLeft(null);
flag = true;
}
}
**#FXML
public void open_admintools_priv(ActionEvent event) throws IOException{
ContentTools = new BorderPane();
BorderPane bp = (BorderPane) ContentTools;
if (flagsc) {
Parent admintools = FXMLLoader.load(getClass().getResource("/app/fxml/AdminTools.fxml"));
bp.setTop(admintools);
flagsc=false;
} else {
ContentTools.setTop(null);
flagsc = true;
}
System.out.println(flagsc);**
}
The method open_admintools_priv should to set visible on top of ContentTools(ContentBorderpane) the Admintools.fxml by pressing a button in another fxml(sidebar.fxml) that I set on the left of my PrincipalBorderPane with the method open_sidebar, that I call creating a new controller of MenuContentController in the SidebarController:
public class SidebarController implements Initializable {
private boolean flagsc = true;
#FXML
private JFXButton condominiobtn;
#FXML
private JFXButton adminbtn;
#FXML
private JFXButton finanzasbtn;
#FXML
private JFXButton reportesbtn;
#FXML
private JFXButton confbtn;
#FXML
private void open_admintools(ActionEvent event) throws IOException{
MenuContentController aux = new MenuContentController();
aux.open_admintools_priv(event);
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
Another problem is that by this way, at the moment I create a MenuContentController, the variable flag is always on true, this variable I use it to set the fxml in borderpane when flag is true, or quit it when flag is false. I don't know if creating an instance of a controller is the way to acces to the objects of that fxml, thanks for your time.

Hide checkbox in java with Scenebuilder

I am working with eclipse jee photon and scenebuilder.
What I am trying to do:
I have a choicebox with two labels:
ObservableList labelList = FXCollections.observableArrayList("examlpe01", "example02");
If example01 is chosen, the checkbox should be visible but disabled. If example02 is chosed the checkbox should be visible and it should be possible to check it.
Here is my code:
public class newUser{
ObservableList <String> labelList = FXCollections.observableArrayList("example01", "example02");
#FXML
private TextField name;
#FXML
private TextField lastName;
#FXML
private Button saveUser;
#FXML
private CheckBox adminRights;
#FXML
private TextField emailAdress;
#FXML
private TextField password;
#FXML
private Button userSpeichern;
#FXML
private MenuButton userDropDown;
#FXML
private MenuItem adminpage;
#FXML
private MenuItem example01;
#FXML
private MenuItem example02;
#FXML
private MenuItem logout;
#FXML
private ChoiceBox label;
#FXML
private void initialize() {
label.setItems(labelList);
label.setValue("mm");
}
#FXML
void logout(ActionEvent event) throws IOException {
Parent Login = FXMLLoader.load(getClass().getClassLoader().getResource("fxml/Login.fxml"));
Scene Login_scene = new Scene(Login);
Stage app_stage = (Stage) userDropDown.getScene().getWindow();
app_stage.setScene(Login_scene);
app_stage.show();
}
DbHelper db = new DbHelper();
private void showCheckbox() {
if (label.equals("example02")) {
}
}
#FXML
void saveUserData(ActionEvent event) {
}
Use this:
#FXML
ChoiceBox choiceBox;
#FXML
CheckBox checkBox;
#FXML
private void choiceBoxOnClicked() {
if (choiceBox.getValue().equals("example01")) {
checkBox.setDisable(true);
} else if (choiceBox.getValue().equals("example02")) {
checkBox.setDisable(false);
}
}
So this should work.

How to load image in ImageView dynamically in Java FX

I'm working with FXML and have two different Scene on a single Stage. btnStart is on scene1, and imgBtn is on scene2. When I click btnStart it sets scene2 to stage and loads an image to imageView (this is throwing NullPointerException). But when I click imgBtn on scene2 it is loading image.
My question is how to load image dynamically when I switch to scene2 ?
#FXML private Button imgBtn;
#FXML private Button btnStart;
#FXML public ImageView imageView;
#FXML
public void imgBtnClicked()throws Exception{
imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));
}
#FXML
public void btnStartClicked()throws Exception{
SetScene2();
imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));
}
public void SetScene2()throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(fxmlFile2.fxml));
String css=getClass().getResource("myStyle.css").toExternalForm();
Scene scene;
try{
scene=new Scene(root,root.getScene().getWidth(),root.getScene().getHeight());
}
catch(NullPointerException e) {
scene=new Scene(root,stage.getWidth(),stage.getHeight());
}
scene.getStylesheets().add(css);
stage.setScene(scene);
}
The question is not exactly very clear, so I'm going to make some guesses here. The most likely problem is that you have confused which Nodes are on which scene which is on which controller.
The correct structure for this is that you have two sets of each of the following items:
FXML file
Controller class
Scene object.
This is how it should be done:
public class ControllerA {
#FXML private Button btnStart;
#FXML
public void btnStartClicked()throws Exception{
setScene2();
}
public void setScene2()throws Exception {
// You may need to set the controller to an instance of ControllerB,
// depending whether you have done so on the FXML.
Parent root = FXMLLoader.load(getClass().getResource(fxmlFile2.fxml));
String css=getClass().getResource("myStyle.css").toExternalForm();
Scene scene;
try{
scene=new Scene(root,root.getScene().getWidth(),root.getScene().getHeight());
}
catch(NullPointerException e) {
scene=new Scene(root,stage.getWidth(),stage.getHeight());
}
scene.getStylesheets().add(css);
stage.setScene(scene);
}
}
public class ControllerB {
#FXML private ImageView imageView;
#FXML private Button imgBtn;
#FXML public void initialize() {
imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));
}
#FXML
public void imgBtnClicked()throws Exception{
imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));
}
}

nested child call to super parent

i m new to javafx so please ignore my silly question here is problem i m facing from 2 day it would we great if any body help me
i have super parent (main view) in that country fxml view get loader
and in country fxml i have one more fxml(call table) that loaded into country
when user click on any data of table view new fxml file get loaded and that file i want to get load into parent i had used super parent stack pane id it throw an error please help me why this happening any solution link ,code or suggestion it will save my day
here is code
ObservableList<addcountryController> data = FXCollections.observableArrayList();
private Pagination pagination;
#FXML
private AnchorPane cresult;
#FXML
private StackPane stackconsearch;
#FXML
private StackPane stackhome;
#FXML
private AnchorPane stackanc;
#FXML
private StackPane stackcountry;
#FXML
private TableView<addcountryController> tableUser;
#FXML
private TableColumn<addcountryController, String> columnName;
#FXML
private TableColumn<addcountryController, String> columnDesc;
DatabaseHandler databaseHandler;
public void setText(String first,String sec){
this.country.setText(first);
this.desc.setText(sec);
}
#Override
public void initialize(URL location, ResourceBundle resources) {
databaseHandler = DatabaseHandler.getInstance();
initCol();
String qu = "SELECT * FROM country_tbl ";
ResultSet rs = databaseHandler.execQuery(qu);
try {
while (rs.next()) {
String id= rs.getString("id");
String name= rs.getString("countryname");
String description = rs.getString("descr");
String country2char= rs.getString("country2char");
String descrshort = rs.getString("descrshort");
data.add(new addcountryController(id,name, description,country2char,descrshort));
}
}catch (SQLException ex) {
Logger.getLogger(addcountryController.class.getName()).log(Level.SEVERE, null, ex);
}
tableUser.setItems(null);
tableUser.setItems(data);
tableUser.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
tableUser.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<addcountryController>() {
public void onChanged(ListChangeListener.Change<? extends addcountryController> c) {
try {
Stage primaryStage=new Stage();
FXMLLoader loader =new FXMLLoader();
loader.load(getClass().getResource("/region/updatecountry.fxml").openStream());
updatecountryController usercontroller=(updatecountryController)loader.getController();
for (addcountryController p : c.getList()) {
String ADDID=p.getId();
String ADD=p.getName();
String ADD1=p.getDescriptionshort();
String ADD2=p.getDescription();
String ADD3=p.getCountrychar();
usercontroller.setText(ADDID,ADD,ADD1,ADD2,ADD3);
}
StackPane root = loader.getRoot();
stackconsearch.getChildren().clear();
stackconsearch.getChildren().add(root);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
here is my editcontroller
private StackPane stackhome;
#FXML
private StackPane stackconsearch;
#FXML
private AnchorPane cresult;
#FXML
private TextField country;
#FXML
private TextField desc;
public void add(ActionEvent event) {
String ADD=countrycode.getText();
try {
if(ADD.isEmpty()){
Alert alert=new Alert(Alert.AlertType.ERROR);
alert.setHeaderText(null);
alert.setContentText("Please Fill All DATA");
alert.showAndWait();
return;
}
FXMLLoader loader =new FXMLLoader();
loader.load(getClass().getResource("/region/newCountry.fxml").openStream());
MainController usercontroller=(MainController)loader.getController();
usercontroller.setText(ADD);
StackPane root = loader.getRoot();
stackconsearch.getChildren().clear();
stackconsearch.getChildren().add(root);
}catch(Exception e) {
e.printStackTrace();
}
}
public void search(ActionEvent event) {
String countrytxt=country.getText();
String desctxt=desc.getText();
if(countrytxt.isEmpty() && desctxt.isEmpty()) {
try{
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.load(getClass().getResource("/region/cresult.fxml").openStream());
StackPane root = fxmlLoader.getRoot();
root.getStylesheets().add(getClass().getResource("/application/application.css").toExternalForm());
countryController usercontroller=(countryController)fxmlLoader.getController();
usercontroller.setText(countrytxt,desctxt);
cresult.getChildren().clear();
cresult.getChildren().add(root);
}catch(IOException e){
e.printStackTrace();
}
}else{
try{
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.load(getClass().getResource("/region/cresult.fxml").openStream());
StackPane root = fxmlLoader.getRoot();
countryController usercontroller=(countryController)fxmlLoader.getController();
usercontroller.setText(countrytxt,desctxt);
cresult.getChildren().clear();
cresult.getChildren().add(root);
}catch(IOException e){
e.printStackTrace();
}
}
}
here is main controller
#FXML
private StackPane stackhome;
#FXML
private AnchorPane Mainview;
#FXML
private AnchorPane stackanc;
#Override
public void start(Stage primaryStage) {
try {
Parent root =FXMLLoader.load(getClass().getResource("Main.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
#FXML
public void country(ActionEvent event) {
FXMLLoader fxmlLoader = new FXMLLoader();
try {
fxmlLoader.load(getClass().getResource("/region/country.fxml").openStream());
} catch (IOException e) {
}
StackPane root = fxmlLoader.getRoot();
stackhome.getChildren().clear();
stackhome.getChildren().add(root);
}
public static void main(String[] args) {
launch(args);
}
here is stackhome is super parent and stackcountry is parent and child of super parent and i have one more parent stacksub which is child of stackhome,stackcountry and it has child called as stackchild i want to load this stackchild to stackhome but it not working any suggestion

how to share data between two stages in javafx

I have two fxml window login and main window.Their respective controllers are given below:
public class MainwindowController extends Stage implements Initializable {
#FXML private Button Send;
#FXML private TextField txtBcast;
#FXML private ListView listviewUsers;
#FXML Label lblDisplayName;
/**
* Initializes the controller class.
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList<String> chat =FXCollections.observableArrayList ("default");
listviewUsers.setItems(chat);
}
public void setLblName(String msg){
lblDisplayName.setText(msg);
}
#FXML public void ActionSend(ActionEvent e){
send();
txtBcast.setText("");
}
private void send() {
if (txtBcast.getText().isEmpty())
return;
// chatManager.sendPublicMsg(format,txtBcast.getText());
}
/**
*
* #param e
* #throws Exception
*/
#FXML public void ActionUserSelected( MouseEvent e) throws Exception{
// String lineRest = e.getActionCommand();
if(e.getClickCount()==2)
{
if(!listviewUsers.getSelectionModel().isEmpty())
{
String str=(String)listviewUsers.getSelectionModel().getSelectedItem();
Parent main= FXMLLoader.load(getClass().getResource("/letschat/fxwindows/Usertab.fxml"));
Scene scene = new Scene(main);
Stage stage = new Stage();
stage.setTitle(str);
stage.setScene(scene);
stage.show();
}
else { JOptionPane.showMessageDialog(null, "Oops! it seems you are trying to click the list view"); }
}
//Stage pstage = (Stage)listUsers.getScene().getWindow();
//pstage.close();
}
}
And
public class LoginwindowController extends Stage implements Initializable {
#FXML private LoginwindowController loginwindowController;
#FXML private MainwindowController mainwindowController;
#FXML private Button btnSignIn;
#FXML private TextField txtDisplayName;
#FXML private ToggleGroup Gender;
#FXML private ComboBox comboStatus;
/**
* Initializes the controller class.
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList<String> items =FXCollections.observableArrayList ("Online","Offline");
comboStatus.setItems(items);
writeToTextField();
}
public void writeToTextField() {
String username = System.getProperty("user.name");
txtDisplayName.setText(""+ username);
}
#FXML protected void ActionSignIn(ActionEvent event) throws Exception {
mainwindowController.setLblName(txtDisplayName.getText());
InetAddress addr = InetAddress.getLocalHost();
if(addr.isLoopbackAddress())
{
Dialogs.create().message("Oops! It seems you are not connected to any network..\n :(").showError();
}
else{
start(txtDisplayName.getText());// start chat manager
Parent root= FXMLLoader.load(getClass().getResource("/letschat/fxwindows/Mainwindow.fxml"));
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setTitle("LetsChat-Welcome "+ txtDisplayName.getText());
// Context.getInstance().setDisplayName(txtDisplayName.getText());
stage.setScene(scene);
stage.getIcons().add(new Image("/letschat/images/logo.png"));
Stage pstage = (Stage)btnSignIn.getScene().getWindow();
stage.show();
pstage.close();
}
}
private void start(String name) {
try {
ChatManager ic = new ChatManager(name);
ic.start();
} catch (Exception ex) {
Dialogs.create().message( "Could not start the chat session\nCheck that there no other instances running :(").showError();
}
}
}
I want the label lblDisplayName in main window updated with text from txtDisplay Name in login window when user clicks signin button.can someone help how to do so..soon plz
There are various ways to do this, in your case Login will create the other stage so an easy way is to create a new FXML loader (variable name: myLoader) and, if you want to pass the username of the user as constructor argument you can use myLoader.setControllerFactory and as return:
return clazz == MyController.class ? new MyController(userName) : null;
MyController is the name of the Controller where you want to read the username
If you want to use set methods, with getController you get the controller instance and call the set method (e.g, myController.setUsername());
To create a custom FXML
FXMLLoader myLoader = new FXMLLoader(<if you use relative paths, here you should pass the position);
remember to call the load() because the URI overload is static. (i.e, use getResourceAsStream).
If your application is large and complex, you could use EventBus (which I prefer everywhere..)
I'm not sure I completely understand the relationship between the two controllers, and which are the FXML files that correspond to the controllers, but it looks like the LoginWindowController loads MainWindow.fxml, and I'm guessing that MainWindowController is the controller for MainWindow.fxml.
In that case, you can just do
#FXML protected void ActionSignIn(ActionEvent event) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
if(addr.isLoopbackAddress())
{
Dialogs.create().message("Oops! It seems you are not connected to any network..\n :(").showError();
}
else{
start(txtDisplayName.getText());// start chat manager
FXMLLoader loader = new FXMLLoader(getClass().getResource("/letschat/fxwindows/Mainwindow.fxml"));
Parent root= loader.load();
MainWindowController mainWindowController = loader.getController();
mainWindowController.setLblName(txtDisplayName.getText());
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setTitle("LetsChat-Welcome "+ txtDisplayName.getText());
// Context.getInstance().setDisplayName(txtDisplayName.getText());
stage.setScene(scene);
stage.getIcons().add(new Image("/letschat/images/logo.png"));
Stage pstage = (Stage)btnSignIn.getScene().getWindow();
stage.show();
pstage.close();
}
}

Resources