Grayed out textfield unless checkbox ticked - java

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

Related

In CodenameOne, why is a checkbox not selected but appearing selected?

I Have an odd problem - not sure if there's a coding mistake or a bug in CN1.
Basically I create a row of CheckBox objects and put them in a container that is X-Scrollable. If i click on one un-selected item and drag until the "elastic" effect pulls it back, it appears to be selected, but the code does not record it as selected.
Please see the following video of the issue:
https://youtu.be/EtputE1kjyo
Note that in the Console output, the word 'selected' is capitalized when the field has been selected and lowercase when it is unselected. Same for focus (I added focus to the output to determine if setFocusable() was working as desired so that focus was not to blame for the selection error).
here's the Checkbox creation code:
cb = new CheckBox(getCacheableImageMaxHeight(mod.getIconFile(),moduleImageHeight));
cb.setName(mod.getModuleID());
cb.setToggle(true);
cb.setUIID("ModuleButton");
cb.setFocusable(false);
cb.setScrollVisible(false);
cb.setTextPosition(Component.BOTTOM);
cb.setCloudDestinationProperty(cb.getName());
//actionlistener added for debugging only
final CheckBox cbFinal = cb;
final String modName = mod.getDisplayName();
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println(modName+", "+(cbFinal.isSelected()?"SELECTED":"selected") + ", " + (cbFinal.hasFocus()?"FOCUS":"focus"));
}
});
c.addComponent(cb);
UPDATE: I've realized there are two "states" at war here:
The toggleButtons (I now realize they're not just CheckBoxes since I set "setToggle(true)) are getting stuck in the "pressed" state as they are dragged and released with the "elastic" effect. Unfortunately, the "pressed" and "selected" states have the same appearance so that means my users think they have selected something when it's just stuck being "pressed" during a drag operation.
Here's some more debugging I did.
The first button is Pressed, but not selected (the bug).
the second button is Selected normally and not showing the bug.
The Third button is interesting because I selected it, then dragged and released it to get it to be SELECTED and PRESSED!
So the question changes to: Is there an open bug for this situation already (Pressed state gets stuck on after button is released) and if so, is there a fix coming or a workaround for now?
Just style the selected state to look different from the pressed state and it should work fine.
In a touch device selected state isn't rendered when the finger is up. This is almost always true unless you changed a flag in Display or set some arcane theme constant.
So I figured out a more effective workaround that doesn't involve adding a separate pressed style (since there could be buttons selected, pressed, and selected+pressed with the bug)
I needed to capture the event that scrolling stopped and then check the state of the buttons to make sure none were still pressed. To do this, I used addPointerReleasedListener on the scrolling container to detect when the pointer came off (so its components are definitely no longer pressed), and then in its Runnable, I make sure each one is released.
scrollingContainer.addPointerReleasedListener(evt -> {
Container cont = (Container) evt.getComponent();
Iterator<Component> buttons = cont.iterator();
while (buttons.hasNext()){
Button button = (Button) buttons.next();
if (button.getState() == Button.STATE_PRESSED) {
button.released();
}
}
});
So far seems to solve the problem. Now we just need a permanent fix, or a note in the documentation of ToggleButtons that when they are in a scrolling container, they could get stuck in a pressed state and need to be released.

How to add doneListener to TextArea in Codename One

TextField has a method called setDoneListener() which allows performing some action using the keyboard search, enter or Done button.
How do I implement the same for TextArea or is there a way to make Textfield multiple rows when typing? Instead of the single line text that scrolls left.
I know that putClientProperty("searchField", true);, putClientProperty("sendButton", true);and putClientProperty("goButton", true); would place a button on the keyboard, but how do I add action this button for TextArea?
Try this:
TextField multi = new TextField();
multi.setSingleLineTextArea(false);
multi.setRows(4);
multi.setColumns(20);
multi.setDoneListener(doneListener);
The JTextArea.setLineWrap(boolean wrap) method might be what you're looking for.
Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false, the lines will always be unwrapped. A PropertyChange event ("lineWrap") is fired when the policy is changed. By default this property is false.

How to select a JRadioButton from ButtonGroup?

I try to do an image creator program in java (with squares/circles/etc)
I have a few JRadioButtons in a ButtonGroup that symbolizes my program's "mode" (if I draw a circle, something else/if I move the objects).
When I click on different modes, the "mode" changes and I'm able to do what I want.
My problem is when I try to change the mode by double-clicking on an object. I do it in a MouseListener. I'm able to select the object, to change the "mode", but I can't change the selected JRadio Button on my ButtonGroup.
I searched for a while (since the setSelected() is not working). I know that ButtonGroup can have only a button selected at once. How could I deselect the curent one and select the one I need (the first one).
Thank you for any advices.
From the docs:
public void setSelected(boolean b)
Sets the state of the button. Note that this method does not trigger
an actionEvent. Call doClick to perform a programatic action change.
As mentioned here use:
radioBtn.doClick();
I created a small method that allow me to set any radio group button. Very convenient if you don't want to use if for any radio button.
public void setButtonGroup(int rdValue, Enumeration elements ){
while (elements.hasMoreElements()){
AbstractButton button = (AbstractButton)elements.nextElement();
if(Integer.parseInt(button.getActionCommand())==rdValue){
button.setSelected(true);
}
}
}
then
setButtonGroup(yourValue, yourButtonGroup.getElements());

How do I make a listener that fires when the USER selects an item in a JComboBox

I'm looking for a listener that fires ONLY when the user, the one who's using the program, selects an item in the JComboBox. I don't want to use ActionListener or ItemListener because those also fire when I select an item through the program. And I can't use MouseListener either because it only fires when I click the JComboBox, not when I select an item.
I was wondering what the easiest way to do this is? Currently, my solution is messy. When I change the selected item of the jcombobox through code, I set a flag to true. And in my action listener, it only executes if the flag is false.
A) I would recommend you to temporarily remove the listener when you perform the selection programatically.
B) If your programatic change is not an effect of another GUI event you could solve it the following ugly/non-robust/error-prone/"hacky" way: Check EventQueue.isEventDispatchThread() to find out if the click was triggered by the GUI thread (the user).
C) (Oops I just reread your question and saw that you've already discovered the method described below. Basically I would say that this (or the the method described above) is your best alternative.)
Another option is to have a boolean flag called something like nonUserSelection which you set to true before you select a value programatically and reset to false afterwards. In the action listener you simply add an
if (nonUserSelection)
return;

capturing input from JTextInput when user doesn't press Enter

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...

Categories