input in text field only number in java application - java

DishFormPanelistIdLbl.setText("Panelist ID:");
DishFormPanelistIdTxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DishFormPanelistIdTxtActionPerformed(evt);
}
});
I have here a text label and text field for ID i want to input only numbers in text how is it possible?been trying the sample program un net beans but they dont have such a solution for this problem any help is appreciated
"Update"
What i want here is when i type letter nothing will show but when number then it will show

What i did is in the design mode i right click the text field > Events > Key > KeyTyped
then in the code i hade something like this
private void DishFormPanelistIdTxtKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
char enter = evt.getKeyChar();
if(!(Character.isDigit(enter))){
evt.consume();
}
}
i didnt get the solution here in stack but i will link it this is the link

You could do this by using a JFormattedTextField. It's pretty straight forward: you pass it a formatter (which extends AbstractFormatter), and the formatter will allow you to restrict and modify how things are displayed in your field. In this case, you could use the pre-made formatter NumberFormatter:
NumberFormatter formatter = new NumberFormatter(); //create the formatter
formatter.setAllowsInvalid(false); //must specify that invalid chars are not allowed
JFormattedTextField field = new JFormattedTextField(formatter); //pass the formatter to the field
This will also add a comma where ever needed (for example, when you type in 1000, it'll display it as 1,000.

Related

JFormattedTextField not returning correct text

I am trying to make a simple dialog box in Beanshell - it should read the contents of three editable text fields and, on button press, carry out a simple task accordingly. I am totally stumped by an error that I am getting where I cannot read the text in some of the fields.
Here’s the code:
// Set up the text fields
textField_Y= new JFormattedTextField();
textField_Y.setValue(150);
textField_Y.setColumns(4);
textField_Y.setEditable(true);
textField_X= new JFormattedTextField();
textField_X.setValue(0);
textField_X.setColumns(4);
textField_X.setEditable(true);
textField_n= new JFormattedTextField();
textField_n.setValue(20);
textField_n.setColumns(4);
textField_n.setEditable(true);
button = new JButton("Generate Stage Position List");
// some Code here to arrange the items within a GUI window
// Try to read the values
button.addActionListener(new ActionListener() {
actionPerformed(ActionEvent eText) {
//Get info from dialog
yShift = textField_Y.getText();
xShift = textField_X.getText();
nPos = Integer.parseInt(textField_n.getText());
print(xshift+" "+yshift+" "+nPos);
});
I run this and the dialog box displays correctly. I don’t change any values, just click the button, and it should print “150 0 20”. Instead it prints “void void 20”. I don’t have the faintest clue why one field is returning a correct number and the other two are returning void. They should all be identical! Can anyone help?
First, looking at this code...
button.addActionListener(new ActionListener() {
actionPerformed(ActionEvent eText) {
//Get info from dialog
yShift = textField_Y.getText();
xShift = textField_X.getText();
nPos = Integer.parseInt(textField_n.getText());
print(xshift+" "+yshift+" "+nPos);
});
yShift != yshift and xShift != xshift. Remember, Java is case sensitive.
I would also recommend making use of getValue instead of getText

EventListener Performed by case

I would like to know the best way to approach what I am trying to achieve, I can't figure out the logical path I should take.
I have a JTextField and a JTextButton, when input is added to the JTextField and either enter or the button is pressed, it will display on the JTextArea. Now, what I want is to choose when and what the JTextArea and Button do.
For example I want default Enter & Button to display next append text in my code. Then when a case is presented I want the JTextField to only accept either int or string and then once completed, I want it to go back to default.
I don't know if what I am trying to do is logical or best practice...
The idea behind this is, I have a story text based gui game. I want it to display text to the JTextArea and when Enter or button is pressed to display the next line of text and when in the story it requires user input, the JTextArea will look for that input.
So far I have an EventListener and ActionListener which submits what I type from JTextField to JTextArea, but that is about it.
Thanks for your assistance! I have solved my issue, not sure if this is the "Best Solution". I combined your solution with a bit of tweaking.
In this instance, buttonState is an int which can be changed throughout my code by calling a constructor "setButtonState". I could have made buttonState a static to make things easier, but thought I could keep things clean.
enterButton.addActionListener(new ActionListener()
{ //This is used so when the enter screen button is pressed, it will submit text from text field to text area.
public void actionPerformed(ActionEvent e) {
String text = inputTextField.getText();
InputTextFieldEvent event = new InputTextFieldEvent(this, text);
if (buttonState == 0) //Displays all text in JTextField to JTextArea, mostly for testing purposes.
{
if (textInputListener != null) {
textInputListener.setInputListenerOccurred(event);
}
}
if (buttonState == 1) //Only accepts string for answer
{
if (inputTextField.getText().matches("[a-zA-Z]+"))
{
textInputListener.setInputListenerOccurred(event);
}
else
{
getAppendMainTextArea("You have entered an invalid input, only letters are allowed.");
}
}
if (buttonState == 2) //Only accepts int for answer
{
if (inputTextField.getText().matches("[0-9]+"))
{
textInputListener.setInputListenerOccurred(event);
}
else
{
getAppendMainTextArea("You have entered an invalid input, only numbers are allowed.");
}
}
}
});

JTextField's real time formatting of user input

I would like to format the user input in real time, while they are typing.
For example, if I want the user to enter a date, I would like the text field to show in light gray the date format. The user would only be able to enter valid digits while he is typing.
If I need the user to enter a phone number, the format would be displayed in light gray in the text field and the user would only be able to enter valid digits...
A javascript example of this can be found here:
http://omarshammas.github.io/formancejs#dd_mm_yyyy
I looked at JFormattedTextField but it seems it doesn't prevent the user from typing wrong characters.
I am wondering how to do the same thing in Java as the javascript code linked above.
Any idea to help me get started or any lib already doing this?
Thanks in advance for any suggestion.
The KeyListener interface has three methods to be implemented: keyPressed, keyTyped and keyReleased. As each key is pressed you can do what you need to in this implemented listener. So for example, if the current key typed or the current contents of the text field is not to your approval, you can take the visual or logical action you need to take.
I don't like links generally, but here is a small tutorial on KeyListeners.
And here is an example to add a KeyListener to a JTextField:
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
public void keyTyped(KeyEvent e) {
// TODO: Do something for the keyTyped event
}
public void keyPressed(KeyEvent e) {
// TODO: Do something for the keyPressed event
}
});

Example text in JTextField

I am looking for a way to put example text into a swing JTextField and have it grayed out. The example text should then disappear as soon as any thing is entered into that text field. Some what similar to what stackoverflow does when a user is posting a question with the title field.
I would like it if it was already a extended implementation of JTextField so that I can just drop it in as a simple replacement. Anything from swingx would work. I guess if there is not an easy way to do this my option will probably be to override the paint method of JTextField do something that way maybe.
Thanks
The Text Prompt class provides the required functionality without using a custom JTextField.
It allows you to specify a prompt that is displayed when the text field is empty. As soon as you type text the prompt is removed.
The prompt is actually a JLabel so you can customize the font, style, colour, transparency etc..:
JTextField tf7 = new JTextField(10);
TextPrompt tp7 = new TextPrompt("First Name", tf7);
tp7.setForeground( Color.RED );
Some examples of customizing the look of the prompt:
If you can use external librairies, the Swing components from Jide software have what you are looking for; it's called LabeledTextField (javadoc) and it's part of the JIDE Common Layer (Open Source Project) - which is free. It's doing what mklhmnn suggested.
How about initialize the text field with default text and give it a focus listener such that when focus is gained, if the text .equals the default text, call selectAll() on the JTextField.
Rather than overriding, put a value in the field and add a KeyListener that would remove the value when a key stroke is registered. Maybe also have it change the foreground.
You could wrap this up into your own custom JTextField class that would take the default text in a constructor.
private JLabel l;
JPromptTextField(String prompt) {
l = new JLabel(prompt, SwingConstants.CENTER);
l.setForeground(Color.GRAY);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.getText().length() == 0) {
// Reshape the label if needed, then paint
final Rectangle mine = this.getBounds();
final Rectangle its = l.getBounds();
boolean resized = (mine.width != its.width) || (mine.height != its.height);
boolean moved = (mine.x != its.x) || (mine.y != its.y);
if (resized || moved)
l.setBounds(mine);
l.paint(g);
}
}
You can't do that with a plain text field, but you can put a disabled JLabel on top of the JTextField and hide it if the text field gets the focus.
Do it like this:
Define the string with the initial text you like and set up your TextField:
String initialText = "Enter your initial text here";
jTextField1.setText(initialText);
Add a Focus Listener to your TextField, which selects the entire contents of the TextField if it still has the initial value. Anything you may type in will replace the entire contents, since it is selected.
jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
if (jTextField1.getText().equals(initialText)) {
jTextField1.selectAll();
}
}
});

How do I use requestFocus in a Java JFrame GUI?

I am given an assignment but I am totally new to Java (I have been programming in C++ and Python for two years).
So we are doing GUI and basically we extended JFrame and added a couple fields.
Say we have a field named "Text 1" and "Text 2". When user presses enter with the cursor in Text 1, move the focus to Text 2. I tried to add
private JTextField textfield1() {
textfield1 = new JTextField();
textfield1.setPreferredSize(new Dimension(200, 20));
textfield1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
textfield1text = textfield1.getText().trim();
textfield1.setText(textfield1text);
System.out.println(textfield1text);
textfield1.requestFocus();
}
});
return textfield1;
}
But that doesn't work at all.
I noticed that requestFocus is not recommended, and instead one should use requestFocusWindows. But I tried that too. Upon some readings it seems like I have to do keyboard action and listener? But my teacher said it only requires 1 line...
Well, you have textfield1.requestFocus(), but your description would imply you need textfield2.requestFocus(). (that's 2).
Another option might be to use:
textField1.transferFocus();
This way you don't need to know the name of the next component on the form.

Categories