private JTextField f1TextField;
f1TextField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
char key = e.getKeyChar();
String text = f1TextField.getText().trim();
if((text.indexOf('.') > -1) && key == '.'){
e.consume();
}
if(!Character.isDigit(key) && key != '.' && key != '-'){
e.consume();
}
if((text.indexOf('-') > -1) && key == '-'){
e.consume();
}
if((text.indexOf('-') == -1) && key == '-' && !text.equals("") && !text.equals(".")){
f1TextField.setText(String.valueOf((Double.parseDouble(text))*(-1)));
e.consume();
}
}
});
This is the KeyListener that I want to provide for a lot of my JTextFields, howefer I no longer have idea how to do it. I tried creating Class that extends JTextField and implements KeyListener (with this code under KeyTyped) but that did not solved my problem (in .form of my application there was an error that says that Class is not found and "Form contains components with custom create option but no createuicomponents() method", after creating createuicomponents() program starts but my custom JTextField is not working as it should be. Is there any way to do this easily or am I making some mistake that I do not know? I'm really not well advanced in Java, please help ;(
CodePudding user response:
You make your anonymous class an actual class.
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class JTextFieldKeyListener extends KeyAdapter {
private final JTextField textField;
public JTextFieldKeyListener(JTextField textField) {
this.textField = textField;
}
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
char key = e.getKeyChar();
String text = textField.getText().trim();
if ((text.indexOf('.') > -1) && key == '.') {
e.consume();
}
if (!Character.isDigit(key) && key != '.' && key != '-') {
e.consume();
}
if ((text.indexOf('-') > -1) && key == '-') {
e.consume();
}
if ((text.indexOf('-') == -1) && key == '-' && !text.equals("")
&& !text.equals(".")) {
textField.setText(String.valueOf(
(Double.parseDouble(text)) * (-1)));
e.consume();
}
}
}
Then, you create as many instances as you need.
f1TextField.addKeyListener(new JTextFieldKeyListener(f1TextField));
f2TextField.addKeyListener(new JTextFieldKeyListener(f2TextField));
f3TextField.addKeyListener(new JTextFieldKeyListener(f3TextField));
...
If you're using a GUI builder, you have to figure out how to add your new class and instance calls. That's why I always recommend that you write Swing code by hand.