How to set the value of combobox from the elements present in that combobox in java/javafx. This is the code what i have done till now.
package LetMeTest;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import java.net.URL;
import java.util.ArrayList;
import java.util.Observable;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
public class TryController implements Initializable {
#FXML
private JFXComboBox<?> cb;
#FXML
private JFXButton btnGet;
#FXML
private JFXButton btnSet;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb)
{
ObservableList oo=FXCollections.observableArrayList("b","a");
cb.setItems(oo);
}
#FXML
private void doGetItem(ActionEvent event)
{
System.out.println("Selected Item="+cb.getSelectionModel().getSelectedItem());
}
#FXML
private void doSetItem(ActionEvent event)
{
cb.setValue("b");
}
}
I am trying to do it using ObservableList. Tell me there is any other possibility to do it.
Related
How can I change a scene without directly interacting with it (like using a button). What I would like for my program to do is change scene, and then using the Initializable class, the program would wait 1.5 seconds then change scene.
I am currently using a PauseTransition to do this, however I get a ClassCastException. Also, I do not understand what Intellij is trying to tell me about the Node. It says 'Find why 'event.getSource()' could be javafx.animation.PauseTransition (not-null)'.
Thanks in advance.
Stack Trace:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: class javafx.animation.KeyFrame cannot be cast to class javafx.scene.Node (javafx.animation.KeyFrame and javafx.scene.Node are in module javafx.graphics of loader 'app')
at Dice.Game/sample.RoundCounterController.lambda$initialize$0(RoundCounterController.java:54)
at javafx.graphics/com.sun.scenario.animation.shared.TimelineClipCore.visitKeyFrame(TimelineClipCore.java:239)
at javafx.graphics/com.sun.scenario.animation.shared.TimelineClipCore.playTo(TimelineClipCore.java:180)
at javafx.graphics/javafx.animation.Timeline.doPlayTo(Timeline.java:177)
at javafx.graphics/javafx.animation.AnimationAccessorImpl.playTo(AnimationAccessorImpl.java:39)
at javafx.graphics/com.sun.scenario.animation.shared.SingleLoopClipEnvelope.timePulse(SingleLoopClipEnvelope.java:99)
at javafx.graphics/javafx.animation.Animation.doTimePulse(Animation.java:1101)
at javafx.graphics/javafx.animation.Animation$1.lambda$timePulse$0(Animation.java:186)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/javafx.animation.Animation$1.timePulse(Animation.java:185)
at javafx.graphics/com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(AbstractMasterTimer.java:344)
at javafx.graphics/com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(AbstractMasterTimer.java:267)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:515)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:499)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:492)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:320)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:829)
RoundCountController.java
import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.animation.Transition;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class RoundCounterController implements Initializable {
#FXML private Label roundLabel;
private static int roundCounter = 0;
#FXML private AnchorPane pane;
private Stage stage;
private Scene scene;
private Parent root;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
PauseTransition pauseTransition = new PauseTransition(Duration.seconds(1.5));
pauseTransition.setOnFinished(event -> {
try {
Parent root = FXMLLoader.load(getClass().getResource("p1GameScene.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
scene = new Scene(root);
stage.setScene(scene);
stage.show();
});
pauseTransition.play();
}
}
In this program, you can add words to the ComboBox using a textfield. How would you make it so the program will not accept any words that are already in the ComboBox? I tried to make it so if the textfield input is equal to something in the ComboBox then it shouldn't add it but it will not work.
package gps_destinations_controller;
import gps_destinations_model.Model;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.control.TextField;
public class Controller implements Initializable
{
#FXML TextField destinationInput;
#FXML ComboBox<String> destinationList;
private SingleSelectionModel<String> selectionModel;
private Model model;
#Override
public void initialize(URL url, ResourceBundle rb)
{
model = new Model();
destinationList.getItems().addAll(model.getDestinations());
selectionModel = destinationList.getSelectionModel();
selectionModel.select(model.getSelectedIndex());
System.out.println(destinationList.getItems());
}
#FXML protected void addDestination()
{
String input = destinationInput.getText();
if(!destinationList.getItems().equals(input))
{
destinationList.getItems().add(input);
}
model.addDestination(input);
destinationInput.clear();
}
#FXML protected void itemSelected( ActionEvent event )
{
int index = selectionModel.getSelectedIndex();
model.updateSelection(index);
}
}
You're comparing the items list itself to the element you want to add. This always results in false and the item is always added. You need to use contains to check, if an element is already in the list:
if(!destinationList.getItems().contains(input)) {
destinationList.getItems().add(input);
}
I am trying to set the focus on the JTextPane so that when the window opens it can immediately be edited with the keyboard. However, nothing I've done seems to give the JTextPane focus on startup. Is this just an issue with using JavaFX with Swing?
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingNode;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javax.swing.*;
public class TestDialog {
#FXML
private ListView listView;
#FXML
private SwingNode node;
private ObservableList<Integer> obsList;
#FXML
public void initialize(){
JTextPane pane = new JTextPane();
SwingUtilities.invokeLater(() -> pane.requestFocusInWindow());
pane.setText("This issue is not reproducible in JDK 8 early-access build (8u172) which is yet to be released.");
node.setContent(pane);
obsList = FXCollections.observableArrayList();
for(int x = 0; x < 12; x++){
obsList.add(x);
}
listView.setItems(obsList);
node.setFocusTraversable(true);
node.requestFocus();
pane.requestFocus();
pane.grabFocus();
}
#FXML
private void removeItem(ActionEvent event) {
obsList.remove(0);
}
}
It's working now thanks to a solution from BWC_semaJ. Rather than using:
SwingUtilities.invokeLater(() -> pane.requestFocusInWindow());
I should have used:
Platform.runLater(() -> {swingNode.requestFocus();}); //Use this instead
I don't know if this helps but below is the demo program I made based on the sample code and for some reason it works for me:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingNode;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javax.swing.*;
public class Test extends Application {
#FXML
private ListView listView;
#FXML
private SwingNode node;
private ObservableList<Integer> obsList;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage arg0) throws Exception {
initialize(arg0);
}
#FXML
public void initialize(Stage stage){
JTextPane pane = new JTextPane();
// The program runs the same no matter if one of the below two lines are used or if neither are used
//SwingUtilities.invokeLater(() -> pane.requestFocusInWindow());
//Platform.runLater(() -> {node.requestFocus();});
pane.setText("This issue is not reproducible in JDK 8 early-access build (8u172) which is yet to be released.");
node = new SwingNode();
node.setContent(pane);
obsList = FXCollections.observableArrayList();
for(int x = 0; x < 12; x++){
obsList.add(x);
}
listView = new ListView();
listView.setItems(obsList);
node.setFocusTraversable(true);
node.requestFocus();
pane.requestFocus();
pane.grabFocus();
StackPane root = new StackPane();
root.getChildren().add(node);
Scene scene = new Scene(root, 500, 500);
stage.setTitle("Test");
stage.setScene(scene);
stage.show();
}
#FXML
private void removeItem(ActionEvent event) {
obsList.remove(0);
}
}
Why does the following code always show null in the console when I want to get the controller ?
RenewCardFXML2_controller controller=loader.getController();
and the console prints null when i press the button.
I have two controllers and want to use textfield from the main app(membershipcards)-txt_numberOfCard_GENERAL inside the second fxml file whick has its own controller.
txt_numberOfCard_GENERAL.getText command from seccond controller and use its value.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package membershipcards;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.SplitPane;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import membershipcards.RenewCardFXML2_controller;
/**
*
* #author Primary
*/
public class mainGUIController implements Initializable {
#FXML
private ImageView logoimg;
#FXML
private SplitPane splitMenuContent;
#FXML
private Button btnCards;
#FXML
private Button btnRenewCard;
#FXML
private Button bntNewClient;
#FXML
private Button btnEditCard;
#FXML
private Button btnStatistics;
#FXML
private AnchorPane detailsPane;
#FXML
private Button btnCardN;
#FXML
public TextField txt_numberOfCard_GENERAL;
#FXML
public TextField txt_memberName_GENERAL;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void loadCardsFXML1(ActionEvent event) {
try {
detailsPane = (AnchorPane) FXMLLoader.load(getClass().getResource("CardsFXML1.fxml"));
} catch (IOException ex) {
Logger.getLogger(mainGUIController.class.getName()).log(Level.SEVERE, null, ex);
}
splitMenuContent.getItems().set(1, detailsPane);
}
#FXML
private void loadRenewCardFXML2(ActionEvent event)throws IOException {
FXMLLoader loader = new FXMLLoader();
detailsPane = (AnchorPane) loader.load(getClass().getResource("RenewCardFXML2.fxml"));
splitMenuContent.getItems().set(1, detailsPane);
RenewCardFXML2_controller controller=loader.getController();
controller.setMGC(this);
System.out.println(controller);
}
}
The FXMLLoader.load(URL) method you are calling is a static method. Consequently, you have not called load on the FXMLLoader instance you created, and since that instance hasn't loaded the FXML, it has not initialized its controller field.
(A good IDE will give you a warning on your loader.load(...) line about calling a static method from a non-static context, or something similar. Eclipse, for example, says "The static method load(URL) should be accessed in a static way.")
The following will work:
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("RenewCardFXML2.fxml"));
detailsPane = loader.load();
splitMenuContent.getItems().set(1, detailsPane);
RenewCardFXML2_controller controller=loader.getController();
Note that you can reduce the first two lines of that code block to a single line
FXMLLoader loader = new FXMLLoader(getClass().getResource("RenewCardFXML2.fxml"));
detailsPane = loader.load();
I am trying to trigger an action on default value of the combo box when it is initialized but I'm only able to find the method to trigger an action when the value is changed using method print() set in OnAction of ComboBox.
Here is my presenter of the FXML file:
package tre;
import java.net.URL;
import java.util.ResourceBundle;
import javax.swing.event.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
public class presenter implements Initializable {
public #FXML ComboBox<String> combo;
private final ObservableList<String> statistic = FXCollections.observableArrayList("Logged In", "Anonymous",
"Logged Off");
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
combo.setItems(statistic);
combo.setValue("Anonymous");
//TODO When Anonymous is displayed as default value in the combo box, it will print it.
}
public #FXML void print(){
String sel = combo.getSelectionModel().getSelectedItem();
System.out.println(sel);
}
}
Is there a solution for it? Thanks