I added a documentListener to a jTextArea, which should set a button disabled whenever the textArea is empty.
This works just at the starting point when the textArea is empty, but when I type something and then delete all the text until textArea.getText() == "", the button still doesn't turn disabled again.
This is what I wrote:
textArea.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
if (textArea.getText() == null) {
disableButton();
} else {
enableButton();
}
}
#Override
public void removeUpdate(DocumentEvent e) {
if (textArea.getText() == null) {
disableButton();
} else {
enableButton();
}
}
#Override
public void changedUpdate(DocumentEvent e) {
if (textArea.getText() == null) {
disableButton();
} else {
enableButton();
}
}
public void enableButton() {
clearModelMenuItem.setEnabled(true);
discardModel.setEnabled(true);
increaseFontSize.setEnabled(true);
decreaseFontSize.setEnabled(true);
incMenuItem.setEnabled(true);
decMenuItem.setEnabled(true);
}
What is the problem here?
Thanks for helping!
It's because you're not actually checking whether the text is empty; you're checking whether it's null. There's a difference between a String that's empty and a String that's null.
You need to be checking
if ("".equals(textArea.getText())) ...
if you want to check whether it's empty.
(You might also want to check for null.)
Related
So I searched Stackoverflow, but couldn't find any actual answer that I got. If there's already an answer to this question, please tell me.
I have a class with a showDescription method. This prints a string variable.
I require this method to be called whenever the "d" key is pressed, in the main method. So, what would the code be to implement the key press/down event?
Do this if you have a swing application:
f.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_D) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("woot!");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
you can read more here and here
If you have a console application then use:
Read Input until control+d
How can I detect the Windows key modifier for KeyEvent? I have add the code:
textField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if ((e.getKeyCode() & KeyEvent.VK_ESCAPE) == KeyEvent.VK_ESCAPE) {
textField.setText("");
}
}
});
But the problem is, when I use the Windows zoom and try to exit from it using Win + Escape, if focus is in TextField, its content clears. I've tried filter by e.getModifiersEx(), but it returns 0. The only way I've found is to detect whether Windows pressed or not, is to create boolean field and change it's value when Windows pressed/released.
So, is there any way to get the Windows key pressure state from KeyEvent for ESCAPE released event?
The way I used for myself:
AbstractAction escapeAction = AbstractAction() {
public void actionPerfomed(ActionEvent e) {
setText("");
}
}
textField.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
if (textField.getText() == null || textField.getText().isEmpty()) {
textField.getActionMap().remove("escape");
textField.getInputMap().remove(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
} else {
textField.getActionMap().put("escape", escapeAction);
textField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), escapeAction);
}
}
});
Hi I badly need some help I already search about Jtextfield to be filled before jbutton enables, DocumentListener most people use to determined if Jtextfield is being populated. I tried DocumentListener and it works but all I want is all Jtextfield must be not empty before the Jbutton enables here is my code.
Ftext.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
change();
}
#Override
public void removeUpdate(DocumentEvent e) {
change();
}
#Override
public void changedUpdate(DocumentEvent e) {
change();
}
private void change(){
if (Ftext.getText().equals("") && Mtext.getText().equals("") && Ltext.getText().equals("") && Addtext.getText().equals("")) {
SaveButton.setEnabled(false);
} else {
SaveButton.setEnabled(true);
}
}
});
if (Ftext.getText().equals("") && Mtext.getText().equals("") && Ltext.getText().equals("") && Addtext.getText().equals(""))
Means that all the fields must be empty. Some times you need to read this logic aloud...
"if field is empty AND field is empty AND field is empty..."
If you used || (or) instead, it would mean that if any one of the fields was empty the statement would be true for example...
if (Ftext.getText().equals("") ||
Mtext.getText().equals("") ||
Ltext.getText().equals("") ||
Addtext.getText().equals("")) {...
You should also consider using .getText().isEmpty() or .getText().trim().isEmpty() if the fields shouldn't contain just spaces.
You might also consider writing a single DocumentListener implementation instead of creating a new anonymous class for each field
public class FieldValidationHandler implements DocumentListener() {
private List<JTextField> monitorFields;
public FieldValidationHandler(JTextField... fields) {
monitorFields = Arrays.asList(fields);
for (JTextField field : monitorFields) {
field.getDocument().addDocumentListener(this);
}
}
#Override
public void insertUpdate(DocumentEvent e) {
change();
}
#Override
public void removeUpdate(DocumentEvent e) {
change();
}
#Override
public void changedUpdate(DocumentEvent e) {
change();
}
private void change(){
boolean enabled = true;
for (JTextField field : monitorFields) {
if (field.getText().trim().isEmpty()) {
enabled = false;
break;
}
}
SaveButton.setEnabled(enabled);
}
}
Then you'd just create a single instance...
FieldValidationHandler handler = new FieldValidationHandler(Ftext, Mtext, Ltext, Addtext);
Now, this approach is a little sneaky, in that it adds the DocumentListener to the fields you specify via the constructor automatically.
Another approach might be to have some kind "Validation" controller, that you would pass to this handler and it would call some kind of "validate" method when change was called.
This would separate the listener from the fields, but this is all a matter of context at the time.
I would personally have a "register" and "unregister" process which would allow you to add or remove fields as you need to
I am making a swing MVC application , to know the intricacies of GUI design using the Swing Framework . My JDK Version is 7 and I have a simple application that contains a dialog having a textfield for storing the path to a file , a browse button , 2 textfields for user id and password and 2 buttons for Update and Cancel functionalities.
Clicking on these buttons simply shows a dialog with either Update or Cancel message on it.
I planned to use DocumentListener to validate the textfield components.
In the UI i have the following code to create the 2 textfields :
public JPasswordField getMyPasswordField() {
if(myPasswordField == null)
{
myPasswordField = new JPasswordField();
myPasswordField.setBounds(133, 93, 163, 21);
myPasswordField.getDocument().putProperty("Owner", "myPasswordField");
}
return myPasswordField;
}
public JTextField getMyUserNameField() {
if(myUserNameField== null)
{
myUserNameField = new JTextField();
myUserNameField.setBounds(133, 66, 163, 21);
myUserNameField.getDocument().putProperty("Owner", "myUserNameField");
}
return myUserNameField;
}
In the controller I used the following code :
myReferenceUI.getMyUserNameField().getDocument().addDocumentListener(this);
myReferenceUI.getMyPasswordField().getDocument().addDocumentListener(this);
And in the method implementation I wrote the following :
public void insertUpdate(DocumentEvent e) {
Object owner = e.getDocument().getProperty("Owner");
changed(owner);
}
#Override
public void removeUpdate(DocumentEvent e) {
Object owner =e.getDocument().getProperty("Owner");
changed(owner);
}
#Override
public void changedUpdate(DocumentEvent e) {
Object owner =e.getDocument().getProperty("Owner");
changed(owner);
}
public void changed(Object e)
{
System.out.println(e.toString());
if( e.toString().equals("myUserNameField"))
{
if(myReferenceUI.getMyUserNameField().getText().equals("") )
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
return ;
}
}
if( e.toString().equals("myPasswordField"))
{
if(myReferenceUI.getMyPasswordField().getText().equals("") )
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
return ;
}
}
myReferenceUI.getMyUpdateButton().setEnabled(true);
}
My intent was to enable the update button only if the 2 textboxes for username and password have non null values.
The listener events fire properly and the update button is disabled in case of null entry in the username / password fields.
But after entering any value in these fields , if i press backspace and erase the text , the update button remains disabled.
What can i do to get rid of this condition ?
Use a DocumentListener that is aware of both the documents that you want to follow. For example:
private static class PasswordValidator implements DocumentListener {
private final Document[] documents;
private final JComponent component;
PasswordValidator(JComponent component, Document... docs) {
this.component = component;
documents = docs;
for (Document doc : docs) {
doc.addDocumentListener(this);
}
validate();
}
#Override
public void insertUpdate(DocumentEvent e) {
validate();
}
#Override
public void removeUpdate(DocumentEvent e) {
if (e.getDocument().getLength() == 0) {
component.setEnabled(false);
}
}
#Override
public void changedUpdate(DocumentEvent e) {
// Attribute change - ignore
}
private void validate() {
for (Document doc : documents) {
if (doc.getLength() == 0) {
component.setEnabled(false);
return;
}
}
component.setEnabled(true);
}
}
That particular implementation would then be used something like:
new PasswordValidator(myReferenceUI.getMyUpdateButton(), myReferenceUI.getMyUserNameField().getDocument(), myReferenceUI.getMyPasswordField().getDocument());
I got around my troubles by attaching PropertyChangedListeners to both my username and password fields and the following bit of code :
public void setUpdateButtonState()
{
if((myReferenceUI.getMyUserNameField().getText().equalsIgnoreCase("")
|| String.valueOf(myReferenceUI.getMyPasswordField().getPassword())
.equalsIgnoreCase("") ))
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
}
else
{
myReferenceUI.getMyUpdateButton().setEnabled(true);
}
I have the ListSelectionListener which tells me when the cell is selected with the mouse.
JGrid grid = new JGrid();
grid.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
grid.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(final ListSelectionEvent e) {
e.getFirstIndex();
e.getLastIndex()
}
}
I want to select the sell only when the button shift is hold. How can i do it?
I need it for the multiple selection. When the user holds shift and clicks the cells it gives me getFirstIndex() and getLastIndex().
Add a KeyListener similar to this to your JGrid, assuming JGrids takes keyListeners
boolean shiftIsDown = false;
yourJGrid.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode == e.VK_SHIFT) shiftIsDown = true;
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode == e.VK_SHIFT &&
shiftIsDown == true) shiftIsDown = false;
}
public void keyTyped(KeyEvent e)
{
// nothing
}
});
Now when you get a valueChanged() event, just check to see if your boolean "shiftIsDown" value is true, and if so you can do your selection.