JFormattedTextField and getValue vs. getText - java

After reading the docs it is not clear to me the difference between getValue and getText for a JFormattedTextField.
In my code, getText gives me what I think I need while getValue always returns null.
It seems to me, based on the docs, that they should both return the same thing at least after the field, when correctly formatted, loses focus.
The getValue method is supposed to "Returns the last valid value."
A simple explanation would be helpful.

Well JFormattedTextField is a text component that allows to keep a value and give it a custom String representation (format).
This value is an Object which is typically a Date or Number instance, the two classes with most different formats.
So having said this, getValue() returns the value held by formatted text field component while getText() returns the value's String representation.
For further details on this component please take a look to How to Use Formatted Text Fields:
A formatted text field's text and its value are two different
properties, and the value often lags behind the text.
The text property is defined by the JTextField class. This property
always reflects what the field displays. The value property, defined
by the JFormattedTextField class, might not reflect the latest text
displayed in the field. While the user is typing, the text property
changes, but the value property does not change until the changes are
committed.
To be more precise, the value of a formatted text field can be set by
using either the setValue method or the commitEdit method. The
setValue method sets the value to the specified argument. The argument
can technically be any Object, but the formatter needs to be able to
convert it into a string. Otherwise, the text field does not display
any substantive information.

Say you have
JFormattedTextField text = new JFormattedTextField(new DecimalFormat("####.##"));
This is a simple JFormatedTextField for numbers. You enter 12 (a valid entry), and both values will be the same. If you enter "Hello", this is invalid and will not be returned by getValue().
You have probably entered invalid data into the textfield.

Related

Anylogic - Using String Value to get an Object

I have a text object (Shape text) in the Main tab. Right now I am referring the text value by hard coding the name in the areas wherever I use.
I want to add more text objects like text1, text2 etc. which properly follows a pattern for the suffix numbers. I have a variable for count of text objects.
In a function, I want to go through all these text object values using a loop. I am able to generate Strings of "text1", "text2", "text3", etc. using simple for loop.
I want to know how to refer these objects and get the values in the text objects.
Thanks in Advance.
what you can instead, is create a collection (arraylist) that contains all these text objects, if they are ordered in the list the way you want, you can use the index of that collection as your identifier..
collection.get(index);
If you insist in using the name, you can make a collection of type LinkedHashMap where the key element class is String and the value elements class is ShapeText
Then you can know what the text is by using
collection.get("text1"); for instance

Why do we need converters for TextFormatters

My professor said that it is 'ideal' to use a filter and a converter for a TextFormatter. I looked at his examples and tried them, but couldn't understand why we need a converter at all.
From the docs:
A Formatter describes a format of a TextInputControl text by using two distinct mechanisms:
A filter (getFilter()) that can intercept and modify user input. This helps to keep the text in the desired format. A default text
supplier can be used to provide the intial text.
A value converter (getValueConverter()) and value (valueProperty()) can be used to provide special format that
represents a value of type V. If the control is editable and the text
is changed by the user, the value is then updated to correspond to the
text.
I am cleary something missing here. I get why you want to convert a string to an integer (for calculations etc.). But why do you have to have it as a part of TextFormatter? Can't we just use getText() and then just cast the text as we want to have the value?
One more thing: If we have a filter that doesn't allow non-numeric characters, then why do we need to take care of the conversion of the text to integer/double etc. with a converter?
Maybe I am just missing something very obvious.
You can't cast a String to an Integer (or any other type, except an Object): you have to convert it. Even if the text formatter has a filter that only allows numeric entry, the text field's getText() method still returns a string, which is usually not very convenient (as the entry in the text field likely represents a numeric value in some object).
You might need to get the integer (for example) value represented by the text field in many different places, so you centralize the conversion code in one place by including the converter as part of the formatter.
Additionally, the formatter's value is an observable property, so you can easily bind other properties to it, etc. This would be tricky if you needed to perform the conversion in a binding on the text field's text property.

jList doesn't return desired string value

I am new in Java, and I've tried to write a simple GUI application that is supposed to return the selected value of a jList into a textfield.
But instead of the selected text, it returns a memory address like [Ljava.lang.Object;#675b9599 to the textField.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(Arsenal.getSelectedValues().toString());
}
Arsenal.getSelectedValues()//Returns Array of Object and Deprecated as well
-------
Instead use jList.getSelectedValue() Value Not Values which returns selected element.So it should be
jTextField1.setText((String)Arsenal.getSelectedValue());
If you have added String to your JList you would even don't need to convert it to String as it will return value according to the type of JList element.
If you want to get all selected values use getSelectedValuesList() instead of getSelectedValues() because it's deprecated.
You are probably retrieving the text of the selected element in the JList wrong.
You must use the getSelectedValue() to retrieve it.
String text = (String) myList.getSelectedValue();
There is no need to call the toString() method as in myList.getSelectedValue().toString() since that might cause you a NullPointerException if there is no selected value, and the JList instead returns anull` value.
Java docs says:
Returns the value for the smallest selected cell index; the selected
value when only a single item is selected in the list. When multiple
items are selected, it is simply the value for the smallest selected
index. Returns null if there is no selection.
JList only returns the Object.So convert it to the String.
jList.getSelectedValue().toString();
It should work.

Only take specific information from text field

I was wondering how you can take just specific characters from a JTextField. For example if a JTextField has the date 20/12/2012 then how do you read only the "12" form the Field.
So is it possible and if so how or would it be easier to use multiple JTextFields?
One approach would be read full text, but split string based on "/" and take 0 index value in resulting array.
(or)
Parse String using SimpleDateFormatter and get Month from Date (assuming entered string will be always date)
If none of above works, then it would be easier to use multiple text fields
StringTokenizer can break up your string for you.
SimpleDateFormat can handle dates if you know the format in the field will be correct.
However having multiple fields for dates is common. You may just want different fields depending on your overall use of the data and user interaction with it.

Format a Jtable Cell, if illegal format, then do nothing

Say I have following columns in my Jtable:
{"Item", "Price"}
I want format the price column to "0.00" format.
But if user enter an illegal string, then keep the original value of the cell.
ex, when the price is "1.23", but when user want to enter "abc", then the cell should still be "1.23"
How could I do this?
Thanks
Let's split your big problemn into smaller ones.
First, you want to have items of your Price column to be displayed according to a specified format, which you can achieve using a TableCellRenderer (which, when rendering numbers, will use a NumberFormat to display the correct number of decimals). As your table has only two columns of different types, the simplest solution is to use JTable#setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer). This way, your numbers will always be displayed using the correct number of decimals.
Second, for your edition issue, the same solution can be rather elegant : call JTable#setDefaultEditor(java.lang.Class, javax.swing.table.TableCellEditor) and set as editor a component one that will, before commiting change to your table model, ensure the new value is a valid number (valid of course according to your rules).
A JTable supports this by default. The table will choose the renderer/editor based on the data stored in each column. So all you need to do is override the getColumnClass(...) method to return Double.class. Then when you edit a cell the editor will make sure the value entered is a valid number.
If you want more control over how the number is formatted then you can use Table Format Renderer.
JFormattedTextField works the way you describe so just create a new CellEditor that extends JFormattedTextField.
Put the formatting command into a try/catch block. If the operation fails with an NumberFormatException, cancel the edit.
Using your original code, make a few minor changes:
public void setValue(Object value) {
NumberFormat formatter = new DecimalFormat("0.00");
String s = null;
try {
s = formatter.format(Integer.parseInt((String)value));
if (null != s) setText(s);
} catch (NumberFormatException ex) {
// what could I do here?
// You could display a warning JOptionPane and/or output to System.out
}
}

Categories