How to display a default message in JTextField java [duplicate] - java

This question already has answers here:
Java JTextField with input hint
(9 answers)
Adding a watermark to an empty JCombobox
(2 answers)
Closed 10 years ago.
I want to create a JTextField with a message inside as a deafult. But not as a proper text but as a comment about what to type inside the JTextField.
So if i type jtf.getText() it returns null or empty because it is just a comment that was printed there. When you click on it then it disappears and you can write whatever you want on it. Is there any method to do such a thing?

A possible technique is to first set the default string as the text of the textField:
JTextField myField = new JTextField("Default Text");
Then use a FocusListener, so that when the user put the focus in the element, the text disappears:
myField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
myField.setText("");
}
public void focusLost(FocusEvent e) {
// nothing
}
});
But you have to be careful: if the user never put the focus in the text field, getText() will return the default string. Therefore, you'd better manage a boolean that tells if the text field has ever had the focus.

I believe what you want is input hint in the text field, something like the image below:
Check xswingx library which can do this.

Would textFieldInstance.setToolTip help:
textFieldInstance.setToolTip("Tool tip for text field");

Related

How to listen what is written inside a JTextArea [duplicate]

This question already has answers here:
Java Swing: How to get TextArea value including the char just typed?
(3 answers)
Closed 2 years ago.
So I have a JTextArea where the user is supposed to put in a location as in town. He can put in the town but I need the String he enters to be saved for later. I don't know exactly what kind of listener to use and how to..
Usually when end users fill out some kind of a form (eg comprised of JTextAreas), to submit / save the data they usually push some button named "Submit" or "Save" etc..
So in this case the actual listener (ActionListener) is added to the button, which once clicked you retrieve your String(s) from the JTextArea(s).
Code example :
yourButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String aString = yourJTextArea.getText();
}
});
You need a DocumentListener
JTextArea area = new JTextArea();
area.getDocument().addDocumentListener(new DocumentListener() ......);

Java multiple message dialogs at the same time with focusLost event

The problem is that when i click on the surname field when the name field is empty both messages appear because the focus is lost even from surname when the message dialog appears. Is there anything i can do to make the program show the name message and the focus to stay on the name field?
I tried the .requestFocus() but it didn't work.
private void NameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (NameField.getText().equals('smth')) {
JOptionPane.showMessageDialog(null, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
private void SurnameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (SurnameField.getText().equals("smth")) {
JOptionPane.showMessageDialog(null, "Please put a surname!","Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
First off, in the NameFieldFocusLost event: if (NameField.getText().equals('smth')) { doesn't fly. The equals() method requires a String: if (NameField.getText().equals("smth")) { or better yet...since you want to ensure a name is actually provided:
if (NameField.getText().trim().equals("")) {
There must be something we're not being shown. I don't understand why both MessageBoxes would be displaying when focus is taken away from the nameFieldFocusLost event. This shouldn't happen unless you have code somewhere moving focus around especially before your form is actually visible. The requestFocus() method should work as well and should be called directly after you display the MessageBox, for example:
private void nameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (nameField.getText().trim().equals("")) {
JOptionPane.showMessageDialog(this, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
nameField.setText(""); // Clear the JTextField in case a white-space was placed there.
nameField.requestFocus(); // Force focus back onto the JTextField.
}
}
If you are moving focus to a JTextField before the parent container is visible (Form / JDialog) then you could possibly experience your particular problem.
EDIT:
Ahhh...I see the problem, thank you for the comment. Here are a few ways you can get around this dilemma:
Add a condition within the focusLost event for the next
JTextField to be in focus which will force an exit of that event
should the validation of the previously focused JTextField fail.
In your case you have a First Name text field and a Last Name text
field. In the focusLost event for the Last Name field you would have
the very first line of code being:
if (nameField.getText().trim().equals("")) { return; }
This way the remaining event code doesn't get run in the Surname
Lost Focus event unless validation for Name field is successful. The
entire Surname event code may look like this:
private void surnameFocusLost(java.awt.event.FocusEvent evt) {
if (nameField.getText().trim().equals("")) { return; }
if (surnameField.getText().trim().equals("")) {
JOptionPane.showMessageDialog(this, "Please put a last name!","Error!", JOptionPane.INFORMATION_MESSAGE);
surnameField.setText(""); // Clear the JTextField in case a white-space was placed there.
surnameField.requestFocus(); // Force focus back onto the JTextField.
}
}
An other way would be to utilize the InputVerifier
Class.
There is good example of its use in this SO
post.
Don't use the JTextField's Focus Events at all. If there is a button
that will be selected to further processing with the inputted data
then check the validation for all your JTextFields there (in the button's actionPerformed event) and force a
focus upon the field that fails (nameField.requestFocus();) for proper input.

Java Moving the Cursor in a JTextField

I have seen questions about moving a cursor using the Robot class by an x and y coordinate, but I am trying to figure out how to reposition a cursor among text in a JTextField.
I have an open parenthesis button that when clicked will take whatever text might be in the JTextField already, concat "(" to it and set this to the JTextField.
I was wondering how I might add the closing parenthesis as well, BUT put the cursor in between the 2 so the user can keep typing uninterrupted. Any suggestions?
If you want to move the Caret in a JTextField to a specific location from a button then one way to do this would be to set focus upon it first using the JTextField.requestFocus() method then you would need to use the JTextField.setCaretPosition() method to actually relocate the Caret.
If you have a JTextField named jTextField1 and you want to move the Caret to the end of the text contained within then you can use:
jTextField1.requestFocus(); //
jTextField1.setCaretPosition(jTextField1.getText().length());
You need to be careful not to exceed the length of text within the JTextField otherwise an IllegalArgumentException will occur which you can catch by surrounding the above code within a try/catch block. You will also need to consider those times when there might not be any text within the JTextField.
try {
jTextField1.requestFocus();
jTextField1.setCaretPosition(jTextField1.getText().length());
}
catch (IllegalArgumentException ex) {
///Do Something Here...
}
To Append Brackets to the end of a JTextField then place the Caret between them would be something like this:
String txt = jTextField1.getText(); // Get the text contained in Textfield (if any)
if (txt.equals("")) { txt+= "()"; } // Nothing for text so just add Parenthases
else { txt+= " ()"; } // Some text there so add a space and Parenthases
jTextField1.setText(txt);
try {
// Set focus to JTextField
jTextField1.requestFocus();
// Move the caret between the Parenthases
jTextField1.setCaretPosition(jTextField1.getText().length()-1);
}
catch (IllegalArgumentException ex) {
// Do something here...
}
I have an open parenthesis button that when clicked will take whatever text might be in the JTextField already, concat "(" to it and set this to the JTextField.
Don't use getText()/setText() to do this.
Instead you just want to "append" the new text to the text field.
So the logic in your ActonListener might be something like:
int end = textField.getDocument.getLength();
textField.setCaretPosition(end);
textfield.replaceSelection("()");
textField.setCaretPosition(end + 1);
Appending text is more efficient because you only generate a DocumentEvent for the added text.
If you use the getText()/setText() approach then you generate a DocumentEvent for the remove text and then a second event for the text added, which does not reflect what actually happened.
Also, using the length from the Document instead of getting the text is also more efficient since you don't need to actually create a String object.

Is there a listener for a cursor being put into JTextField?

Here is my application. It's a wallet to update my money when I spend or get profit. Look it up on image hosting here http://tinypic.com/r/687bdk/8
Is there a way to detect that a cursor has been put into one of the JTextFields? If there is, then could I dispatch a method that would delete whatever is in the other JTextField? There should only be one JTextField with input, it is unacceptable to have inputs in both text fields.
You can add a FocusListener to each textfield i.e.
JTextField myTextField = new JTextField();
myTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
//when selected...
}
#Override
public void focusLost(FocusEvent e) {
//when not selected..
}
});
Is there a way to detect that a cursor has been put into one of the JTextfields? If there is, than I could dispatch a method that would delete whatever is in the other JTextField.
As a user I'm not too crazy about that design. I've used accounting type applications before where you have two columns (debit/credit) and a number can only be entered into one.
In those applications the number is not removed on focus, it is removed if a value is entered in the other field. This allows for tabbing between fields on the forum without data disappearing just because focus changes.
To implement this type of functionality you would add a DocumentListener to the Document of the text field. Then whenever text is entered into the Document the listener is invoked and you can clear the text from the other text field.
Check out the section from the Swing tutorial on How to Write a DocumentListener for more information and examples.
It called: CaretListener
jTextArea=new JTextArea();
jTextArea.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent e){
//your code
}
}
);
It mainly used when you need to know that your caret position is changed.

How to add set of integers in a JTextArea

I have added set of integers to a JTextArea for each button click.
what exactly I want is that I want to add all the integers and display in a separate JTextArea,Also I want to ask whether we can access the value of a variable within an action listener outside the action listener.
Here is the code:
private ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals(t.getText()))
{
onec=one.calone(n);
td.append(Double.toString(onec));
td.append("\n");
}
res=Integer.parseInt(td.getText());
}
};
When the user presses button 't' It will keep on adding the integer 'onec' to
textarea 'td' using append method.And I have stored the result from the action
listener into a variable 'res' of double datatype.
private ActionListener listener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals(tot.getText()))
{
totd.setText(Double.toString(res));
}
}
};
When the user clicks the button 'tot',It should add all the integers in the
textarea 'td' and display it in the textarea 'totd'.
This code is not working.
Please help me this is the last part of my project.
As I don't know what is not working - it would of been good if you explained more clearly - my guess is...
Instead of Double.toString(onec)
Use String.valueOf(onec)
EDIT: If this is not the case, please elaborate on what your problem is, and a fuller code listing.
converting the contents of the textArea to double does not calculate sum. Try looping throught the first textArea reading each value while calculating the sum

Categories

Resources