I don't have quite much information, but perhaps someone was facing the same problem. I wrote an application for some friends, and it includes some Alert Dialogues. The problem is that the alerts are not showing on one of the pcs it was tested (but on my pc, it does!). I have Windows 10 and Java 1.8.0_51, the testing system had Windows 7 and Java 1.8.0_60.
I styled it with css. This is how I implemented it (alarm is just an audioclip):
public void play(Stage stage, Callable<Void> func){
if (alert == null) {
alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Alarm");
alert.setHeaderText(LanguageLoader.getInstance().getLocalizedString("alarmDialog"));
alert.initOwner(stage);
alarm.setCycleCount(Timeline.INDEFINITE);
}
if (!alert.isShowing()) {
alarm.play();
stage.toFront();
stage.requestFocus();
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
alarm.stop();
try {
func.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
alert.show();
}
}
Edit: I updated to 1.8.0_60 too, and the dialog isn't showing on my system either!
This is the exception I get:
Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: showAndWait is not allowed during animation or layout processing
at javafx.scene.control.Dialog.showAndWait(Unknown Source)
at utils.Alarm.play(Alarm.java:38)
at note.NoteController.update(Controller.java:76)
at java.util.Observable.notifyObservers(Unknown Source)
at java.util.Observable.notifyObservers(Unknown Source)
at note.NoteModel.update(Model.java:57)
at java.util.Observable.notifyObservers(Unknown Source)
at java.util.Observable.notifyObservers(Unknown Source)
at utils.Watch.lambda$0(Clock.java:35)
at com.sun.scenario.animation.shared.TimelineClipCore.visitKeyFrame(Unknown Source)
at com.sun.scenario.animation.shared.TimelineClipCore.playTo(Unknown Source)
at javafx.animation.Timeline.impl_playTo(Unknown Source)
at javafx.animation.AnimationAccessorImpl.playTo(Unknown Source)
at com.sun.scenario.animation.shared.InfiniteClipEnvelope.timePulse(Unknown Source)
at javafx.animation.Animation.impl_timePulse(Unknown Source)
at javafx.animation.Animation$1.lambda$timePulse$26(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javafx.animation.Animation$1.timePulse(Unknown Source)
at com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(Unknown Source)
at com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$405(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
I use a timeline in the class Clock.. I guess that's the problem. can I build a working clock without using timeline?
It seemes like in Java 1.8.0_60, the showAndWait() method of the class Alert can't be called during an animation (basically that's what the exception says). The problem was that I used a timeline to check the system time, and showed an alarm when a certain time is reached. To solve the problem, I changed
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
alarm.stop();
try {
func.call();
} catch (Exception e) {
e.printStackTrace();
}
}
to this:
alert.showingProperty().addListener((observable,oldValue,newValue)->{
if (!newValue){
alarm.stop();
try {
func.call();
} catch (Exception e) {
e.printStackTrace();
}
}
});
So instead of waiting for some input, it simply listens to changes in the showing property. Don't know how to fix this if you use other alerts with more buttons though.
Related
I'm trying to make a sound of Windows play when the user clicks the button. The code is just below:
public class TestController extends Application {
public String audio = getClass().getResource("src/Sounds/WindowsError.wav").toString();
#FXML
private Button playbt;
#FXML
void playtest(MouseEvent event)
{
System.out.println("Clicked!");
AudioClip clip = new AudioClip(audio);// 1
clip.play(); // 2
}
#Override
public void start(Stage primaryStage) {
try
{
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/FXML/Test.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root);
primaryStage.setTitle("Test");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
The controller is properly configured to FXML. However, when I try to run the project, the following error occurs.
Exception in Application constructor java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class Controller.TestController
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$159(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$165(LauncherImpl.java:819)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$179(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$177(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$178(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$152(WinApplication.java:177)
... 1 more
Caused by: java.lang.NullPointerException
at Controller.TestController.<init>(TestController.java:17)
... 13 more Exception running application Controller.TestController
The files in my project are arranged as follows:
Does anyone know why this error occurs? The project hangs when opening due to the sound playback code.
I'm not totally solid on this, but I think the syntax of the getResource for the audio variable is in "relative address" form since it doesn't start with "/". In other words, it could be looking for a subfolder src in Controller package folder.
Maybe the following will help the system locate your audio resource:
public String audio = getClass().getResource("../Sounds/WindowsError.wav").toString();
Perhaps it would be good to move this line into the start() method, and run a System.out.println(audio) to inspect what you have at that point.
EDIT: just saw fabian's comment. Changing to the form using the classpath root as he suggests might be a better general practice than my suggestion to use a relative path.
i just want to download an image from Firebase storage,but i am having these issues.My google play service is up to date.I have an image "dog.jpg" in bucket and no other file.
Firebase bucket
My mainActivity code
public class MainActivity extends AppCompatActivity {
private StorageReference pathRef = FirebaseStorage.getInstance().getReference().child("dog.jpg");
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageView);
}
public void getImage(View v){
File localFile;
try {
localFile = File.createTempFile("images","jpg");
pathRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Local temp file has been created
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//handle error
Toast.makeText(MainActivity.this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_LONG).show();
}
});
}catch (IOException exception){
Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_SHORT).show();
}
}
}
Errors i am getting.
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11020000 but found 9683470
W/DynamiteModule: Local module descriptor class for com.google.android.gms.firebasestorage not found.
I/DynamiteModule: Considering local module com.google.android.gms.firebasestorage:0 and remote module com.google.android.gms.firebasestorage:0
E/NetworkRqFactoryProxy: NetworkRequestFactoryProxy failed with a RemoteException:
com.google.android.gms.dynamite.DynamiteModule$zzc: No acceptable module found. Local version is 0 and remote version is 0.
at com.google.android.gms.dynamite.DynamiteModule.zza(Unknown Source)
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/FileDownloadTask: Unable to create firebase storage network request.
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: null
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: null
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
whats wrong with my code...i even tried it on real device but still unable to download this file my storage rules are:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write:if true
}
}
}
Your Play services is not up to date as you suggest. This error message tells you what's going on:
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11020000 but found 9683470
The message suggests that you're using client library version 11.0.2, but Play services 9.6.83 is installed on the device. The version of Play has to be greater than or equal to the version of the client library in order for things to work.
Hi I am learning JFX and trin to write a simple jtable example and I am getting a error when running the application
my code snippet error comes is
itemPrice.setCellValueFactory(new PropertyValueFactory<Item, Double>("itemPrice"));
itemPrice.setCellFactory(TextFieldTableCell.forTableColumn());
itemPrice.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Item, Double>>() {
#Override
public void handle(TableColumn.CellEditEvent<Item, Double> t) {
((Item) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemPrice(t.getNewValue());
}
Error is
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
at javafx.util.converter.DefaultStringConverter.toString(DefaultStringConverter.java:34)
at javafx.scene.control.cell.CellUtils.getItemText(CellUtils.java:100)
at javafx.scene.control.cell.CellUtils.updateItem(CellUtils.java:201)
at javafx.scene.control.cell.TextFieldTableCell.updateItem(TextFieldTableCell.java:204)
at javafx.scene.control.TableCell.updateItem(TableCell.java:663)
at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:523)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64)
at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
at javafx.scene.control.Control.impl_processCSS(Control.java:859)
at javafx.scene.Node.processCSS(Node.java:9035)
at javafx.scene.Node.applyCss(Node.java:9132)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1957)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCell(VirtualFlow.java:1790)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCellLength(VirtualFlow.java:1872)
at com.sun.javafx.scene.control.skin.VirtualFlow.computeViewportOffset(VirtualFlow.java:2511)
at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1189)
at javafx.scene.Parent.layout(Parent.java:1076)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Scene.doLayoutPass(Scene.java:552)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2397)
at com.sun.javafx.tk.Toolkit.lambda$runPulse$30(Toolkit.java:314)
at com.sun.javafx.tk.Toolkit$$Lambda$216/252608964.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:313)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:340)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:525)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:505)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$400(QuantumToolkit.java:334)
at com.sun.javafx.tk.quantum.QuantumToolkit$$Lambda$42/820829455.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$38/1329190985.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
and I know this is due to casting issue in java but duno how edit handler works in JFX same code for string data type works how to fix, Help/Tip Please
Use
itemPrice.setCellFactory(TextFieldTableCell.forTableColumn(new DoubleStringConverter()));
So I was trying to launch my JavaFX application and a stack trace error showed up:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
And I wondered what was going. At the bottom of the stack trace it says there's a NullPointer at the launch(args) method. I tried everything but I couldn't get it to work. This is my code:
public class Main extends Application{
public void main(String[] args){
launch(args);
}
//START
//GUI
#Override
public void start(Stage primarystage) throws Exception {
SplitPane fullpane = new SplitPane();
//DECK
ScrollPane deckscrollpane = new ScrollPane();
AnchorPane deck = new AnchorPane();
deck.setOnMouseClicked((e)->{
System.out.println(e.getSceneX());
System.out.println(e.getSceneY());
});
Rectangle rec = new Rectangle();
rec.setTranslateX(23);
rec.setTranslateY(20);
rec.setWidth(200);
rec.setHeight(300);
deck.getChildren().add(rec);
deckscrollpane.setContent(deck);
//MAP
StackPane map = new StackPane();
fullpane.getItems().addAll(deckscrollpane, map);
fullpane.setDividerPositions(0.4f, 0.6f);
Scene scn = new Scene(fullpane, 700, 700);
primarystage.setScene(scn);
primarystage.show();
}
}
I'm pretty new to JavaFX, and I was hoping someone fairly experienced can explain how I'm supposed to fix this. My IDE (Eclipse) isn't showing any errors in the code either. The error only pops up when I run the program. I installed the JavaFX plugin (I think it's called something like e(fx)clipse or somethin' like that). A little help?
I want to include checks for my combobox to restrict "access" to some of the values. I could just remove those unaccessible items from the list, yes, but I'd like the user to see the other options, even if he can't select them (yet).
Problem: Selecting another value inside a changelistener causes an IndexOutOfBoundsException, and I have no idea why.
Here is a SSCCE. It creates a ComboBox with Integer values, and the first one is selected on default. Then I tried to keep it very easy: Every change of the value is considered as "wrong" and I change the selection back to the first element. But still, IndexOutOfBounds:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
public class Tester extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
ComboBox<Integer> box = new ComboBox<Integer>();
ObservableList<Integer> vals= FXCollections.observableArrayList(0,1,2,3);
box.setItems(vals);
box.getSelectionModel().select(0);
/*box.valueProperty().addListener((observable, oldValue, newValue) -> {
box.getSelectionModel().select(0);
});*/
/*box.getSelectionModel().selectedItemProperty().addListener((observable,oldValue,newValue)->{
System.out.println(oldValue+","+newValue);
box.getSelectionModel().select(0);
});*/
box.getSelectionModel().selectedIndexProperty().addListener((observable,oldValue,newValue)->{
System.out.println(oldValue+","+newValue);
box.getSelectionModel().select(0);
});
Scene scene = new Scene(new Group(box),500,500);
stage.setScene(scene);
stage.show();
}
}
I tested it with valueProperty, selectedItemProperty and selectedIndexProperty, as well as all of these:
box.getSelectionModel().select(0);
box.getSelectionModel().selectFirst();
box.getSelectionModel().selectPrevious();
box.setValue(0);
if (oldValue.intValue() < newValue.intValue())
box.getSelectionModel().select(oldValue.intValue());
The only think that works is setting the value itself:
box.getSelectionModel().select(box.getSelectionModel().getSelectedIndex());
box.setValue(box.getValue));
Here is the exception:
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(Unknown Source)
at javafx.collections.ListChangeListener$Change.getAddedSubList(Unknown Source)
at com.sun.javafx.scene.control.behavior.ListViewBehavior.lambda$new$178(Unknown Source)
at com.sun.javafx.scene.control.behavior.ListViewBehavior$$Lambda$126/644961012.onChanged(Unknown Source)
at javafx.collections.WeakListChangeListener.onChanged(Unknown Source)
at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(Unknown Source)
at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(Unknown Source)
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.callObservers(Unknown Source)
at javafx.scene.control.MultipleSelectionModelBase.clearAndSelect(Unknown Source)
at javafx.scene.control.ListView$ListViewBitSetSelectionModel.clearAndSelect(Unknown Source)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.simpleSelect(Unknown Source)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.doSelect(Unknown Source)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$172/2037973250.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/2117255219.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
What am I doing wrong?
In JavaFX, you cannot change the contents of an ObservableList while a change is already in progress. What is happening here is that your listeners (any of the ones you try) are being fired as part of the box.getSelctionModel().getSelectedItems() ObservableList changing. So basically, you cannot change the selection while a selection change is being processed.
Your solution is a bit unwieldy anyway. If you had another listener on the selected item (or combo box value), even if your method worked it would temporarily see the combo box with an "illegal" selection. E.g in the example above, if the user tries to select "1", another listener would see the selection change to the disallowed value "1", then back to "0". Dealing with values that are not supposed to be allowed in this listener would likely make your program logic pretty complex.
A better approach, imho, is to prevent the user from selecting the disallowed values. You can do this with a cell factory that sets the disable property of the cell:
box.setCellFactory(lv -> new ListCell<Integer>() {
#Override
public void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(item.toString());
setDisable(item.intValue() != 0);
}
}
});
Including the following in an external style sheet will give the user the usual visual hint that the items are not selectable:
.combo-box-popup .list-cell:disabled {
-fx-opacity: 0.4 ;
}
I know the thread is quite old but I had a similar problem and I worked it out in a different way. I tried to change ComboBox' selected item in its onAction method when the item wasn't available at that moment (for example because of the given condition). As #James_D said in his answer, the problem is setting the object that is being currently modified.
Just add your code inside the Platform.runLater() method:
Platform.runLater(() -> box.getSelectionModel().select(0));
In my case it worked, hope it will work in the others too.