Trying to control the display of a message based on the value in a TextField. I have a fade away timed message display based on certain value input in the TextField box. Like to have a mouse hover over to display the same message while the input value is still invalid. Looks like the code I have below would still show the message even after the input value has beed changed to be valid.
...
errorLimit.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
if (newValue.trim().length() > 0) {
int enteredValue = Integer.parseInt(newValue);
if (enteredValue <1 || enteredValue >25000) {
errorLimit.setStyle("-fx-text-fill: red");
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
if (errorLimit.getStyle().equals("-fx-text-fill: red")) {
errorLimit.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
}
});
}
} else {
errorLimit.setStyle("-fx-text-fill: black");
}
}
}
});
...
Any idea how I can do this? Thanks!
Just put the if(...) clause inside the handle(...) method...
errorLimit.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
if (newValue.trim().length() > 0) {
int enteredValue = Integer.parseInt(newValue);
if (enteredValue <1 || enteredValue >25000) {
errorLimit.setStyle("-fx-text-fill: red");
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
} else {
errorLimit.setStyle("-fx-text-fill: black");
}
}
}
});
errorLimit.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
if (errorLimit.getStyle().equals("-fx-text-fill: red")) {
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
}
}
});
I would strongly suggest creating a BooleanProperty to indicate if the field is valid or not, instead of checking the value of the style; but that's a different issue I guess.
Related
I am trying to range beacons and I am doing exactly what it is written here:
http://altbeacon.github.io/android-beacon-library/samples.html
didRangeBeaconsInRegion method is firing but always with empty collection.
I have installed "locate" by altbeacon and it located 3 beacons.
this is my code: am I missing something?
public class BeaconSingletone implements BeaconConsumer {
private static BeaconSingletone instance;
private final org.altbeacon.beacon.BeaconManager beaconManager2;
private ArrayList<BeaconThin> listNearBeacons = new ArrayList<>();
BeaconRegion region = new BeaconRegion("ranged region",
UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), null, null);
private List<EventInterface> listeners = new ArrayList<EventInterface>();
private BeaconSingletone()
{
beaconManager2 = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(ar_activity.get());
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
beaconManager2.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager2.bind(this);
public static BeaconSingletone getInstance() {
if(instance == null) {
instance = new BeaconSingletone();
}
return instance;
}
private void showNotification(Region region, final List<Beacon> list) {
listNearBeacons.clear();
listNearBeacons.add(new BeaconThin(3514,7580,-1));
for (Iterator<EventInterface> i = listeners.iterator(); i.hasNext(); ) {
EventInterface item = i.next();
//item.NewBeaconFound(list.get(0).getMajor(),list.get(0).getMinor(),Utils.computeAccuracy(list.get(0)));
item.NewBeaconsFound(listNearBeacons);
}
return;
}
#Override
public void onBeaconServiceConnect() {
beaconManager2.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<org.altbeacon.beacon.Beacon> beacons, org.altbeacon.beacon.Region region) {
if (beacons.size() > 0) {
Log.i("BeaconManager", "The first beacon I see is about "+beacons.iterator().next().getDistance()+" meters away.");
}
}
});
try {
beaconManager2.startRangingBeaconsInRegion(new org.altbeacon.beacon.Region("mybeacons", null, null, null));
} catch (RemoteException e) { }{
}
}
#Override
public Context getApplicationContext() {
return ar_activity.get();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
ar_activity.get().unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return ar_activity.get().bindService(intent, serviceConnection, i);
}
}
You need to add a beacon layout for the beacon type you are using (iBeacon?). Replace this line:
beaconManager2.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
With the proper layout from here:
https://beaconlayout.wordpress.com
I've installed the PocketSphinx demo and it works fine under Ubuntu and Eclipse, but despite trying I can't work out how I would add recognition of multiple words.
All I want is for the code to recognize single words, which I can then switch() within the code, e.g. "up", "down", "left", "right". I don't want to recognize sentences, just single words.
Any help on this would be grateful. I have spotted other users' having similar problems but nobody knows the answer so far.
One thing which is baffling me is why do we need to use the "wakeup" constant at all?
private static final String KWS_SEARCH = "wakeup";
private static final String KEYPHRASE = "oh mighty computer";
.
.
.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
What has wakeup got to do with anything?
I have made some progress (?) : Using addGrammarSearch I am able to use a .gram file to list my words, e.g. up,down,left,right,forwards,backwards, which seems to work well if all I say are those particular words. However, any other words will cause the system to match what is said to the "nearest" word from those stated. Ideally I don't want recognition to occur if words spoken are not in the .gram file...
Thanks to Nikolay's tip (see his answer above), I have developed the following code which works fine, and does not recognize words unless they're on the list. You can copy and paste this directly over the main class in the PocketSphinxDemo code:
public class PocketSphinxActivity extends Activity implements RecognitionListener
{
private static final String DIGITS_SEARCH = "digits";
private SpeechRecognizer recognizer;
#Override
public void onCreate(Bundle state)
{
super.onCreate(state);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text)).setText("Preparing the recognizer");
try
{
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
}
catch (IOException e)
{
// oops
}
((TextView) findViewById(R.id.caption_text)).setText("Say up, down, left, right, forwards, backwards");
reset();
}
#Override
public void onPartialResult(Hypothesis hypothesis)
{
}
#Override
public void onResult(Hypothesis hypothesis)
{
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null)
{
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech()
{
}
#Override
public void onEndOfSpeech()
{
reset();
}
private void setupRecognizer(File assetsDir)
{
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup().setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
recognizer.addKeywordSearch(DIGITS_SEARCH, digitsGrammar);
}
private void reset()
{
recognizer.stop();
recognizer.startListening(DIGITS_SEARCH);
}
}
Your digits.gram file should be something like:
up /1e-1/
down /1e-1/
left /1e-1/
right /1e-1/
forwards /1e-1/
backwards /1e-1/
You should experiment with the thresholds within the double slashes // for performance, where 1e-1 represents 0.1 (I think). I think the maximum is 1.0.
And it's 5.30pm so I can stop working now. Result.
you can use addKeywordSearch which uses to file with keyphrases. One phrase per line with threshold for each phrase in //, for example
up /1.0/
down /1.0/
left /1.0/
right /1.0/
forwards /1e-1/
Threshold must be selected to avoid false alarms.
Working on updating Antinous amendment to the PocketSphinx demo to allow it to run on Android Studio. This is what I have so far,
//Note: change MainActivity to PocketSphinxActivity for demo use...
public class MainActivity extends Activity implements RecognitionListener {
private static final String DIGITS_SEARCH = "digits";
private SpeechRecognizer recognizer;
/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
// Check if user has given permission to record audio
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
return;
}
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(MainActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
reset();
}
}
}.execute();
((TextView) findViewById(R.id.caption_text)).setText("Say one, two, three, four, five, six...");
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null) {
return;
} else if (hypothesis != null) {
if (recognizer != null) {
//recognizer.rapidSphinxPartialResult(hypothesis.getHypstr());
String text = hypothesis.getHypstr();
if (text.equals(DIGITS_SEARCH)) {
recognizer.cancel();
performAction();
recognizer.startListening(DIGITS_SEARCH);
}else{
//Toast.makeText(getApplicationContext(),"Partial result = " +text,Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), "Hypothesis" +text, Toast.LENGTH_SHORT).show();
}else if(hypothesis == null){
makeText(getApplicationContext(), "hypothesis = null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDestroy() {
super.onDestroy();
recognizer.cancel();
recognizer.shutdown();
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
reset();
}
#Override
public void onTimeout() {
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
// .setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
File digitsGrammar = new File(assetsDir, "digits.gram");
recognizer.addKeywordSearch(DIGITS_SEARCH, digitsGrammar);
}
private void reset(){
recognizer.stop();
recognizer.startListening(DIGITS_SEARCH);
}
#Override
public void onError(Exception error) {
((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}
public void performAction() {
// do here whatever you want
makeText(getApplicationContext(), "performAction done... ", Toast.LENGTH_SHORT).show();
}
}
Caveat emptor: this is a work in progress. Check back later. Suggestions would be appreciated.
I have to know how to combine strings and SVGs within a combobox.
For example the SVG should be at the end of a string to show if the String has already been set somewhere.
So an item that already appears should be something like:
"This string already appears somewhere else" + mySVG.
If the string doesnt appear somewhere else the items value is simply the string itself.
Showing the string is no problem, my problem starts at adding the SVG.
My SVG is this:
SVGPath mySVG = new SVGPath();
mySVG.setContent("M0,4.2l1.4,-0.3L3,5.7A13,13 0 0,1 7.4,0H8.5A15,15 0 0,0 4,7.2L2.5,7.5Z");
I hope you understand what I want to do.
You can do it by setting a cell factory to the ComboBox:
public class JavaFxTest2 extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll("apple", "banana", "orange");
comboBox.setCellFactory(l -> new ListCell<String>() {
private SVGPath mySVG;
{
setContentDisplay(ContentDisplay.RIGHT);
mySVG = new SVGPath();
mySVG.setContent("M0,4.2l1.4,-0.3L3,5.7A13,13 0 0,1 7.4,0H8.5A15,15 0 0,0 4,7.2L2.5,7.5Z");
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
if ("banana".equals(item)) {
setGraphic(mySVG);
} else {
setGraphic(null);
}
setText(item);
} else {
setGraphic(null);
setText(null);
}
}
});
primaryStage.setScene(new Scene(comboBox));
primaryStage.show();
}
public static final void main(String[] args) {
launch(args);
}
}
I am creating some forms and I need to create masks and validation for some fields.
Is it implemented in anyway in JavaFX?
My example of the mask.
Using:
<MaskField mask="+7(DDD)DDD-DDDD"/>
<MaskField mask="AA DDD AAA" placeholder="__ ### ___"/>
etc
Restricting input from Richard's fxexperience post:
TextField field = new TextField() {
#Override public void replaceText(int start, int end, String text) {
// If the replaced text would end up being invalid, then simply
// ignore this call!
if (!text.matches("[a-z]")) {
super.replaceText(start, end, text);
}
}
#Override public void replaceSelection(String text) {
if (!text.matches("[a-z]")) {
super.replaceSelection(text);
}
}
};
If you want to create your use a mask and create your own control, take a look at Richard's MoneyField, which also includes a sample project and source. Along the same lines there are controls to restict input to Integers, Doubles or formatted web colors (e.g. #rrggbb) in the fxexperience repository. All of these follow a common theme where they subclass Control, provide some properties to be get and set which define the public interface and then also define a private backing skin which handles rendering of the UI based on the values set through the public interface.
I had the same needs. I created this field, called it SpecialTextField, and pushed into GitHub. Example also there. Hope this help.
NOTE: this only works correctly with JRE 1.8.0_25 or lower. With JRE 1.8.0_48 or 0_51, the caret position is always set to 0 after each character input.
No, this is not implemented in standard JavaFX. You need to use some library or do it yourself.
This is my implementation of static mask for text fields. It works for date, phone and other types of static masks:
/**
* Adds a static mask to the specified text field.
* #param tf the text field.
* #param mask the mask to apply.
* Example of usage: addMask(txtDate, " / / ");
*/
public static void addMask(final TextField tf, final String mask) {
tf.setText(mask);
addTextLimiter(tf, mask.length());
tf.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
String value = stripMask(tf.getText(), mask);
tf.setText(merge(value, mask));
}
});
tf.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(final KeyEvent e) {
int caretPosition = tf.getCaretPosition();
if (caretPosition < mask.length()-1 && mask.charAt(caretPosition) != ' ' && e.getCode() != KeyCode.BACK_SPACE && e.getCode() != KeyCode.LEFT) {
tf.positionCaret(caretPosition + 1);
}
}
});
}
static String merge(final String value, final String mask) {
final StringBuilder sb = new StringBuilder(mask);
int k = 0;
for (int i = 0; i < mask.length(); i++) {
if (mask.charAt(i) == ' ' && k < value.length()) {
sb.setCharAt(i, value.charAt(k));
k++;
}
}
return sb.toString();
}
static String stripMask(String text, final String mask) {
final Set<String> maskChars = new HashSet<>();
for (int i = 0; i < mask.length(); i++) {
char c = mask.charAt(i);
if (c != ' ') {
maskChars.add(String.valueOf(c));
}
}
for (String c : maskChars) {
text = text.replace(c, "");
}
return text;
}
public static void addTextLimiter(final TextField tf, final int maxLength) {
tf.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
if (tf.getText().length() > maxLength) {
String s = tf.getText().substring(0, maxLength);
tf.setText(s);
}
}
});
}
See also:
JavaFX 2.2 TextField maxlength
Supported by current javafx-2 platform by default - No, but go through this link , it has many insights and sample code for Form validation in javaFX
public class NumberTextField extends TextField {
private int maxLenght;
public NumberTextField(int maxLenght) {
super();
this.maxLenght = maxLenght;
}
#Override
public void replaceText(int start, int end, String text) {
if (validate(text)) {
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text) {
if (validate(text)) {
super.replaceSelection(text);
}
}
private boolean validate(String text) {
if (this.getText() != null) {
}
boolean status = ("".equals(text) || text.matches("[0-9]"));
if (this.getText() == null) {
return status;
} else {
return (status && this.getText().length() < maxLenght);
}
}
}
In some cases I would validate the text property:
myTextField
.textProperty()
.addListener(
(obs, oldVal, newVal) ->
{
if(!newVal.matches("\\d+"))
textField.setText(oldV);
});
Unlucky: textField.setText(oldV); will enter the same function again, testing unnecessarily if oldVal matches.
If the TextField becomes a value that doesn't matches before this listener is added to the TextField, enter a not matching new value will cause a loop!!!
To avoid this, it will be safer to write:
String acceptableValue = "0";
myTextField
.textProperty()
.addListener(
(obs, oldVal, newVal) ->
{
if(!newVal.matches("\\d+"))
textField.setText(oldVal.matches("\\d+") ? oldV : acceptableValue);
});
I wrote a class that extends the TextField and apply the mask.
package com.model;
import java.text.NumberFormat;
import java.util.Locale;
/**
* ATENTION
* DO NOT FORGUET TO IMPORT IN FXML
* <?import com.view.TextFieldMoney?>
*
* */
import javafx.scene.control.TextField;
public class TextFieldMoney extends TextField {
private int maxlength;
private String valor = "";
public TextFieldMoney() {
this.maxlength = 11;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
#Override
public void replaceText(int start, int end, String text) {
// Delete or backspace user input.
if (getText() == null || getText().equalsIgnoreCase("")) {
valor = "";
}
if (text.equals("")) {
super.replaceText(start, end, text);
} else{
text = text.replaceAll("[^0-9]", "");
valor += text;
super.replaceText(start, end, text);
if (!valor.equalsIgnoreCase(""))
setText(formata(valor));
}
}
#Override
public void replaceSelection(String text) {
// Delete or backspace user input.
if (text.equals("")) {
super.replaceSelection(text);
} else if (getText().length() < maxlength) {
// Add characters, but don't exceed maxlength.
// text = MascaraFinanceira.show(text);
if (text.length() > maxlength - getText().length()) {
// text = MascaraFinanceira.show(text);
text = text.substring(0, maxlength - getText().length());
}
super.replaceSelection(text);
}
}
/*
*Return the number without money mask
**/
public String getCleanValue(){
String cleanString = getText().replaceAll("[^0-9]", "");
Double cleanNumber = new Double(cleanString);
return String.valueOf(cleanNumber/100);
}
private String formata(Double valor) {
Locale locale = new Locale("pt", "BR");
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
return nf.format(valor);
}
public String formata(String valor) {
double v = new Double(valor);
return formata(v/100);
}
}
And in the FXML where is
<TextField fx:id="valorTextField" GridPane.columnIndex="2" GridPane.rowIndex="2" />
put
<TextFieldMoney fx:id="valorTextField" GridPane.columnIndex="2" GridPane.rowIndex="2" />
private ObservableCollection<Scores> _scores;
public ObservableCollection<Scores> Scores
{
get
{
return _scores;
}
set
{
_scores = value;
RaisePropertyChanged("Scores");
Recalculate();
}
}
public int RowNumber { get; set; }
public string StudentId { get; set; }
public string StudentName { get; set; }
private double _studentAverage;
public double StudentAverage
{
get
{
return _studentAverage;
}
set
{
_studentAverage = value;
RaisePropertyChanged("StudentAverage");
}
}
private string _gradeYear;
public string GradeYear
{
get
{
return _gradeYear;
}
set
{
_gradeYear = value;
RaisePropertyChanged("StudentGrade");
}
}
private void Recalculate()
{
StudentAverage = (from score in Scores select score.Score).Sum();
}
Hi, how can i get the notification when a score changes inside ObservableCollection so that i can recalculate.
Actually i am binding the whole Entity to a Gridview. Whenever a Score changes in the column i want my Total column to automatically calculate the Total and display.
Note 1
In a nutshell - you should subscribe to INotifyPropertyChanged.PropertyChanged event of all your "scores", and in the event handler you should recalc your TotalScore. But the problem is that you should also monitor changes in your Scores collection (if you need it, of course).
As a very useful helper you can try to use my Extended ObservableCollection. This class already contains ItemPropertyChangedEvent, so you should just write something like:
private ObservableCollectionEx<Scores> _scores;
public ObservableCollectionEx<Scores> Scores
{
get
{
return _scores;
}
set
{
if (_scores == value) return;
if (_scores != null)
_scores.ItemPropertyChanged -= OnItemPropertyChanged;
_scores = value;
if (_scores != null)
_scores.ItemPropertyChanged += OnItemPropertyChanged;
RaisePropertyChanged("Scores");
Recalculate();
}
}
void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Score")
Recalculate();
}
Note 2
Take a look also at this article. It will teach how to avoid "magic strings" in notifications (like RaisePropertyChanged("Scores") and e.PropertyName == "Score").
Note 3
Instead of
StudentAverage = (from score in Scores select score.Score).Sum();
it's better to use
StudentAverage = Scores.Sum(score => score.Score);
But this is not necessarily, this is just my style of coding :)
BTW, why it's mixed - "average" and "sum"? Is this mistake?