问题
Anyone know how to auto add $ sign into the textfield when the user enter in the field and also disable the user from cancel the $ sign.
回答1:
Not "strictly" what you're asking, but start by taking How to use for attend text fields, for example...
paymentField = new JFormattedTextField(NumberFormat.getCurrencyInstance());
paymentField.setValue(new Double(payment));
paymentField.setColumns(10);
paymentField.setEditable(false);
The problem with this is it's possible for the user to remove the $ sign and the validation is very strict, meaning that the text entered into the field MUST start with a $
Another possibility is to use the BuddySupport API from Swing Labs, SwingX library
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
paymentField = new JFormattedTextField(nf);
paymentField.setValue(100d);
paymentField.setColumns(10);
paymentField.setEditable(false);
BuddySupport.addLeft(new JLabel("$"), paymentField);
This means that that $ is a separate component from the actual field and can't be removed by the user (but is contained within the field so it is not affected by the parent container's layout manager)
回答2:
The java.awt.TextField could be monitored for changes by adding a TextListener for TextEvent's. In the JTextComponent based components, changes are broadcasted from the model via a DocumentEvent to DocumentListeners. The DocumentEvent gives the location of the change and the kind of change if desired.
You need to use the DocumentListener and combine it with some Regex to do the magic. If the text at a given point does not match the format you want, do not update the JTextField or simply using the .charAt() method would do but then it is up to you
SSCCE without DocumentListener
package stack;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class OhMyDollar {
static JFrame frame;
static JTextField field;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
frame = new JFrame("Useless Title");
field = new JTextField("$", 30);
frame.getContentPane().add(field);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
field.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent event) {
}
@Override
public void keyReleased(KeyEvent event) {
}
@Override
public void keyTyped(KeyEvent event) {
StringBuffer text = new StringBuffer(field.getText());
StringBuffer dollar = new StringBuffer("$");
if(field.getText().isEmpty() || text.charAt(0)!='$'){
field.setText(dollar.append(text).toString());
}
}
});
}
});
}
}
来源:https://stackoverflow.com/questions/21495886/adding-sign-into-the-textfield-when-the-user-enter-in-the-field