i have a JFormattedTextField , and i want that when i try to enter a number, example 1002 , that i will rounded to the nearest multiple of 5
1002->1000
304->305
6->5
9->10
1->0
etc..
i've already setup a number format to cancel the grouping, and accepting only numbers
NumberFormat format=NumberFormat.getInstance();
format.setGroupingUsed(false);
pun1[i]=new JFormattedTextField(format); //pun1 and pun2 are the arrays of FIELDS
pun2[i]=new JFormattedTextField(format);
how can i resolve this problem?
I want this editing inside the field, while i'm writing the number, just as when the grouping character appears!
This works for int arguments:
public int roundToClosestFive(int num) {
return (int) (Math.round(num / 5.0) * 5);
}
Remember, to get the int value of the string you've entered you can do: Integer.valueOf(string); and pass that as an argument to the method. To have the text inside the JFormattedTextField change on focus change or enter, you could call the above method from the propertyChange() method of a PropertyChange listener that you can add to the JTextFormattedTextField. Something like this in the propertyChange() method:
public void propertyChange(PropertyChangeEvent e) {
Object source = e.getSource();
if (source == pun1[i]) {
((JFormattedTextField) source).setText(""
+ roundToClosestFive(((Number)pun1[i].getValue()).intValue()));
}
}
Related
This question already has answers here:
Restricting JTextField input to Integers [duplicate]
(6 answers)
Closed 3 years ago.
I want to control user input text on jtextfield. It seems I can't find any good way in netbean 8. in C# use keypress event, but in java I'm new.
I choose key type event
I want input only number with 2 digit after decimal
10.00
1224547885544.12
545545464646464646465466.10
not
12121212.654654654654
I've tried
// not a good idea
char c=evt.getKeyChar();
if((Character.isDigit(c))||(c==KeyEvent.VK_PERIOD)||(c==KeyEvent.VK_BACK_SPACE)){
int punto=0;
if(c==KeyEvent.VK_PERIOD){
String s=pricefield.getText();
int dot=s.indexOf('.');
punto=dot;
if(dot!=-1){
getToolkit().beep();
evt.consume();
}
}
}
else{
getToolkit().beep();
evt.consume();
}
//second try
char enter = evt.getKeyChar();
if(!(Character.isDigit(enter))){
evt.consume();
}
it's not good idea I think.
try other many ways.
please, help me.
Assuming you are referring to a JavaFX TextField:
You can get the textProperty of the textfield by calling textField.textProperty(). Since this is a property, you can attach a listener to it, to listen for changes to the text in the field:
textField.textProperty().addListener((observable, oldValue, newValue) -> {
// this code is called whenever the text in the field changes
// oldValue is the text contained before the event was triggered
// newValue is the text that the field is about to be set to
if (oldValue.contains("[a-zA-Z]")) { // any predicate you want/need
textField.setText(oldValue); // revert the text of the field back to its old value
}
});
For a Swing TextField, that should help you:
JFormattedTextField textField = new JFormattedTextField();
textField.setFormatterFactory(new AbstractFormatterFactory() {
#Override
public AbstractFormatter getFormatter(JFormattedTextField tf) {
NumberFormat format = DecimalFormat.getInstance();
//or two, if you want to force something like 10.00
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);
InternationalFormatter formatter = new InternationalFormatter(format);
formatter.setAllowsInvalid(false); //important!
return formatter;
}
});
I have a project and my Java program in Swing uses a double array to accept values from the user and print the total of the items, kind of like an order form.
Say the user enters no value in the text box, this shows an error and prevents further calculations.
My question is ,what should I code in order for the computer to understand that there is nothing entered in the text box , so just take the value as 0. I want to either do this by comparing/converting the double array value to a string and then continuing with calculations .
Here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
double price[]=new double[]{0.25,8.55,0.50,0.25};
double amount[]=new double[4];
double quantity[]=new double[4];
quantity[0]=Double.parseDouble(jTextField1.getText());
quantity[1]=Double.parseDouble(jTextField2.getText());
quantity[2]=Double.parseDouble(jTextField3.getText());
quantity[3]=Double.parseDouble(jTextField4.getText());
for(int i=0;i<4;i++) // I want to use a for-loop or if-statement to
check if there is a value entered or not
{
if()
{
quantity[i] //no clue what to do here.
}
}
for(int i=0;i<4;i++)
{
{
amount[i]=quantity[i]*price[i];
}
}
jTextField5.setText(String.valueOf(amount[0]));
jTextField6.setText(String.valueOf(amount[1]));
jTextField7.setText(String.valueOf(amount[2]));
jTextField8.setText(String.valueOf(amount[3]));
First you would want to check if the text fields are empty or a String value before parsing them. And you will likely need to do it for all of the fields.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// check the values of the text fields including an or condition for regular expressions
if (jTextField1.isEmpty() || jTextField1.getText().matches("\\d+.?\\d*") {
// you can use something like a modal to alert
JOptionPane.showMessage(null,"Must enter a decimal value");
} else {
// do something with jTextField1
}
}
You can use
if (!jTextField1.getText().isEmpty())
I have a decimal number in EditText and I'm trying to change it to always show a decimal part but the user doesn't be able to change the decimal part, only the integer part has to be editable. The decimal part is always a default value.
Example: I have the number 2.025,50 at EditText, if I delete all the digits Ill have 0,50. If I write 10 , Ill have 10,50.
Can anyone help me out ??
I created a function you can use for this, so you just input your number with a decimal and it will give you the decimal part of the number. Use editText changed listener. So when u pass the value being typed by a user call this function and pass the numberWithTheFraction to the function getFractionalPart and add the userinput as shown in the code bellow.
private static double getFractionalPart(double num) {
if (num > 0) {
return num - Math.floor(num);
} else {
return ((num - Math.ceil(num)) * -1);
}
}
you can have a look at this example for an example of editText change listener.
So in the above example when you say textView.setText(getFractionalPart(numberWithTheFraction)+userInput)
I am making a colour changer using RGB input, and I want to make sure the input's are integers whilst parsing. If one of the RGB values is not parsable, then it should clear that field but keep the fields that parsed fine. My code works but I have to use 3 try/catch statements but I want to reduce it to one. How would I merge all these three if possible?
How would I merge all these three if possible?
Move common code to helper method. I added value range check too.
private static int getChannelValue(JTextField field) {
String error;
try {
int value = Integer.parseInt(field.getText());
if (value >= 0 && value <= 255)
return value;
error = "Out of range";
} catch (NumberFormatException f) {
error = "Not an integer number";
}
JOptionPane.showMessageDialog(null, "No. " + error);
field.setText("");
return -1; // invalid
}
int r = getChannelValue(codeR);
int g = getChannelValue(codeG);
int b = getChannelValue(codeB);
if (r != -1 && g != -1 && b != -1)
centreName.setForeground(new Color(r, g, b));
I assume that you are having all of these values gather once a JButton is clicked? Well, instead of doing that why not store the values when the client is done writing to the TextFields and then use parseInt on that specific field?
field.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) { }
#Override
public void focusLost(FocusEvent e) {
// parse and store int here
}
});
Since Color only accepts integers 0-255, you could instead use a regex
inputString.matches("[12]?\\d?\\d")
The regex accepts 1/2/nothing for the first digit, a number or nothing for the second digit, and requires the third digit
This works for 0-255, but also accepts numbers like 05, 00, and 260 (but not 005, unless you make it [012]), but Integer.parseInt() will figure them out
You may want to also exclude values like 260, which is covered in: Validate if input string is a number between 0-255 using regex
inputString.matches("1?[0-9]{1,2}|2[0-4][0-9]|25[0-5]")) will exclude values like 260, but not 05 or 00
I'm trying to learn something about GUI, using NetBeans6.8, starting with the GUI section in The java tutorial.
There is a simple exercise for a Celsius-Fahrenheit converter. I want that to have two TextFields, one for Celsius and one for Fahrenheit temperature; if the user types in the celsius text field he got the result "printed" in the fahrenheit text filed. and vice versa.
So, i put on both the textfields one KeyTyped event, here's the code:
private void celsiusTextKeyTyped(java.awt.event.KeyEvent evt) {
int cels = Integer.parseInt(celsiusText.getText());
int fahr = (int)(cels * 1.8 + 32);
fahrText.setText(fahr + "");
}
private void fahrTextKeyTyped(java.awt.event.KeyEvent evt) {
int fahr = Integer.parseInt(fahrText.getText());
int cels = (int)(fahr / 1.8 - 32);
celsiusText.setText(cels + "");
}
It doesn't work. If i type something in a textfield i got this exception: java.lang.NumberFormatException: For input string: ""
The code that attach the listeners:
celsiusText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
celsiusTextKeyTyped(evt);
}
});
fahrText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
fahrTextKeyTyped(evt);
}
});
[However, i can't modify it, it's autogenerated.]
Method .getText() returns a string not a number, if that string contains non-numeric characters (i.e. a letter, a space, nothing at all) then parseInt will throw a NumberFormatException. Since your using KeyEvent, as soon as you press say "7", the event is fired before 7 is entered into the text box. Thus the text box still only contains "", which is where the error comes from. You may wish to also listen to the keyUp event instead.
You need to enclose your code in a try catch block.
private void fahrTextKeyTyped(java.awt.event.KeyEvent evt)
{
try
{
int fahr = Integer.parseInt(fahrText.getText());
int cels = (int)(fahr / 1.8 - 32);
celsiusText.setText(cels + "");
}
catch(NumberFormatException ex)
{
//Error handling code here, i.e. informative message to the user
}
}
An alternative is you could filter out non-numbers on keydown event, see example here - http://www.javacoffeebreak.com/java107/java107.html (Creating a custom component - NumberTextField)
I suspect that what's happened is that you added these handlers with something like celsiusText.addKeyListener, yes?
The thing is, that'll give you not just the KEY_TYPED events you wanted, but also KEY_DOWN and KEY_UP. The KEY_DOWN event will happen before the text is really entered into the field, so your code firing on that will see the field as blank still. Trying to convert the empty string to a number gives you a format exception.
The easiest way to fix this is the try/catch construct other people have been posting.
You probably set action to keyDown, this mean that even occur before the key value is "added" to textbox, while You retrieve the value from it is still empty "".
There is a simple exercise for a
Celsius-Fahrenheit converter
That is a really old example. The better approach is to use a DocumentListener, not a KeyListener.