I'm building a Gui using net beans (Java) and my question is how to get the string in the text field to the variable without pressing the Enter key?
I wrote this code:
private void idTextBoxActionPerformed(java.awt.event.ActionEvent evt) {
this.Id = evt.getActionCommand();
}
The problem is that if I just enter the text and move to the next text field, the data doesn't go into the Id variable, if I press Enter everything OK.
Pressing Enter invokes an ActionEvent from that textfield which you listen for in your actionPerformed method and that is why your code only works in that scenario.
You could use a FocusListener to acheive what you want. You will want to listen for the focusLost event, which is when you move away from the textfield.
class foo implements FocusListener {
JTextField textField = new JTextField("A TextField");
textField.addFocusListener(this);
public void focusGained(FocusEvent e) {
// Do whatever you want
}
public void focusLost(FocusEvent e) {
// Save the text in the field to your id variable
}
}
EDIT
The following tutorial shows how to use a formatted textfield. You can ignore the formatting bit and focus on the propertyChangeListner aspect of it.
The idea is the same as my first example but using a different type of listener.
You could use the action event or focus event to track the changes at component level. But if its the text changes that you are interested in, then you should consider using a DocumentListener. Read the tutorial here
Related
so I am trying to verify what is typed into my text field is only numeric and not alphanumeric. I've looked into formatted textboxes, but haven't been able to implement them, due to lack of understanding the tutorial oracle has up on their site. I did some more searching and found the key listener class and it seemed like the best option.
So when I run the program and type into the text field instead of consuming the character event it just beeps at me. Here's the code:
private void buildPanel()
{
// Create a label to display instructions.
messageLabel = new JLabel("Enter a time in seconds the object has fallen");
// Create a text field 10 characters wide
fallingTextField = new JTextField(10);
// Add a keylistener to the text field
fallingTextField.addKeyListener(new TextFieldListener());
// Create a button with the caption "Calculate"
calcButton = new JButton("Calcualte");
// Add an action listener to the button
calcButton.addActionListener(new CalcButtonListener());
//Create a JPanel object and let the panel field reference it
panel = new JPanel();
// Add the label, text field, and button components to the panel
panel.add(messageLabel);
panel.add(fallingTextField);
panel.add(calcButton);
}
/**
The TextFieldListener class checks to see if a valid key input is typed into
the text field.
*/
private class TextFieldListener implements KeyListener
{
/**
The keyPressed method
#param evt is a key event that verifies a number is inputed otherwise
the event is consumed.
*/
public void keyPressed(KeyEvent evt)
{
char c = evt.getKeyChar();
if(Character.isAlphabetic(c))
{
getToolkit().beep();
evt.consume();
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent ev)
{
}
}
Here:
if(Character.isAlphabetic(c))
{
getToolkit().beep();
You tell your listener to beep every time you enter an alphabetic character. So it beeps when you do that.
Everything working exactly as the code implies it should.
For the other part of your question; check out the Javadoc for consume() (which is inherited from InputEvent).
Consumes this event so that it will not be processed in the default manner by the source which originated it.
You are not on the source side of things. The event has already been created, and dispatched to listeners. Calling consume() in your context ... simply doesn't do anything any more. It is more or less a "no op".
Again: you wrote code that waits for keyboard input, and when the input is alphabetic, it beeps. That is all that your code does. I assume if you provide a "/" for example ... nothing should happen. If you want to validate, then you need a "feedback" loop; for example your listener could overwrite the text field content when it detects bad input.
I think the problem is that the character has already been added by the time the event has been processed. You need to set the value of the field without the last character, like:
fallingTextField.setValue(fallingTextField.getValue().substring(0, fallingTextField.getValue().length - 1))
Alternatively, you can use the example at Oracle site and use a Mask input, like the following:
zipField = new JFormattedTextField(
createFormatter("#####"));
...
protected MaskFormatter createFormatter(String s) {
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(s);
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
return formatter;
}
I'm making a simple calculator, so far I did a text field where I can type numbers and it listens if key was typed from keyboard.
private void resultKeyTyped(java.awt.event.KeyEvent evt) { }
What I want is to click on let's say '1' with mouse and send a key event to this method, so it would be like I clicked it on keyboard. Tried doing keypress with robot but it says 'void type is no good here' or something like that. I wanted to just run that resultKeyTyped method from withing mouse click listener, like this:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt)
{
resultKeyTyped(KeyEvent.VK_1);
}
To call the resultKeyTyped, you have to pass a KeyEvent. You can just create a KeyEvent using appropriate constructor:
KeyEvent event = new KeyEvent(textField, 0, System.currentTimeMillis(), 0, KeyEvent.VK_1);
resultKeyTypes(event);
Although from your description (eg simple calculator), it sounds like you may wish to choose a different approach:
Add an ActionListener to the JButton
Within the implementation of the ActionListener, change the JTextField text by using the setText method
The best way to do this (assuming that you are clicking on a Button instead of something else) in my opinion would be this:
Button button1 = new Button("1");
button1.addActionListener(new ActionListener() {
int thisKey = KeyEvent.VK_1;
#Override
public void actionPerformed(ActionEvent e) {
resultKeyTyped(thisKey);
}
});
Now, the one thing that you need to change is that resultKeyTyped needs to take an int as a parameter instead of a keyevent. From what I understand, all that you care about is which key was pressed, not how long it was pressed or anything like that. So, wherever you call resultKeyTyped, pass it KeyEvent.getKey()
Hopefully this helped!
P.S. if you really want a keyevent, you can use the keyevent constructor, but since you were using a robot anyways, I am pretty sure that you only care about the key
I am trying to make a registration form and what i am trying to do is display a default text in text fields, simple meaning something like the below image.
What i am trying to do is , until the user enters data to a field for a example there is a field called "First Name". When the user selects the field "First Name" text disappears and the user can type their First Name.
IF the user doesn't type anything, the text should display again in the text field.
I tried using the focus listener, but i couldn't really get it to work because with my method even if the user types data to the field and go to the next field , the text of the previous field gets deleted and the default text gets displayed.
Here is what i have done :-
txtFirstName.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
txtFirstName.setText("");
}
public void focusLost(FocusEvent e) {
txtFirstName.setText("First Name");
}
});
Thank you for your time.
What i am trying to do is , until the user enters data to a field for
a example there is a field called "First Name". When the user selects
the field "First Name" text disappears and the user can type their
First Name. IF the user doesn't type anything, the text should display
again in the text field.
I think that you looking for prompt, see
Text Prompt by #camickr
another ideas how to create a prompt for JTextField
You have to implement an IF-clause to your focusLost and focusGained Listener. So do something like this:
public void focusLost(FocusEvent e) {
if(txtFirstName.getText().trim().equals(""))
txtFirstName.setText("First Name");
else
//do nothing
}
And for focusGained():
public void focusGained(FocusEvent e) {
if(txtFirstName.getText().trim().equals("First name"))
txtFirstName.setText("");
else
//do nothing
}
Or something like this ;)
I find that a useful way to draw attention to a jcombobox when one wants the user to select from it is to make it drop down at the point it gains focus usually when the previous item has been completed by the user.
How can this been done in Java?
You could do:
comboBox.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
comboBox.showPopup();
}
});
You want JComboBox#setPopupVisible
Add in a FocusListener to monitor for focus gained and you should be right.
Depending on if the combo box is editable or not, you may need to add a focus listener to the editor as well
rightclick on the combo box. go to events ---> mouse ----> mouseentered.
it will take you to :
private void jComboBox1MouseEntered(java.awt.event.MouseEvent evt) {}
inside the curly braces, type: jComboBox1.showPopup();
it should look like:
private void jComboBox1MouseEntered(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
jComboBox1.showPopup();
}
I have this code:
this.trigger = new Trigger();
this.presentationModel = new PresentationModel(this.personBean, this.trigger);
final ValueModel firstNameAdapter = presentationModel.getBufferedModel("firstName");
final JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
and
firstNameTextField.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
trigger.triggerCommit();
}
});
So when I push the enter button on the JTextField, I expect the value in my ValueModel class to be the same as the value in my JTextField. This doesn't happen unless I click outside the JTextField, then back inside the JTextField, and then push enter. If I just type in the text and hit enter, the ValueModel does not get the updated value. I am stuck on this problem, can anybody help?
BTW, I used this link for figuring out JGoodies in the first place: JGoodies Tutorial
I hope I am understanding your question correctly.
You need to get the text in the text field and set it in the ValueModel.
firstNameTextField.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
//this get the text from the text field
String firstName = firstNameTextField.getText();
//now write your code to set the firstname into the ValueModel
trigger.triggerCommit();
}
});
I looked through the JGoodies API (should have done this sooner) and found an unexpected static call, Bindings.commitImmediately()
If I call this method before my call to trigger.triggerCommit(), everything works as expected :)
Create a text field that commits on each key typed instead of when focus is lost:
BasicComponentFactory.createTextField(firstNameAdapter, false);
Also, you should consider architecting your program to not use buffered models. I find that they make things more complicated and tricky, and think I saw Karsten Lentzsch recommending not to use them as well in a mailing list.
The most useful way for me to learn JGoodies was to look at the tutorial code for the JGoodies binding and validation libraries.