In my Swing app, I have a screen that has a bunch of JTextFields. Each JTextField uses an ActionListener's actionPerformed method to copy the user-entered text to my data model object.
This method seems to only be called if the user presses Enter. How can I copy the user-entered text to my data model object if the user doesn't press Enter but instead 1) tabs between fields or 2) uses the mouse to click from one field to the next?
If you only want to perform an action when the user moves away from the field (not on every character changing in the field) then listen to the focus events:
JTextField textField = ...
textField.addFocusListener(new FocusAdapter(){ void focusLost(FocusEvent e)
{ doSomething(); } );
You might want to take a look at JFormattedTextField which handles this kind of thing for you.
muJTextField.addFocusListener(/* focus listener here */); for focus changes
myJTextField.getDocument().addDocumentListener(/* document listener here */); for document changes
For document changes use changeUpdate()
the problem with mouseclick, is that the component you click on must grab focus, else focus lost will not be called...
i had the same problem, so i used a timer to commit my code, every x milliseconds...if you sure that focus lost will be called when you click on some other component, a simple focus listener will do the trick...
Related
I'm writing a program using JavaFX and I currently have three TextFields. When you press enter while any of the text fields are focused, there is an EventHandler which calls the appropriate method for each field. There is no submit button because I want it to submit each input separately (that's just how I made the rest of the program) to be validated and return a String containing any errors in the input. If the users input is invalid, it resets it to the last valid value it had.
However, when testing I found that sometimes I just click somewhere else (such as the next field) rather than pressing enter, so I wanted to implement the same function as pressing enter but when the user clicks outside the field. There is a MouseClicked event on the root that I have attempted to make it submit the input for all of the fields at once which works, but if any field has not been filled in, then it will be unsuccessful and return an error message (which might confuse a user).
Additionally, if the user clicks inside the TextField again, say to delete something from the middle of the word, the event will be triggered and the field will be reset to the last valid value if the current input was invalid.
I've considered using a MouseExited event on each field, but I think that might be triggered by the cursor leaving the field, rather than a click outside of the field.
What would be a good way of doing this, while minimising the number of event methods in my program?
I have two JFrame forms that accept information such as Name,Rollno,Enrollment Number,gender,etc.Name and gender are on first JFrame form while the other details are on the second JFrame form.All the information gets stored in MySql Database after clicking 'next form' button.The same button takes the user to the next form.If the user fills all the details in the first form and clicks the 'next form' button of the form and he/she exits the second form,only half the database will be having the details and the other half will have nothing.
So, please suggest me such code that when the user clicks the close(X) button of the second form, all the details saved in the Database get deleted.
(Forms are entirely coded in NetBeans)
Please help me out.
The best way to solve this method is to not save anything into the database until the user completes all forms (ie. cache the information from the first form and save it once all once the user completes all the data).
Option number 2 would be to delete the data when the X button is clicked, however this isn't the best since the application can be force closed or such, case in which you can't perform any action. Anyways, here's how to detect the X button being clicked.
First you want to disable automatic exiting:
// You probably have EXIT_ON_CLOSE instead of this somewhere in your code already, just replace with this
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Then you want to handle the close event yourself:
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// In here you can delete any data in the database or even use JOptionPane to confirm the exit
// To close the frame once everything is done, do this:
frame.dispose();
}
});
Note: You can use System.exit(0) instead of frame.dispose() to ensure that everything is terminated right away.
How, using JTextField, can I create my program to enable/disable a textfield depending on whether or not a checkbox is ticked?
I have an option which, if checked, needs to take input. If not checked, I'd like the text field to remain grayed out with the user unable to enter text.
mchq08 did not give a complete answer since his code will do nothing if the JCheckBox is unchecked. You don't need the if block as all you'd need is a single line of code in your item listener
checkBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent){
// the line below is the line that matters, that enables/disables the text field
textField.setEnabled(itemEvent.getStateChange() == ItemEvent.SELECTED);
}
});
You can do that task with the check box with a simple if/else statement within an event listener.
You would want to put this into an event Listener for the check Box so when the event is fired it will allow it to editable. You could also go a step more and create another if/else if the check box is false and delete the text within the text box and set it to editable.
if(checkBox.isEnabled()){
textBox.setEditable(true);
}
Link CheckBox
Link TextBox
We currently have a focus problem with a JTable/JTextEditor in java swing. The JTable has a custom cell editor which is a JTextField.
The issue is when a cell is being edited and contains invalid data, and the user clicks on a JButton, the text field will stop editing and the JButton actionPerformed (clicked) is called. The JTable#setValueAt handles validation so if the data in the JTextField is invalid, the underlying TableModel is not updated.
Ideally, we do not want to let the JButton click occur. Focus should remain with the JTable or the JTextField.
Clicking the button will perform a submit action and close the frame the table is in. As the validation in the TableModel#setValueAt does not update the value, it submits the old value.
Can this be done? I am still fairly new to Swing so I am not aware what to check.
Unfortunately, our code is not straight forward. The UI is constructed from XML in such a way that the button knows nothing about anything else on a form (this is code I have inherited).
In .net you could stop a control losing focus by handling a Validating event and setting a cancel flag. Is there a similar mechanism with Java.
Validating the input after editing has concluded, in setValueAt(), may be inconveniently late. The editor itself can preclude navigation for invalid values, as shown in this example that links to the corresponding tutorial section.
For valid values, you can make the table commit when losing focus:
table.putClientProperty("terminateEditOnFocusLost", true);
Can you try using inputverifier on the editor component, i.e. text field?
When the focus is lost from a component, the lost focus method is called (more reference in http://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html). Therefore, you may call the validation method when you lose the focus.
If you do not need to be aware of the specific field being edited, you can also perform validation inside your button and prevent the submission if it is not sucessful.
I'd achieved a similar functionality by overriding the stopCellEditing method in my JTable's CellEditor.
#Override
public boolean stopCellEditing() {
String s = (String) getCellEditorValue();
if (s != null) {
if (!testYourValue()) {
Toolkit.getDefaultToolkit().beep();
return false;
}
}
return super.stopCellEditing();
}
So as you may know, if you have a text field and you add an ActionListener to it, it will only listen to the keypress of the enter button. However, I want to let my ActionListener listen to changes in text of the . So basically I've got this:
public static JPanel mainPanel() {
JPanel mainp = new JPanel();
JTextArea areap = new JTextArea("Some text in the textarea");
JTextField fieldp = new JTextField("Edit this");
areap.setEditable(false);
fieldp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(//change in textfield, for instance a letterpress or space bar)
{
//Do this
}
}
});
mainp.add(areap);
mainp.add(fieldp);
return mainp;
}
Any way I can listen to changes in text (like documented in the actionPerformed event)?
From an answer by #JRL
Use the underlying document:
myTextField.getDocument().addDocumentListener();
Yeah, but what is a document listener and how do you use it? You're not really answering the question.
I have a JTextField in my app's user interface. When the user makes any change to it, I want a nearby JCheckBox to be checked. The purpose is to tell the app to USE the value that was entered. Users often enter a value there but if they don't explicitly tell the app to use it then the app continues to ignore it. Instead of "training" users I'm supposed to follow the principle of least astonishment and automatically check the "Use this value" box.
But how do I listen for a change? Can't you guys just tell me the easy way, instead of "educating me" about document listeners?
Documents are the mechanisms java swing uses to store the text inside of a JTextField. DocumentListeners are objects that implement the DocumentListener interface and thus make it possible for you to list to changes in the document, i.e. changes in the text of the JTextField.
To use the document and documentlistener capabilities, as suggested above extend your class (probably but not necessarily a JFrame) so that it implements the DocumentListener interface. Implement all the methods for the interface (most likely your java ide can do that semi-automatically for you. FYI, the DocumentListener interface has three methods, one for inserting characters (into the text field), one for removing characters, and one for changing attributes. You are going to want to implement the first two as they are called when characters are added (the first one) or deleted (the second one). To get the changed text, you can either ask the document for the text, or more simply call myTextField.getText().
C'est tout!
Phil Troy