Textfield loses focus when user clicks on checkbox (Java Swing) - java

So I'm using a JPasswordField to get the user input, and then give instantaneous feedback regarding the strength of the entered password. My problem is that if the user clicks on the 'hide' checkbox, the string in the textfield isn't immediately masked by '●', but works only when the textfield regains focus. I've tried to use component.getFocus within the mouseListener, but it doesn't seem to work.
Here's what this particular listener looks like:
inputT.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent hideClicked){
if (hideC.isSelected()){
inputT.setEchoChar('•');
inputT.requestFocus();
}
if (!hideC.isSelected()){
inputT.setEchoChar('\u0000');
inputT.requestFocus();
}
}
});

Show the feedback to the user in a different field than the password field that they are typing into. Ideally a separate read only component that is to the right of the password in your GUI. Your password strength feedback would then be updated by a listener on the password field, but the JPasswordField could then just work like normal.

From the JavaDoc: http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#requestFocus%28%29
public void requestFocus()
Requests that this Component gets the input focus. Refer to Component.requestFocus() for a complete description of this method.
Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow(). If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial.
Also, as MadProgrammer pointed out - your listener is on the JPasswordField instead of the JCheckBox.

Don't use mouse listener. For doing on selection, use ItemListener:
checkBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent evt) {
if(evt.getStateChange()==ItemEvent.SELECTED)
jPasswordField1.setEchoChar((char)0);
else jPasswordField1.setEchoChar('*');
}
});
Well, the above code works perfectly for me.

Start by attaching a ActionListener to the the checkbox, this means that user can click or press the space bar to activate the check box
In the actionPerformed method, check the state of the checkbox and the required changes.
Use JPasswordField#selectAll or JPassword#requestFocusInWindow (usually I do it the other way round ;)). If these do not work, you might even consider using JPassword#repaint to force the field to repaint

Related

Dynamic update of visual components in swing

I have a question regarding the possibility to dinamically update the visual side of a swing application.
I have created a small program, that works without any compile/logic errors and it does it's thing but it has a flaw. It does not automatically update when user clicks on something.
Let me explain the issue with the underneath picture
I tried adding a repaint and revalidate to anything. but it doesn't seem to work. they get ignored. Really, I added a repaint/revalidate method to EVERYTHING. Still nothing :)
I suggest adding the action event to the checkbox (I called it fullAutomaticCheckBox and the field txtField):
private void fullAutomaticCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
txtField.setEnabled(fullAutomaticCheckBox.isSelected());
}
To add the event listener:
fullAutomaticCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fullAutomaticCheckBoxActionPerformed(evt);
}
});
I want the text field to enable itself.
Then you add an ActionListener to the check box to enable/disable the text field depending on the state of the checkbox.
once user inputs a number it will repaint dynamically
If you want the screen to repaint, then you need to invoke the "update calculations" code dynamically. So you can add a DocumentListener to the text field. This will generate an event any time the user adds or removes text in the text field.
Read the section from the Swing tutorial on How to Write a DocumentListener for a basic example to get you started.

How to enable a button when text is entered in a text field in Netbeans

I'm very new at coding Java and Netbeans. So basically, I have a "save" button and three text fields, I want to enable the Button when these three text fields are edited and disable the button when one of them is empty. Also I'm wondering where I should put my codes. Since it's Netbeans I'm only familiar with ActionPerformed methods, there you can set an action when a button is pressed.
If you can keep it simple it would be appreciated!
public project() {
initComponents();
//Here I want the window to appear in the middle of the screen
setLocationRelativeTo(null);
if(txfField1.getText().equals("")){
btnSave.setEnabled(false);
}
else {
btnSave.setEnabled(true);
}
}
I tried with this code on only one of the three text fields and It does not work, the button is always enabled. The button is initially disabled. Additionally I have also tried to put my code below this method:
public class project extends javax.swing.JFrame {
You can use event handlers to change the state of the button. For example, if you have one text field and you want to change the state of the button depending on the data inside the text field, you could use something like
if (!jTextField1.getText().equals("")) {
jButton1.setEnabled(true);
} else {
jButton1.setEnabled(false);
}
and the event handler you can use
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
You can generate this automatically in Netbeans by going to the event tab when you have clicked on a component in the design view.
It seems in your example you have the right idea, however you need to update the button using events such as key pressing, key releasing etc
You can add it in onblur() method of those text boxes.
If it can, you can add a validation with an error message on click of save button, which might be more meaningful.

Menu mnemonic doesn't work [duplicate]

In SWT you can give any button a shortcut key simply by adding & in front of the letter in the button label. For example, if my button label is &Play, I can activate the button by hitting letter p on the keyboard.
In Swing, you can add a shortcut key using the mnemonic property. However, you need to hit alt+p to activate the button. This is really most appropriate for menu shortcuts. I want to activate the button with a letter press and no alt modifier.
I've seen this post on how to do it, but it seems absurdly complicated. Is there an easier way to do this?
http://linuxjavaprogrammer.blogspot.com/2008/01/java-swing-jbutton-keyboard-shortcuts.html
Update: After #camickr suggestion, I ended up using this code. I couldn't find any clear and simple example online, so hopefully this will help people out.
// play is a jButton but can be any component in the window
play.getInputMap(play.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0), "play");
play.getActionMap().put("play", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
playActionPerformed(e); // some function
}
});
Yes, Swing was designed to use Key Bindings. So instead of adding an ActionListener to the button you add an Action. Then that Action can be shared by the button or a menu item. You can also assign any number of KeyStrokes to invoke the Action by using the KeyBindings. The tutorial also has a section on Actions which explains why using an Action is beneficial.
JComponent has a registerKeyboardAction(...) method which basically does the InputMap/ActionMap bindings for you, but it also has to wrap the ActionListener in a wrapper Action so its preferrable for you to do you own bindings.
Further to camickr's answer, I am now using a little utility function like this:
public static void clickOnKey(
final AbstractButton button, String actionName, int key )
{
button.getInputMap( JButton.WHEN_IN_FOCUSED_WINDOW )
.put( KeyStroke.getKeyStroke( key, 0 ), actionName );
button.getActionMap().put( actionName, new AbstractAction()
{
#Override
public void actionPerformed( ActionEvent e )
{
button.doClick();
}
} );
}
Now to set the keyboard shortcut for a button I just do:
clickOnKey( playButton, "play", KeyEvent.VK_P );
I had a similar problem with a dynamically constructed (based on data input) form and just ended up attaching a keyListener action to the buttons. On form construction I parse the Component tree for the buttons and attach the listener. The listener than also parses the tree and matches the keypress with the appropriate button (via the text in the button), since I have no idea which one will have focus at any given time, and fires the button doClick... It's ugly, feels hackish, and has got to be a bit processor intensive, but it allows the flexibility I need for this particular dynamic form...

JButton: actionPerformed while invisible/disabled?

Is it possible that, for example, a JButton calls actionPerformed() of an ActionListener attached to it while the button itself is hidden or has been disabled?
Like, the user clicks the button, an event gets added to the Event Queue, and in a previous event the button gets disabled.
I'd think that this would not lead to an actionPerformed(), because the user merely submitted a click- or press-event that checks all this stuff in the current JFrame.
But does anybody know if there is any case where such an unwanted situation happens? Of course, always provided that you don't do anything with Swing objects outside of the EDT.
Edit for anyone looking at this: Yes, it can indeed happen under certain circumstances. I should post an example as an answer at some point.
From the JavaDocs
public void setEnabled(boolean enabled)
Sets whether or not this component is enabled. A component that is
enabled may respond to user input, while a component that is not
enabled cannot respond to user input. Some components may alter their
visual representation when they are disabled in order to provide
feedback to the user that they cannot take input.
For more info
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setEnabled%28boolean%29
INFO : JButton extends AbstractButton which extends JComponent
Just use a conditional statement and tell the app to enable jButton when the conditions are met.
For example:
private buttonNameActionPerformed(java.awt.evt evt){
if(condition.equals(something)){
jButton.setEnabled(true);
}
else{
jButton.setEnabled(false);
}
}

Shortcut key for jButton without using alt key

In SWT you can give any button a shortcut key simply by adding & in front of the letter in the button label. For example, if my button label is &Play, I can activate the button by hitting letter p on the keyboard.
In Swing, you can add a shortcut key using the mnemonic property. However, you need to hit alt+p to activate the button. This is really most appropriate for menu shortcuts. I want to activate the button with a letter press and no alt modifier.
I've seen this post on how to do it, but it seems absurdly complicated. Is there an easier way to do this?
http://linuxjavaprogrammer.blogspot.com/2008/01/java-swing-jbutton-keyboard-shortcuts.html
Update: After #camickr suggestion, I ended up using this code. I couldn't find any clear and simple example online, so hopefully this will help people out.
// play is a jButton but can be any component in the window
play.getInputMap(play.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0), "play");
play.getActionMap().put("play", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
playActionPerformed(e); // some function
}
});
Yes, Swing was designed to use Key Bindings. So instead of adding an ActionListener to the button you add an Action. Then that Action can be shared by the button or a menu item. You can also assign any number of KeyStrokes to invoke the Action by using the KeyBindings. The tutorial also has a section on Actions which explains why using an Action is beneficial.
JComponent has a registerKeyboardAction(...) method which basically does the InputMap/ActionMap bindings for you, but it also has to wrap the ActionListener in a wrapper Action so its preferrable for you to do you own bindings.
Further to camickr's answer, I am now using a little utility function like this:
public static void clickOnKey(
final AbstractButton button, String actionName, int key )
{
button.getInputMap( JButton.WHEN_IN_FOCUSED_WINDOW )
.put( KeyStroke.getKeyStroke( key, 0 ), actionName );
button.getActionMap().put( actionName, new AbstractAction()
{
#Override
public void actionPerformed( ActionEvent e )
{
button.doClick();
}
} );
}
Now to set the keyboard shortcut for a button I just do:
clickOnKey( playButton, "play", KeyEvent.VK_P );
I had a similar problem with a dynamically constructed (based on data input) form and just ended up attaching a keyListener action to the buttons. On form construction I parse the Component tree for the buttons and attach the listener. The listener than also parses the tree and matches the keypress with the appropriate button (via the text in the button), since I have no idea which one will have focus at any given time, and fires the button doClick... It's ugly, feels hackish, and has got to be a bit processor intensive, but it allows the flexibility I need for this particular dynamic form...

Categories

Resources