Home > Java > body text

Set live decimal format to JOptionPane.showInputDialog

WBOY
Release: 2024-02-13 18:00:11
forward
661 people have browsed it

php editor Xiaoxin will introduce to you how to set the real-time decimal format to JOptionPane.showInputDialog. This feature allows the user to enter a live decimal number and format it into the desired format. In this way, users can easily input and process decimal values, which improves user experience and data processing efficiency. Let’s take a look at the specific steps below.

Question content

I have a jformattedtextfield which has decimal format and if the value is less than or equal to 0 it displays showinputdialog to Update it.

How to set up a "live" decimal formatter for showinputdialog?

// Format
NumberFormat format = DecimalFormat.getInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);


// Text field
JFormattedTextField textField = new JFormattedTextField();


// Validation
String regex = "[.,]";
String valueString = textField.getText().split(",")[0].replaceAll(regex, "");
int value = (int) Double.parseDouble(valueString);

while(value <= 0) {
    value = Integer.valueOf(JOptionPane.showInputDialog(parentComponent, "The value must be greater than 0", "Warning", JOptionPane.WARNING_MESSAGE));
}
Copy after login

I do not know what to do.

Workaround

numberformatter (or maskformatter) may be what you are looking for.

NumberFormat format = DecimalFormat.getInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);

NumberFormatter formatter = new NumberFormatter(format); //also check MaskFormatter 
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(false);

// value is be committed on each keystroke instead of focus lost
    formatter.setCommitsOnValidEdit(true);
    
 JFormattedTextField textField  = new JFormattedTextField(formatter);
Copy after login

The above is the detailed content of Set live decimal format to JOptionPane.showInputDialog. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!