I'm hoping that Java is not as in-elegant as my efforts with it lead me to believe.
I am working with JRadioButtons, and want to programmatically determine an "ID" associated with them. For this, I am trying to read "name" as listed in its NetBeans properties.
In the ide, when I right-click the component, I am given the option of "Change Variable Name..." I use this to set values such as rb1, rb2, etc.
But in the properties panel, there is also the "name" entry which can be set to a different value. I use this to set "id"-s such as 1, 2, etc.
Working with radio buttons, I know that I can have a series of if-statements that, in a handler, ask
Object src = evt.getSource();
int val=-1;
if (src == rb1) { val=1; }
else if (src == rb2) { val=2; }
else if (src == rb3) { val=3; }
else { val=4; }
But, besides requiring me to hard code the id value with the control name myself, where I'm prone to make a transcription error, I want to believe that there is simpler single-statement means to achieve this, something like:
String name = rbGroup.getSelection().getName();
.getText();
.getLabel();
But, I seem to be stuck with the much less elegant and verbose use of multiple if-else statements.
How can I query the control to give me the properties listed in the NetBeans IDE in the simplest means possible?
One way is to use the Action Command of the button:
rb1.setActionCommand("1");
Then in the event handler you can juse use:
String command = evt.getActionCommand();
The action command defaults to the text of the button if you don't set it explicitly.
Related
I am using eclipse e4 application. I am using the eventBroker to pass values from one part to another part. If many parts(Kind of tabs) are open , how to pass values to the part(tab) that is currently selected. ? I am using the #UIEventTopic to get the values for the part. But the problem is ,the values are replicated to all the tabs. In other words , I am trying to show different JFreechart in different tabs, but the charts are replicated to the previous tabs.
Can anyone please suggest me some ideas?
Thanks in advance
The event broker always broadcasts to anything that is dealing with the event, you can't use it to send to one specific thing.
If you are in a Handler you can get the current part in the #Execute method and set a value directly in your class - something like:
#Execute
public void execute(#Named(IServiceConstants.ACTIVE_PART) MPart activePart)
{
Object part = activePart.getObject();
if (part instanceof MyClass)
{
((MyClass)part).setValue(xxxx);
}
}
Update:
If you are in another part use the EPartService to get the active part:
#Inject
EPartService partService;
...
MPart activePart = partService.getActivePart();
Object part = activePart.getObject();
if (part instanceof MyClass)
{
((MyClass)part).setValue(xxxx);
}
You can also use EPartService.findPart("part id") to find a part with a given id.
I need a JFileChooser which acts like notepad.exe or mspaint.exe in save mode. As you may know when you type wildcard (* or ?) characters in the File name field the file view will show only those files which are matching for the users input. This is OK, but my problem is with the Files of type combobox:
In JFileChooser: the Files of type combo box is updated as well when the user enters a wildcard in the File name field.
See the screenshot here!
But if you try this with notepad.exe you will realize that the File name field remains as it was before, so the search pattern is not updated.
See the notepad's screenshot here!
So my question is: Does anybody know a solution how to achieve that the Files of type combo box should NOT be updated by the entered filter?
I need a cross-platform solution, so it should work both on XP and Linux.
Thanks in advance!
Sorry for the links, but I am not allowed to attach it directly!
The glob pattern recognition feature is implemented in the FileChooserUI delegate for each Look & Feel. For example, MetalFileChooserUI contains a nested ApproveSelectionAction, inherited from BasicFileChooserUI, that invokes setFileFilter(). This adds the new pattern, via a PropertyChangeEvent, to the listening MetalFileChooserUI.FilterComboBoxModel. You may be able to intercept the added filter somewhere along the chain.
You may also be able to leverage the file pattern matching capability introduced in Java 7 and discussed here.
Finally I've found a solution:
Using a custom file chooser UI derived from BasicFileChooserUI will solve my issue in the following way: I've overriden the getApproveSelectionAction() method with my custom action:
protected class CustomApproveSelectionAction extends BasicFileChooserUI.ApproveSelectionAction {
#Override
public void actionPerformed(ActionEvent e) {
String filename = getFileName();
// using a custom pattern to accept valid charachters only:
Matcher matcher = pattern.matcher(filename);
if (matcher.matches()) {
// this is the good case, just let the super implementation do what have to do.
super.actionPerformed(e);
} else {
// this is the bad case, we must warn the user and don't let the super implementation take effect.
// display an error message similar like notepad does it.
}
}
}
If the filename is ok, then I allow what super implementation does, otherwise I will display a message.
I have RCP application, and i have a command in it, that launches a wizard of some entity (edit wizard, that shows all fields of entity, and user can change it and finish wizard to save this entity). I'm using JFace data binding to bind entity's field to swt Texts and Combos.
That command have handler (that contains wizard call), and this handler is bind to some button and all works fine.
Then i need to bind this command to some Key combination (Ctrl+E for example). I'm using org.eclipse.ui.bindings extention for it:
<key
commandId="com.project.command"
contextId="com.project.view.context"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
sequence="M1+E">
</key>
"com.project.view.context" is made by me to bind to same key combination in 2 different views and it's looks ok (and activates different commands in these 2 views).
But when i open my wizard through this key combination there is a problem:
SWT Text fields dont binds to Integer fields of entity. With String fields it's all ok, and they're binding fine. But Integer fields dont (There are just empty space in it).
What i've tried:
I debugged my wizard and wizard page, and all time entity state is
fine (their Integer fields is correct and not 0 or null)
Tried to write Integer to String Convertors for JFace binding. Didnt help.
I tried disable JFace binding for this fields, and seting Text field
value manual:
swtTextField.setText(entity.getIntegerField().toString());
But this also didnt work! Looks like it's not JFace binding problem,
but SWT text problem? Debuggin this situation :
entity.getIntegerField().toString() = "1234" before and after
"setText" swtTextField.getText = "" before and after "setText"
(And when i run this debug not from Key combination-command call,
all looks good and swtTextField.getText = "1234" after "setText")
Tried to change context of binding extention to default
("org.eclipse.ui.contexts.window") that didnt helped too.
So, summing up, all works fine, when i calling my command through button (or context menu). But there is a problem with Integer->Text fields (String fields works fine) when i calling my command through key combination binding extention.
Have any ideas what's wrong with it?
Added: I found out, that the problem is in key combination. When the key combination contains not-english key symbol (Ctrl+non-english-key my language key symbol, cause our application uses not-english key combinations) then the problem appears: SWT Text doesnt accept Integer values. When the key combinations is english (Ctrl+english-key) - all is ok.
All other commands (without SWT Text fields) works fine too, and they are binded to Ctrl+non-english-key combinations too...
That is very strange and I still dont understand, why that hanneps...
I have bumped into this problem several months ago. The problem was with JFace Data Bindings. What helped:
use org.eclipse.core.databinding.observable.value.IObservableValue for observing your Text. So you can write code like this: IObservableValue yourTextObserveTextObserveWidget = SWTObservables.observeText(yourText, SWT.Modify);
Use org.eclipse.core.databinding.beans.BeansObservables to observe the value of your entity so you can write code like this: BeansObservables.observeValue(yourModel, "yourInt");
Use org.eclipse.core.databinding.DataBindingContext and bind your IObservableValue like this: bindingContext.bindValue(yourTextObserveTextObserveWidget, yourModelTemplateObserveValue, null, null)
So the final code for binding your model to a Text will be like this:
DataBindingContext bindingContext = new DataBindingContext();
IObservableValue yourTextObserveTextObserveWidget = SWTObservables.observeText(yourText, SWT.Modify);
IObservableValue yourModelTemplateObserveValue = BeansObservables.observeValue(yourModel, "yourInt");
bindingContext.bindValue(yourTextObserveWidget, yourModelTemplateObserveValue, null, null);
Please check the documentation of the data binding if you have any further questions. This is working in my program with String, boolean and Integer types. I haven't tested anythig else though.
In my Wicket application I used one radio button with "yes" and "no" options. If I select "No", I should display one dropdown choice. I wrote code using AjaxFormChoiceComponentUpdatingBehavior. How do I unittest this using WicketTester?
Solution for Wicket 1.5.x:
AbstractAjaxBehavior behavior = (AbstractAjaxBehavior)WicketTesterHelper.
findBehavior(getTester().getComponentFromLastRenderedPage("path:to:component"),
AjaxFormChoiceComponentUpdatingBehavior.class);
getTester().executeBehavior(behavior);
First select the radio button that you want.
form.select("path to radio button", 0/1)
Then execute ajax behaviour:
tester.executeBehavior((AbstractAjaxBehavior)tester.getComponentFromLastRenderedPage("path to radio buttons").getBehaviors().get(0));
Here is my piece of code which works perfectly for me with select box but should fiat as well for radio button if you change Behaviour class. Needed steps are:
Insert new value into form (use FormTester)
Find behaviour
Execute behaviour on change
Here is an example of code:
//simulate insert new value
FormTester formTester = tester.newFormTester(PANEL_ID + FORM);
formTester.setValue("selectBox", "newValue");
//Find onchange behaviour
AjaxFormComponentUpdatingBehavior behavior =
(AjaxFormComponentUpdatingBehavior) WicketTesterHelper.findBehavior(
tester.getComponentFromLastRenderedPage(PANEL_ID + FORM + ":" + "selectBox"),
ajaxFormComponentUpdatingBehavior.class);
//execute onchange
tester.executeBehavior(behavior);
I missed the par how to update form value in previous answers.
If the radio button is on a form I think you should use the FormTester class:
http://wicket.apache.org/apidocs/1.4/org/apache/wicket/util/tester/FormTester.html
For an example of an Ajax form submit test you can take a look at:
http://www.java2s.com/Open-Source/Java-Document/J2EE/wicket-1.4/org/apache/wicket/ajax/form/AjaxFormSubmitTest.java.htm
Try something like this:
tester.executeAjaxEvent("form:myRadioButtonId", "onchange");
This turns out to be somewhat painful, at least in Wicket 1.4 (I haven't tried with 1.5).
Via a web search, I found hints in Mischa Dasberg's blog. Basically, you can't use the BaseWicketTester.executeAjaxEvent((String componentPath, String event) method because the behavior you're using isn't an AjaxEventBehavior and you can't use the BaseWicketTester.executeBehavior(final AbstractAjaxBehavior behavior) because it wipes out the request parameters.
Mischa's solution was to implement his own executeBehavior method in a parent test case, which worked for his situation, but not for my need, as it assumed the request parameter id was the same as the full component path.
I've done something similar by implementing my own executeAjaxBehavior in an extension of WicketTester, but assuming (as is true in my case) that the request parameter is the last ":" separated section of the component path:
public void executeAjaxBehavior(String path, String value) {
AbstractAjaxBehavior behavior = (AbstractAjaxBehavior) getComponentFromLastRenderedPage(path).getBehaviors().get(0);
CharSequence url = behavior.getCallbackUrl(false);
WebRequestCycle cycle = setupRequestAndResponse(true);
getServletRequest().setRequestToRedirectString(url.toString());
String[] ids = path.split(":");
String id = ids[ids.length-1];
getServletRequest().setParameter(id, value);
processRequestCycle(cycle);
}
Both his solution and mine (based on his) also assume that the behavior is the first (or only) one on the component.
This is a bit clunky, but something like this may work for you.
It might be better if the ids and behavior were gotten separately and passed as parameters, and of course you might do well to find the first behavior that actually was an AjaxFormChoiceComponentUpdatingBehavior instead of blithely assuming it was the first behavior, but this is a start.
This is also similar code to what's inside the BaseWicketTester class for the other behavior testing methods, which might be worth looking through.
I have a TableViewer with an ICellModifier which seems to work fine. I set an ICellEditorValidator on one of the cell editors, though, and I can't get it to behave the way I would like. Here's my abbreviated code:
cellEditors[1] = new TextCellEditor(table);
cellEditors[1].setValidator(new ICellEditorValidator() {
public String isValid(Object value) {
try {
Integer.parseInt((String) value);
return null;
} catch(NumberFormatException e) {
return "Not a valid integer";
}
}
});
It mostly works fine. However, there are two issues:
The modify method of the cell
modifier receives a null as the new
value if the validator returns an
error. I can code to handle this,
but it doesn't seem right. Null
could be a valid value, for example,
if the user's picking a background
color and they picked transparent.
(This is a general issue, not specific to this example.)
The validator's error message is
never displayed to the user. This
is the big problem. I could also
add an ICellEditorListener and
display a dialog from the
applyEditorValue method if the
last value was invalid. Is this the
"proper" way to do it?
By the way, for reasons beyond my control, I'm limited to the Eclipse 3.0 framework.
you can add a listener to your Editor:
cellEditors[1].addListener(
public void applyEditorValue() {
page.setErrorMessage(null);
}
public void cancelEditor() {
page.setErrorMessage(null);
}
public void editorValueChanged(boolean oldValidState,
boolean newValidState) {
page.setErrorMessage(editor.getErrorMessage());
}
With page being your current FormPage, this will display the errorMessage to the user.
Regarding the second issue, the string the validator's method isValid returns becomes the error message for the CellEditor owning that validator. You can retrieve that message with CellEditor.getErrorMessage.
It appears to me that the easiest way to show the error message is through a ICellEditorListener, as Sven suggests above. Maybe the tricky thing about this listener is that the cell editor is not passed as a parameter to any of its methods, so the assumption is that the listener knows which cell editor is talking to it.
If you want the dialog, the preference page or whatever object to implement the ICellEditorListener interface you have to be sure it knows the cell editor being edited.
However, if it's the cell editor itself which implements the interface it should have a way to properly carry the error message over into the dialog, the preference page or whatever. That's the currentForm page Scott is looking for.
One last thing worth noticing if you're using EditingSupport is that the value passed into the EditingSupport.setValue method is null when ICellEditorValidator.isValue returns an error message. Don't forget to check it out.