I want a JTextFeild event when keyboard button pressed.I want concatenate "ADZ" text to the front whole text.(If we enter "2" whole text should be "ADZ2") THe Action will performed only first key press.After any key pressing action won't be performed.Action will performed only once.
I tried below code,but if type 22 it gives"ADZADZ22".
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
JTextFeild1.setText("ADZ"+num1);
I want this if type 22, it will gives ADZ22.
A simple way to solve it, is to check if the prefix is already there.
This avoids that the same prefix is added twice.
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
if (!num1.startsWith("ADZ"))
{
num1 = "ADZ" + num1;
JTextFeild1.setText(num1);
}
...
}
Please note: Java coding rules would suggest to make field names (e.g. jTextField) start with a lower case character. The same goes for method names (e.g. private void jTextField1KeyTyped)
public static int counter = 0;
Maintain a static counter at class level. At key press increase it by one. check :
if(counter == 1) {
// do your operation
}
Check if your JTextField is empty and then set a prefix. This method sets "ADZ" when the field is empty and you type something and then appends everything you type.
public void keyTyped(KeyEvent ke) {
if(txfInput.getText().equals("")) {
txfInput.setText("ADZ");
}
}
Related
I am trying to retrieve the values from a JTextField on a keypress to do something if the values are integers and to clear the field if the values are not integers. Every time I try to retrieve the value, I am getting the value entered before that(if I enter 12 I get 1 back then if I enter 123 I get 12 back) and when I try to clear the field on an invalid character everything but the invalid character gets cleared?
public void setUpListeners()
{
JTextField jT [] = myV.getTextFields();
jT[0].addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
int id = e.getID();
if (id == KeyEvent.KEY_TYPED)
{
char c = e.getKeyChar();
try
{
//check if chars entered are numbers
int temp = Integer.parseInt(String.valueOf(c));
String tempS = jT[0].getText();
System.out.println(tempS);
}
catch(Exception ex)
{
jT[0].setText("");
System.out.println("Not an integer");
}
}
}
});
}
You could do the following:
public static boolean validateNumber(char num){
return (num >= '0' && num <='9');
}
And then use parameter KeyEvent "e":
if(!validateNumber(e.getKeyChar()))
e.consume();
And instead of using
public void keyTyped(KeyEvent e){
use
public void keyReleased(KeyEvent e){
I think you will get what you need, I hope I have helped you ;)
Swing components use Model-View-Controller (MVC) [software] design pattern / architecture. The model holds the data. For a JTextField the data is the text it displays. The default model for JTextField is PlainDocument, however JTextField code actually refers to the Document interface which PlainDocument implements.
Look at the code for method getText() in class JTextComponent (which is the superclass for JTextField) and you will see that it retrieves the text from the Document.
When you type a key in JTextField, the character gets passed to the Document. It would appear that your keyTyped() method is invoked before the character you typed reaches the Document, hence when you call getText() in your keyTyped() method, you're getting all the text apart from the last character you typed.
That's one of the reasons not to use a KeyListener in order to validate the text entered into a JTextField. The correct way is detailed in the question that tenorsax provided a link to in his comment to your question.
Apart from DocumentFilter or JFormattedTextField (or even InputVerifier), you can add an ActionListener to JTextField which will execute when you hit Enter in the JTextField. You will find many on-line examples of how to implement each one of these options, including the link provided in tenorsax comment.
I am developing a Java Swing application that has a number pad using JButtons. It has numbers 0 - 9, a dot for the decimal and an enter button. Obviously, the number on the button is just a character and not an integer as I intend it to be.
I want the user to be able to click the buttons to enter a currency amount such as $25.68. When they have finished they will press enter.
I want to take this amount and put it into a double variable.
In the actionPerformed function I will do the usual:
if (e.getSource() == numberButton1){
//put in first index of array
}
Initially I thought I would put this into an array of integers and account for the dot button by assigning it to -1 and the enter as -2. But once I have the numbers in the array they will be backwards and I know I could read them out in reverse by counting the number of elements and starting at the last index then using a factor of 10 as I go along but all this seems overly complicated. Not to mention having to account for the decimal place. So before I start writing a million lines of code I thought I would ask...
...is there a simple way to do this?
Consider taking a look at Actions API, it will allow you to define a self contained action which you can configure any way you like
For example...
public class NumberAction extends AbstractAction {
private char value;
private JTextField field;
public NumberAction(char value, JTextField field) {
this.value = value;
this.field = field;
putValue(NAME, Character.toString(value));
}
#Override
public void actionPerformed(ActionEvent e) {
String text = field.getText();
text += value;
field.setText(text);
}
}
Now, I've simply used char as the base value as, realistically, your not actually making use of the any kind of numeric value...
You would construct your buttons doing something like...
JButton num7 = new JButton(new NumberAction('7', field);
JButton num8 = new JButton(new NumberAction('8', field);
JButton num9 = new JButton(new NumberAction('9', field);
//...
For example...
Declare a global String value. For each numeric or dot(.) button press concatenate the number or dot to the string. Then parse the string as double when you need to use it. Here is an example:
String value = "";
// Lines of code
if (e.getSource() == numberButton1)
{
value += "1";
}
if (e.getSource() == dotButton)
{
value += ".";
}
// Do the same for other numbers
// When you need the value as a double do the following
double _value = Double.parseDouble(value);
PS: Don't forget to add a check if user presses the dot two times. You cannot have two decimals.
Concatenate all inputs in string
Then at enter button clicked parse the string as double
Declar
String value ="";
double val =0;
At each button
value=value+"3";
And...
value=value+".";
And so on.
Then at enter button
val =Double.parseDouble(value);
Now its numiric double... Use it
I have following code that needs something smart to deal with typed in chars and detection:
private final MultiWordSuggestOracle mySuggestions = new MultiWordSuggestOracle();
private final Set<String> mySuggestionsData = new HashSet<String>();
#UiHandler("suggestBox")
public void onKeyPress(KeyDownEvent event) {
if (Character.isLetterOrDigit(event.getCharCode())) {
char[] text = suggestBox.getText().trim().toCharArray();
if (text.length != 1) return;
for (char ch : text) {
if (!Character.isLetterOrDigit(ch)) {
return;
}
}
//load data from server into mySuggestionsData
}
}
The question has 3 parts:
How do you test pressed key against alphanumeric chars. Keep in mind this is GWT so I would rather not use regex ( but if there is no other option ...).
What is the best way to detect the length of text typed into the SuggestBox?
Is KeyDownEven the best choise? And why is it triggered twice when any key is pressed?
Instead of handling events, you should make your own SuggestOracle (possible wrapping a MultiSuggestOracle used as an internal cache) and check the query's length and "pattern" there to decide whether to call the server or not (and then give an empty list of suggestions as the response, or maybe a single suggestion being the exact query).
As a side note, I don't understand why you don't want to use a regex; either using the java.lang.String methods taking a regex as a String, or the com.google.gwt.regexp.shared.RegExp class.
1. I'd use KeyPressHandler instead of Up/Down handler.
As far as I understand, you are more interested to get what the user has typed but not the key that was actually pressed on the keyboard. Also, you can use Character.isDigit(c) and Character.isLetter(c) since KeyPressEvent.getCharCode() will return char (c).
2. Likely you want to check text length at some point (e.g. when user presses Enter), then
// handler block
if (c == KeyCodes.KEY_ENTER) {
int length = ((SuggestBox) event.getSource()).getText().length();
// take an action depending on length
}
// handler block continued
should fit.
3. See [1] and perhaps it's browser specific.
Edit: [1],[2] and [3] combined (using KeyUpHandler):
private static final int THREASHOLD = 2;
private String phrase = "";
...
searchBox.addKeyUpHandler(new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
String text = ((SuggestBox) event.getSource()).getText();
if (!phrase.equals(text)) {
if (text.length() >= THREASHOLD) {
boolean alphanum = true;
for (int i = 0; i < THREASHOLD; i++) {
char c = text.charAt(i);
if (!Character.isDigit(c) && !Character.isLetter(c)) {
alphanum = false;
break;
}
}
if (alphanum) {
//RPC (won't be called twice)
}
}
phrase = text;
}
}
});
I have a String named updatedDisplay that is set to empty in the constructor.
The buttons[] are JButtons and alarmCode is a String field.
I want the user to press four buttons (and they should be concatenated and stored in the updatedDisplay field).
The checkCode() method is executed to try match updatedDisplay against alarmCode. Trouble is, they never match. I think it may be something to do with a "space" when I originally declare my updatedDisplay as follows:
private String updatedDisplay = " ";
The updatedDisplay field doesn't seem to be storing the e.getActionCommand() value.
//add actionListeners to each button (except the "clear" button) to display value on screen
for (int i = 0; i< (buttons.length -1); i++) {
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//store the name of the button in a local variable
String command = e.getActionCommand();
System.out.println("You clicked " + command);
updatedDisplay = updatedDisplay + command;
//updatedDisplay = command;
System.out.println (updatedDisplay);
screen.setText(updatedDisplay);
}
});}
I have an armButton that, when pressed, should trigger the checkCode() method. The method checks if updatedDisplay and alarmCode are equal:
//add actionListener to the arm button
armButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
checkCode();
}
});
checkCode():
public void checkCode() {
//check if user entered the correct code
if (updatedDisplay == alarmCode)
{
updatedDisplay = "System Armed!";
screen.setText(updatedDisplay);
}
else
{
updatedDisplay = "Incorrect Code, Try again!";
screen.setText(updatedDisplay);
}
}
Even when I output the button presses to the terminal window they look right - but as I said, I suspect a "space" is being entered at the start.
Any ideas?
Solution
Try:
if( updatedDisplay.equals( alarmCode ) { // ...
Comparison
To understand this, read:
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Summary
Since updatedDate and alarmCode are object references, you must ask the objects to compare their values. You can think of them as pointers whose values are locations in memory that contain strings. Rather than comparing the value of the pointers (references), you want to compare the text that starts at that memory location.
I have a calculation application which I need to validate the fields to check if the values entered are numeric numbers and not alphanumeric. I have some ideas about the codes.
Please guide me if I have done anything wrong or seem noob as this is my first time trying out Swing.
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text1 = jTextField1.getText(); // TODO add your handling code here:
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
String text2 = jTextField2.getText(); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (text1 and text2 != <numeric number>){
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
// TODO add your handling code here:
}
Please do help. By the way why does my NetBeans keep informing me that it does not recognize the "JOptionPane" Command?
Float.parseFloat() will throw a NumberFormatException if the String isn't numeric and cannot be parsed into a Float. You can add a try-catch block to check for this condition:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
float num1, num2, result;
try {
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
result = num1+num2;
jTextField3.setText(String.valueOf(result));
} catch (NumberFormatException e) {
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
}
If alphanumeric input is not valid for the Swing component in the first place, then instead of validating this post-entry, you should restrict the component to accept only certain format in the first place.
Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.
That said, you can, among other things, use Integer.parseInt(String s) to see if an arbitrary string can be parsed into an int; the method throws NumberFormatException if it can't. There are also Double.parseDouble, etc.
See also
Java Tutorials/Swing/How to use Formatted Text Field
How to use the Focus Subsystem/Input Validation
Java Tutorials/Internationalization/Formatting - Numbers and Currencies
Related questions
A simple way to create a text field (or such) that only allows the user to enter ints/doubles in Java?
A textbox class only accept integers in Java
Validating an integer or String without try-catch - java.util.Scanner option
try {
Integer.parseInt(foo);
} catch (NumberFormatException e) {
// Naughty
}
Try this:
String temp = txtField.getText();
try
{
int val = Integer.parseInt(temp);
}
catch(NumberFormatException e) {
System.out.println("Invalid");
}
To make it more enjoyable, use JOptionPane (makes it more more interactive)
textFieldCrDays = new JTextField();
textFieldCrDays.addKeyListener(new KeyAdapter() {
//// validate onlu numeric value
public void keyTyped(KeyEvent e) {
if (textFieldCrDays.getText().length() < 3 && e.getKeyChar() >='0' && e.getKeyChar() <= '9')
{
// Optional
super.keyTyped(e);
}
else
{
// Discard the event
e.consume();
}
}
});
A relatively old question, but I figured I would take a shot at it, to maybe help out the random Google Searches.
Another approach someone could take to minimise code and reduce the number of additional classes is to add a KeyListener for the keyType event and check for the Char value. This isn't very portable (you can't use region specific formatting such as numerical punctuation), but this could be quite helpful for straight integers.
You could also do a relative length here as well:
textField.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent keyEvent)
{
if (textField.getText().length() < 3 && keyEvent.getKeyChar() >= '0' && keyEvent.getKeyChar() <= '9')
{
// Optional
super.keyTyped(keyEvent);
}
else
{
// Discard the event
keyEvent.consume();
}
}
});
You can also add another event listener to validate the entire integer for further processing (the entire number must be > 800 and < 5220 for example).
A good place for this would be on the focusLost event(?).
If you are doing these features frequently, it would be best to subclass the JTextField class to provide this functionality.
EDIT: Using Character.isLetter(keyEvent.getKeyChar()) is even more clear.