I've used the following line of code to only allow users to enter digits inside a JFormattedTextField which collects information on time
final JFormattedTextField periodTextField = new JFormattedTextField();
periodTextField.setFormatterFactory(new DefaultFormatterFactory(createFormatter("##:## - ##:##")));
When running my application the text field will appear as ": - :" by default, but I would like it to appear as "00:00 - 00:00" as default, and editing the text field will only change the values of the 0's nothing else. I've looked at this guide for help on using formatters in java, but it doesn't mention how you can set default values. Is there a simple way to achieve what I need.
Related
Here is a picture of my JTextArea:
Here is my code:
String display = "";
display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
stocks + "\t\t\t" + req +"\n";
txtArea.setText(display);
What should I do so that the texts are aligned properly regardless of the length of characters of the words?
As much as possible I want to use JTextArea not JTable (since I'm not familiar with it yet)
Thank you in advanced!
Use a JTextPane instead of JTextArea, as that can do HTML. Then add an HTML <table>. Probably with some styles.
StringBuilder display = new StringBuilder("<html><table>");
display.append("<tr><td align='right'>").append(num)
.append("</td><td>").append(name)
.append("</td><td align='right'>").append(stocks)
.append("</td><td>").append(req)
.append("</td></tr>");
display.append("</table>");
txtPane.setText(display.toString());
This allows proportional fonts and styled text like bold, red, background colors.
As mentioned by #AndyTurner above your best approach is to rely on the String formatter to set the character width of each variable to print with also the ability to right or left justified. So in your case, as you left justified everything it could be something like that:
txtArea.setText(String.format("%-3s%-20s%-5s%-5s%n", num, name, stocks, req));
In this example I allocated 3 characters for num, 20 for name and 5 for stocks and req.
More details here
I want to use JTextArea not JTable (since I'm not familiar with it yet)
Well, now is the time to become familiar with a JTable. Use the proper component for the job, that is why multiple components exist. Don't try to fit a square peg in a round hole.
A JTextArea is not the appropriate component for that kind of formatting.
Instead you should be using a JTable. A JTable is designed to display data in a row/column format. Check out the section from the Swing tutorial on How to Use Tables for more information and working examples.
If you must use a text component then use a JTextPane. You can manually set the value of a tab so all the text is aligned. The problem with this approach is again you need to determine what the size of each tab should be. So this means either you make a random guess at the size of each column or you iterate through all the data to determine the size. Of course this complicates the code. See: Java Setting Indent Size on JTextPane for an example.
Again, the better solution is to learn to use Swing how it was designed to be used.
String display = "";
// just add values accordingly the best way to get the result you
// want is to mess around with formatting until you have the values
// where you want them in the textfield.
display = String.format("%20s %10s%n", value1, value2);
//display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
// stocks + "\t\t\t" + req +"\n";
txtArea.setText(display);
As the title suggests, I have the following listener on a JFormattedTextField:
myFormattedTextField.addPropertyChangeListener("value", new PropertyChangeListener()
{
#Override
public void propertyChange(PropertyChangeEvent evt)
{
System.out.println("Old value: " + evt.getOldValue());
System.out.println("New value: " + evt.getNewValue());
}
});
This always prints out null for both getOldValue() and getNewValue().
If I remove "value" string as a parameter, I get even weirder results, like the JPanel the textField is residing in or true/false values.
What exactly am I missing here?
What exactly am I missing here?
It's hard to tell exactly what is the problem based on your snippet. However be aware that JFormattedTextField component works along with both an AbstractFormatterFactory and an AbstractFormatter to be able to convert from a String representation to an Object value and the other way around.
If you initialize the formatted text field as follows, then both formatter and formatter factory will be null and no value could be ever converted: thus it will always be null:
JFormattedTextField textField = new JFormattedTextField(); // default empty constructor
If this is the case then you have an explanation about what is happening. If you take a look JFormattedTextfield class' constructors all of them take parameters that will help the component to initialize both formatter and formatter factory, except for empty constructor.
For a better understanding please have a look to How to Use Formatted Text Fields tutorial.
Side note
You say in a comment:
I am not using a NumberFormatter. Since the text fields can be blank to start with.
It's irrelevant if you want the text field be blank at the start: just don't set any value to the text field and leave the user change it (of course initial value will be null). But you definitely need to set a formatter.
if you are using NumberFormatter this may solve your problem:
numberFormatter.setCommitsOnValidEdit(true);
Is it possible to set MaskFormatter of a JFormatterTextField to ##,## and the value type of the JFormatterTextField to Float? I tried it using the following mask for a default formatter factory but it does not work and the getValue().getClass() gives me java.lang.String.
DefaultFormatterFactory dff = new DefaultFormatterFactory();
mf = new MaskFormatter("##,##);
mf.setValueClass(Float.TYPE);
dff.setDefaultFormatter(mf);
field.setFormatterFactory(dff);
And the problem with number formatting is that it doesn't mask the field for me.
PS. My default system configuration uses "," as "." in the English one. So it's not the problem and I brought it just for precision.
You are running into a bit of a limitation of JFormattedTextField here.
If you use DecimalFormat http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html you can set up the display to look however you like but it does not rigidly enforce what the user types. The returned result will be a number.
If you use MaskFormatter then you get the rigid enforcement, but the value returned is a string.
You could use the MaskFormatter and simply pass it to Float.valueOf(str) when you need the result. The alternative is to either implement your own format object or to listen on some of the events provided by the text field and/or its backing document and directly do your own control of the users entry.
I have a textfield in which I want to restrict user to enter only valid number with 14 digit before .(dot) and 4 digit after .(dot).
I have tried it using :
<mx:TextInput id="txtValue1" restrict="[0-9]*\.?[0-9]" maxChars="19"/>
Its not working for restriction 4 digit after .(dot).
A more common way would be to use a NumberValidator, and set the precision attribute of the validator to 4. Also, set the maxValue of the NumberValidator to whatever suits, then set the source of the NumberValidator to the textInput id. That should work I'd say, and it will also allow you to set the error fields of the validator which will pop up beside the textInput if incorrect number is entered
you can view and download a code (this works!) in my public repository from this LINK.
Basically, i created a class (NumberInput) based on TextInput class from Adobe, the diferrence in both classes was the textFieldChanged method, i add a call here to myFormat function(). This function does what you're needing.
Be careful with this class, do not use it as the final solution but I will anyway to find what you need. Check the SWF called NumberInputTest.swf, source code is in src\NumberInput.as.
I hope this help you. Sorry for my english :D.
How do you add zero padding to a JSpinner?
Since the spinner creates the JFormattedTextField itself, I can't just pass the format into the JFormattedTextField constructor.
Isn't there a way to set the formatting on an existing JFormattedTextField?
What I want: value = 37, editor = "0037"
UPDATE:
I have tried this as suggested:
JSpinner mySpinner = new JSpinner();
mySpinner.setEditor(
new JSpinner.NumberEditor(mySpinner, "####"));
and the result is no change at all to the presentation of the spinner's data. It seems like a reasonable solution; has anyone tried this successfully so I can be sure it's just something flaky in my own application?
You can set the editor yourself, like this:
// minimum of four digits
mySpinner.setEditor(new JSpinner.NumberEditor(mySpinner, "0000"));
"0000" is a DecimalFormat string specifying four digits, zero-padded as necessary; "####" specifies four digits but does not zero-pad.
The DecimalFormat API documentation covers formatting strings in more detail.
Referring to the javadocs, JSpinner has a setEditor(JComponent) method. Use that to set your custom JFormattedTextField, with its custom Format.