how can i catch the selected value of a fxml combobox and implement it into a javafx class?
i gave the combobox the fx:id "sample" and created a button with onAction="#test" and tried .getValue and .getPromptText.
#FXML private ComboBox<String> Sample;
#FXML protected void test( ActionEvent event ) {
String output = (String) Sample.getValue();
System.out.println(output);
String output = (String) Sample.getPromptText();
System.out.println(output);
}
If i try to run it i get an error:
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1440)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Node.fireEvent(Node.java:6863)
at javafx.scene.control.Button.fire(Button.java:179)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3324)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3164)
at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3119)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1559)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2261)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:228)
at com.sun.glass.ui.View.handleMouseEvent(View.java:528)
at com.sun.glass.ui.View.notifyMouse(View.java:922)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435)
... 45 more
Caused by: java.lang.NullPointerException
at TW_JAVAFX_Undecorator.ButtonController.pruefen(ButtonController.java:60)
... 50 more
Thanks in advance
Zombie
Try this:
String output = Sample.getSelectionModel().getSelectedItem();
System.out.println(output);
I think the code you have in your question should work as long as the case of the combobox identifier in the code matches that of your fxml fx:id.
I modified this JavaFX fxml combo box selection demonstration app to add a button with an onAction method to retrieve a value from the combo box using the comboBox getValue() method and it worked fine for me.
Check the case of things, I notice that you say the fx:id is sample, yet in your code you use Sample - and the cases must match otherwise the fxml loader won't inject the node into your controller correctly.
Hard to say if the NullPointerException in your code is related to your combo box value retrieval issue as you don't say what the code at TW_JAVAFX_Undecorator.ButtonController.pruefen(ButtonController.java:60) is or provide full executable code to replicate the issue.
To get the ComboBox selected value, you can use Sample.getSelectionModel method.
Example:
myComboBox.getSelectionModel().selectedItemProperty()
.addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
System.out.println("Value is: "+newValue);
}
});
I was trying to find an answer for this error (which has just happened to me in same conditions) and found this post.
If you actually declared your ComboBox identifier correctly as jewelsea said (If not anyway I think other error would have appeared).
The fact is everything was well declared (no syntax error or compiling error).
The error is in runtime, the event #FXML protected void test(ActionEvent event) is been executing when you fill/add data to your ComboBox.
But value property is not changing since no user input has been detected (I'm assuming you're adding data to your ComboBox somewhere else when you initialize the Scene).
So getValue() is returning null.
In this case the line which broken the code is:
System.out.println(output);
Because output is null.
Try to put a breakpoint in the beginning of test(ActionEvent event) method.
I expect this help also others.
Related
I'm having a bit of a problem with a ListView that is bound to a class that is based on ICollection and where i store my data in a LinkedList.
public class CircularList<T> : ICollection<T>
{
private readonly LinkedList<T> list;
public IEnumerator<T> GetEnumerator()
{
return this.list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
// more code..
}
When I jump to the screen where this is shown, I get the message: A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
Additional information: Collection was modified after the enumerator was instantiated.
However, if I press continue, the list is shown without a problem. The last entry I added is in there. I know it is allready in there before going to that screen, because i also bind to a field in the bottom of my app where i show the last added entry from that Linkedlist. Also, when i go to that screen a second time without adding new entry's into the list no warnings pop up.
Could it be that I have to refresh the IEnumerator before jumping to that screen (or when adding an item to the list), and if so, how? Or could it be something completely else?
I already checked that there are no additions or deletions from the list when the list is being shown on screen.
Need help finding a TableLayoutPanel added at run time to a tab control of a winform. Please find example code below. Any help would be appreciated.
private void GenerateControls()
{
TableLayoutPanel tp = new TableLayoutPanel();
tp.Name = "tpName";
tab1.Controls.Add(tp);
}
private void findTablePanelControl()
{
TableLayoutPanel tp = (TableLayoutPanel)this.Controls.Find("tpName", true)[0];
string name = tp.Name;
}
I receive the follow error message: Index was outside the bounds of the array.
I also tried the following code, but get this error (Object reference not set to an instance of an object) on the "string name =" line:
TableLayoutPanel tpParseSchema = (TableLayoutPanel)this.Controls.Find("tpParseSchema", true).FirstOrDefault();
I found the problem. The provided example code actually will work. The problem with my real code was that I mistakenly keyed in the wrong name value for the TableLayoutPanel. I ended up figuring this out by recursively stepping through all of the child controls of the tab control. Here is example code of how I did that.
foreach (Control ctrl in tab1.Controls)
{
string ctrlname = ctrl.Name;
}
I have a button made from a data controls 'CreateInsert' operation.
I have set a boolean in my code (initialized to false) and when the createInsert button is clicked, I want to check this boolean before executing it's operation.
However, in this button's ActionListener, is nothing related to the CreateInsert operation I need to stop if my boolean check returns true..
Now my question is, where is the real Action handling for the CreateInsert button/how can I control it (stop it from executing) in my code?
Thanks in advance!
create a managed bean to the create insert button(I hope u can do that).
now open the managed bean java class , it automatically contains create insert method somewhat like this :::
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("CreateInsert1");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
}
return null;
A WinForms form that includes a UserControl throws an exception when I attempt to display it in design mode, but runs properly when the program is ran or debugged.
The designer says:
The variable 'fpInfoA' is either undeclared or was never assigned.
ResearchTool fMain.Designer.cs Line:282 Column:1
Call Stack
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
However, it looks like the variable is assigned as I would expect in InitializeComponent
private void InitializeComponent()
{
// ... (Order of statements is same as in actual code) ...
this.tpFpA = new System.Windows.Forms.TabPage();
this.fpInfoA = new ResearchTool.FPInfo();
// ...
this.tpFpA.Controls.Add(this.fpInfoA); // THIS LINE BLOWS UP IN DESIGN MODE
}
Thoughts on how to track down this issue? For example, is there a way to debug initialization of the designer?
One workaround in case you can't fix the issue, would be to surround the offending bits of code with checks for DesignMode.
As in:
private void InitializeComponent()
{
...
if(!DesignMode)
{
this.fpInfoA = new ResearchTool.FPInfo();
}
...
}
This can also speed it up a little bit if it's doing things that aren't needed in design mode and that are quite slow, like connecting to databases or similar.
As Hans Olsson said, this potentially could be resolved by checking for design-mode and disabling offending logic.
This error will also trigger if there is any issue with the constructor of your UserControl. If there is an exception caused when the designer instantiates your UserControl, the designer will fail. In my case, the failure resulted in the same "[...] is either undeclared or was never assigned" error.
For example, see the following user control:
public class MyUserControl : UserControl {
public MyUserControl()
{
InitializeComponent();
throw new Exception(); //Causes a designer error.
}
}
Now, when observing the designer for a form that contains this MyUserControl, we will see something similar to the following:
I cannot say if the designer is like this for previous versions of Visual Studio; but as for Visual Studio 2017, you can clearly see what happened.
The designer failed because a System.Exception was thrown. As a result, the variable [REDACTED] was thought to be undeclared or never assigned when in fact the auto-generated designer code was correct. The issue was with the MyUserControl's constructor.
Now, if you need to put logic that depends on external services/resources inside the control's constructor, you need to indicate that it should only occur during runtime. Alternatively, you can provide mock-up resources for design-time.
To do this, you can use the LicenseManager and check its current UsageMode.
The modified code below only throws the exception in runtime now, and the designer doesn't have the error anymore.
public class MyUserControl : UserControl {
public MyUserControl()
{
InitializeComponent();
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
throw new Exception(); //No longer fails in design-time.
}
}
}
You will find the information on how to trace design time code execution at:
What information do you need to fix a problem, which occurs with your products at design time?
Why would a dependency-property implementation crash my application when I provide a default value?
This segment of code is in the class declaration for my UserControl object. Everything works fine - it compiles and runs perfectly.
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
However, when I add the default value to the dependency property:
The code compiles, but crashes with a fatal exception when it tries to instantiate the UserControl.
For reference, my code now looks like this - with the PropertyMetaData line added:
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl),
new System.Windows.PropertyMetadata(new System.Windows.Shapes.Rectangle()));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
Removing the PropertyMetadata from the call to Register() causes the program to function perfectly, without any crashes or any other problems. But I need the default value for later code. How can I get it to accept the default value without crashing?
When it crashes, the following exceptions are shown in the output window:
A first chance exception of type 'System.ArgumentException' occurred in WindowsBase.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
I need to get this working ASAP, so any advice would be awesome!
Short answer:
Dependency property default values need to be thread safe (e.g. inherit from System.Windows.Freezable) but System.Windows.Forms.Rectangle isn't.
Long answer:
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/2cb12481-ef86-40b7-8333-443598d89933/
Hint:
If you are using Visual Studio it really helps to let the IDE break on every exception being thrown. Just go to "Debug" -> "Exceptions" and check "Common Language Runtime Exceptions" "Thrown".
Then you'll be prompted and get the exception message which in your case looks like this: "Additional information: Default value for the 'Rect' property cannot be bound to a specific thread."