Restrict text input inside combobox - combobox

I need to restrict text input inside combobox with positive numbers. I've searched stackoverflow for this and found similar question: Recommended way to restrict input in JavaFX textfield
The only difference is that the mentioned question addresses bare textfield. The answer approved by the javafx designers is to extend the TextField class and override couple of methods: replaceText and replaceSelection. This hack does not work with combobox: TextField instance if stored inside and is avaiable as read-only property named editor.
So what is the recommended way to restrict text input inside javafx combobox?

Since this question question never got a proper answer I'm adding a solution I've implemented that restricts the user to input that matches a regular expression and is shorter than a particular length (this is optional). This is done by adding a ChangeListener to the editor TextField. Any input that doesn't match will not get written into the editor TextField.
This example restricts the user to a maximum of two numeric characters.
ComboBox<Integer> integerComboBox = new ComboBox<Integer>();
integerComboBox.setEditable(true);
integerComboBox.getEditor().textProperty()
.addListener(new ChangeListener<String>() {
// The max length of the input
int maxLength = 2;
// The regular expression controlling the input, in this case we only allow number 0 to 9.
String restriction = "[0-9]";
private boolean ignore;
#Override
public void changed(
ObservableValue<? extends String> observableValue,
String oldValue, String newValue) {
if (ignore || newValue == null) {
return;
}
if (newValue.length() > maxLength) {
ignore = true;
integerComboBox.getEditor().setText(
newValue.substring(0, maxLength));
ignore = false;
}
if (!newValue.matches(restriction + "*")) {
ignore = true;
integerComboBox.getEditor().setText(oldValue);
ignore = false;
}
}
});

You might register a check method on the editor property to check if any input is accpetable.
Here I allow editing, but draw a red frame if values are not in the items list.
ObservableList<String> myChoices = FXCollections.observableArrayList();
void testComboBoxCheck(VBox box) {
myChoices.add("A");
myChoices.add("B");
myChoices.add("C");
ComboBox<String> first = new ComboBox<String>();
first.setItems(myChoices);
first.setEditable(true);
first.editorProperty().getValue().textProperty().addListener((v, o, n) -> {
if (myChoices.contains(n.toUpperCase())) {
first.setBackground(new Background(new BackgroundFill(Color.rgb(30,30,30), new CornerRadii(0), new Insets(0))));
} else {
first.setBackground(new Background(new BackgroundFill(Color.RED, new CornerRadii(0), new Insets(0))));
}
});
box.getChildren().addAll(first);
}

How about decouplign the Text editor from the ComboBox and link their values?
HBox combo = new HBox();
TextField editor = new TextField();
ComboBox<String> first = new ComboBox<String>();
first.setItems(myChoices);
first.setButtonCell(new ComboBoxListCell<String>(){
#Override public void updateItem(String s, boolean empty) {
super.updateItem(s, empty);
setText(null);
}
});
editor.textProperty().bindBidirectional(first.valueProperty());
combo.getChildren().addAll(editor, first);
box.getChildren().addAll(combo);
Now you have full conroll over the TextField allowing to override any methods etc.

Related

Why can not update autocomplete suggestions?

I am using two AutocompleteTextFilters as depended filters. I want the second one filter to change its options depending on the suggestion of the first filter.
I have bind an event listener on the first filter so as when it loose focus it triggers a proccess on the second filter.
The proble is that the second filter never changes its options. I even have setup hardcoded values in case somethig was wrong on my code but no luck.
The code I use is below:
public CreateSubmission(com.codename1.ui.util.Resources resourceObjectInstance, Map<String, ProjectType> projectTypes) {
this.projectTypes = projectTypes;
initGuiBuilderComponents(resourceObjectInstance);
gui_ac_projecttype.clear();
gui_ac_projecttype.setCompletion( this.projectTypes.keySet().toArray( new String[0]) );
gui_ac_projecttype.addFocusListener( new ProjectTypeFocusListener( this ));
gui_ac_steps.setCompletion( new String[]{"t10", "t20"});
}
public void makeSteps (String selection) {
ProjectType projectType = this.projectTypes.get( selection );
if (projectType != null) {
this.selectedProjectType = selection;
int length = projectType.projectSteps.length;
String[] steps = new String[ length ];
for(int i =0; i < length; i ++) {
steps[i] = projectType.projectSteps[i].projectStep;
}
// String[] s = gui_ac_steps.getCompletion();
gui_ac_steps.setCompletion( new String[]{"t1", "t2"} );
gui_ac_steps.repaint();
}
else {
}
}
public class ProjectTypeFocusListener implements FocusListener{
private CreateSubmission parent;
public ProjectTypeFocusListener( CreateSubmission parent ) {
this.parent = parent;
}
#Override
public void focusGained(Component cmp) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void focusLost(Component cmp) {
this.parent.makeSteps (
((AutoCompleteTextField)cmp).getText()
);
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
On the above code the initialization happens on "public CreateSubmission" method.
"gui_ac_projecttype" is the first AutocompletionTextField that triggers the whole proccess through it's FocusListener handler (class ProjectTypeFocusListener )
"gui_ac_steps" is the second AutocompleteTextField filter that must change its values. On the code above I initialize it's suggestions to "t10", "t20". Those two values are shown correctly.
Later from iside the FoculListenerHandler's method "ProjectTypeFocusListener.focusLost" I call method "makeSteps" which sets the suggestion options to "t1", "t2 and then I repaint the component. These two last values are never shown. It remains on the first values "t10", "t20".
The Strange thing is that in debugger when I ask gui_ac_steps.getCompletion(); to see the current options ( the code that is commentd out into makeSteps method) I get the correct values "t1", "t2".
But on the screen it keeps showing "t10", "t20".
any help is aprreciated.
You shouldn't do anything "important" in a focus listener. Especially not with a text field. They are somewhat unreliable because the text field switches to native editing and in effect transfers the focus there. The problem is that some events are delayed due to the back and forth with the native editing so by the time the focus event is received you've moved on to the next field.
Try something like this for this specific use case https://www.codenameone.com/blog/dynamic-autocomplete.html

Chop the text and display three dots in PropertyGrid of winforms

I would like to cut the extra text and display three dots(...) and when user clicks on the cell, everthing has to be displayed. how to calculate the width of the property grid cell and cut the text. Any help will be grateful.
Pictures are attached for explanation
Instead of this
I would like to achieve this
and it should vary according to the cell size
The property grid does not allow that and you cannot customize it to do so using any official way.
However, here is some sample code that seems to work. It uses a TypeConverter to reduce the value from the grid's size.
Use at your own risk as it relies on PropertyGrid's internal methods and may have an impact on performance, since it requires a refresh on the whole grid on each resize.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// note this may have an impact on performance
propertyGrid1.SizeChanged += (sender, e) => propertyGrid1.Refresh();
var t = new Test();
t.MyStringProperty = "The quick brown fox jumps over the lazy dog";
propertyGrid1.SelectedObject = t;
}
}
public class AutoSizeConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value == null)
return null;
// small trick to get PropertyGrid control (view) from context
var view = (Control)context.GetService(typeof(IWindowsFormsEditorService));
// bigger trick (hack) to get value column width & font
int width = (int)view.GetType().GetMethod("GetValueWidth").Invoke(view, null);
var font = (Font)view.GetType().GetMethod("GetBoldFont").Invoke(view, null); // or GetBaseFont
// note: the loop is not super elegant and may probably be improved in terms of performance using some of the other TextRenderer overloads
string s = value.ToString();
string ellipsis = s;
do
{
var size = TextRenderer.MeasureText(ellipsis, font);
if (size.Width < width)
return ellipsis;
s = s.Substring(0, s.Length - 1);
ellipsis = s + "...";
}
while (true);
}
}
public class Test
{
// we use a custom type converter
[TypeConverter(typeof(AutoSizeConverter))]
public string MyStringProperty { get; set; }
}
Here is the result (supports resize):

GMAP.NET adding labels underneath markers

I have just started using gmap.net and I was looking for the functionality of adding labels under the markers. I see there's tooltips but I would like to have a constant label under my marker with a one word description.
I searched for docs or other answers but I cannot find anything which leads me to believe that it is not implemented. If someone can verify this I would appreciate it.
You need to create your own custom marker.
Based on the source of GMapMarker and the derived GMarkerGoogle I came up with this simplified example:
public class GmapMarkerWithLabel : GMapMarker, ISerializable
{
private Font font;
private GMarkerGoogle innerMarker;
public string Caption;
public GmapMarkerWithLabel(PointLatLng p, string caption, GMarkerGoogleType type)
: base(p)
{
font = new Font("Arial", 14);
innerMarker = new GMarkerGoogle(p, type);
Caption = caption;
}
public override void OnRender(Graphics g)
{
if (innerMarker != null)
{
innerMarker.OnRender(g);
}
g.DrawString(Caption, font, Brushes.Black, new PointF(0.0f, innerMarker.Size.Height));
}
public override void Dispose()
{
if(innerMarker != null)
{
innerMarker.Dispose();
innerMarker = null;
}
base.Dispose();
}
#region ISerializable Members
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
protected GmapMarkerWithLabel(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
}
Usage (assuming a GMap instance named gm):
GMapOverlay markerOverlay = new GMapOverlay("markers");
gm.Overlays.Add(markerOverlay);
var labelMarker = new GmapMarkerWithLabel(new PointLatLng(53.3, 9), "caption text", GMarkerGoogleType.blue);
markerOverlay.Markers.Add(labelMarker)
I'll answer here because this is the first question that pops up when looking to display a text marker for the WPF GMAP.NET library. Displaying a text marker with the WPF version of the library is actually much easier than in WinForms, or at least than the accepted answer.
The GMapMarker in WPF has a Shape property of type UIElement, which means you can provide a System.Windows.Controls.TextBlock object to display a text marker :
Markers.Add(new GMapMarker(new PointLatLng(latitude, longitude))
{
Shape = new System.Windows.Controls.TextBlock(new System.Windows.Documents.Run("Label"))
});
Since the marker displays the top left portion of the shape at the given position, you can play with the GMapMarker.Offset property to adjust the text position according to its dimensions. For instance, if you want the text to be horizontally centered on the marker's position :
var textBlock = new TextBlock(new Run("Label"));
textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
textBlock.Arrange(new Rect(textBlock.DesiredSize));
Markers.Add(new GMapMarker(new PointLatLng(request.Latitude, request.Longitude))
{
Offset = new Point(-textBlock.ActualWidth / 2, 0),
Shape = textBlock
});
The solution to get the TextBlock's dimensions was quickly taken from this question, so if you need a more accurate way of getting the block's dimensions to play with the offset I suggest you start from there.

How to highlight the word(s) with bold in text block for specified keyword using the attached property

The objective is to bold the word(s) of text in Textblock with matching input keyword.
For example: Stackoverflow is a very helpful, keep using Stackoverflow to sharpen your skills.
When the keyword is: Stackoverflow it should now display as
Stackoverflow is a very helpful, keep using Stackoverflow to sharpen your skills.
I tried to achieve the same objective using attached property. Below is the snap code of the same
public class HighLightKeyWord : DependencyObject
{
//This word is used to specify the word to highlight
public static readonly DependencyProperty BoldWordProperty = DependencyProperty.RegisterAttached("BoldWord", typeof(string), typeof(HighLightKeyWord),
new PropertyMetadata(string.Empty, OnBindingTextChanged));
public static string GetBoldWord(DependencyObject obj)
{
return (string)obj.GetValue(BoldWordProperty);
}
public static void SetBoldWord(DependencyObject obj, string value)
{
obj.SetValue(BoldWordProperty, value);
}
private static void OnBindingTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var _Key = e.NewValue as string;
var textblk = d as TextBlock;
string SourceText = textblk.Text;
SetBold(_Key, textblk, SourceText);
}
private static void SetBold(string key, TextBlock text, string SourceText)
{
text.Inlines.Clear();
var words = SourceText.Split(' ');
for (int i = 0; i < words.Length; i++)
{
var word = words[i];
var inline = new Run() { Text = word + ' ' };
if (String.Compare(word, key, StringComparison.CurrentCultureIgnoreCase) == 0)
{
inline.FontWeight = FontWeights.Bold;
}
text.Inlines.Add(inline);
}
}
}
// Bind object in Main
StackOverFlow stkovrflw = new StackOverFlow();
stkovrflw.Text = "Stackoverflow is a very helpful,keep using Stackoverflow to sharpen your skills.";
stkovrflw.KeyWord = "Stackoverflow";
this.DataContext = stkovrflw;
In Xaml I binded the value as
<TextBlock Text="{Binding Path=Text}" loc:HighLightKeyWord.BoldWord="{Binding Path=KeyWord}" />
Above code is working fine, however when I directly sets the HighlightText property in the xaml instead through data binding, Text property of the Text block is getting empty in the OnBindingTextChanged method and this method is called only once when dependency property is set .
I used this design based on Spellchecker concept so that other teamates can reuse my attached property in their projects.
Can anyone suggest how to fix the problem?
Whether you want to modify a TextBlock FontWeight attribute or another display property, I've written the following static method and found it very useful. (Note: The method illustrates highlighting text by modifying the Foreground property. The same principle can be used for any other TextBlock display attribute.)
static Brush DefaultHighlight = new SolidColorBrush(Colors.Red);
public static void SetTextAndHighlightSubstring(this TextBlock targetTextBlock, string sourceText, string subString, Brush highlight = null)
{
if (targetTextBlock == null || String.IsNullOrEmpty(sourceText) || String.IsNullOrEmpty(subString))
return;
targetTextBlock.Text = "";
var subStringPosition = sourceText.ToUpper().IndexOf(subString);
if (subStringPosition == -1)
{
targetTextBlock.Inlines.Add(new Run { Text = sourceText });
return;
}
var subStringLength = subString.Length;
var header = sourceText.Substring(0, subStringPosition);
subString = sourceText.Substring(subStringPosition, subStringLength);
var trailerLength = sourceText.Length - (subStringPosition + subStringLength);
var trailer = sourceText.Substring(subStringPosition + subStringLength, trailerLength);
targetTextBlock.Inlines.Add(new Run { Text = header });
targetTextBlock.Inlines.Add(new Run { Text = subString, Foreground = highlight ?? DefaultHighlight });
targetTextBlock.Inlines.Add(new Run { Text = trailer });
}
You can call this method using the TextBlock extension syntax like so:
TextBlockTitle.SetTextAndHighlightSubstring(_categoryItem.ItemText, _searchText);
In this example, the following display resulted:
I recently ran into the same problem with the broken text binding. I realize this is an old question, but figured I'd share my finding anyway.
Basically Text property's data-binding is severed the moment Inlines.Clear is called. The way I got around this problem was by adding an internal text dependency property that replicated text's binding so subsequent text changes would continue to trigger highlighting.
Try adding something like this before clearing text.Inlines.
protected static string GetInternalText(DependencyObject obj)
{
return (string)obj.GetValue(InternalTextProperty)
}
protected static void SetInternalText(DependencyObject obj, string value)
{
obj.SetValue(InternalTextProperty, value);
}
// Using a DependencyProperty as the backing store for InternalText. This enables animation, styling, binding, etc...
protected static readonly DependencyProperty InternalTextProperty =
DependencyProperty.RegisterAttached("InternalText", typeof(string),
typeof(HighlightableTextBlock), new PropertyMetadata(string.Empty, OnInternalTextChanged));
private static void SetBold(string key, TextBlock text, string SourceText)
{
//Add the following code to replicate text binding
if (textblock.GetBindingExpression(HighlightableTextBlock.InternalTextProperty) == null)
{
var textBinding = text.GetBindingExpression(TextBlock.TextProperty);
if (textBinding != null)
{
text.SetBinding(HighLightKeyWord.InternalTextProperty, textBinding.ParentBindingBase);
}
}
...
}
In InternalTextProperty's propertyChangeCallback you can have the same code as OnBindingTextChanged() or you could refactor them into another method.
For those who don't want to write their own code. I have created a lightweight nuget package that adds highlighting to regular TextBlock. You can leave most of your code intact and only have to add a few attached properties. By default the add-on supports highlighting, but you can also enable bold, italic and underline on the keyword.
https://www.nuget.org/packages/HighlightableTextBlock/
The source is here: https://github.com/kthsu/HighlightableTextBlock

textbox validated method does not work while assigning value to textbox

I am using c#.net 2.0 winforms. I use errorprovider control in my form to validate a textbox. While I programatically assign value to that textbox. textbox validated method does not take the value from the textbox or considers it a blank value. How can I validate my textbox by without entering value in the textbox. Here is the code
private void textBox6_Validated(object sender, EventArgs e)
{
bTest6 = txtRegExPinIsValid(textBox6.Text);
if (bTest6)
{
this.errorProvider1.SetError(textBox6, "");
}
else
{
this.errorProvider1.SetError(textBox6, "This field must contain Exactly 6 digits");
}
}
private bool txtRegExPinIsValid(string textToValidate)
{
Regex TheRegExpression;
string TheTextToValidate;
string TheRegExTest = #"^\d{6}$";
TheTextToValidate = textToValidate;
TheRegExpression = new Regex(TheRegExTest);
// test text with expression
if (TheRegExpression.IsMatch(TheTextToValidate))
{
return true;
}
else
{
return false;
}
}
While performing update operation I fill the textbox with values from the ms access table. If the value is correct, just leave it otherwise I have to update it. Please help me. Thanks in advance
I would recommend placing the validation code in a separate method. Call that method from both the Validated event and the location in your code where you need to programatically validate, as shown below:
// Call this from wherever you need to validate a TextBox
void PerformValidation(TextBox textBox)
{
bTest6 = txtRegExPinIsValid(textBox6.Text);
if (bTest6)
{
this.errorProvider1.SetError(textBox6, "");
}
else
{
this.errorProvider1.SetError(textBox6, "This field must contain Exactly 6 digits");
}
}
private void textBox6_Validated(object sender, EventArgs e)
{
PerformValidation(textBox6);
}

Resources