How to change selected value of a JComboBox - java

I have to two comboboxes, based on the selection made in the first combobox the selected value of the second box should change.
Please find the code snippet below:
secondcombobox.setSelectedItem(firstcombobox.getSelectedItem());

You should use an ActionListener:
firstcombobox.addActionListener(new ActionListener(){
void actionPerformed(ActionEvent e){
// sets the selected item of secondcombobox to be the value of firstcombobox
// assuming secondcombobox contains such a value.
secondcombobox.setSelectedItem(firstcombobox.getSelecteditem());
}
});
Note scoping here is important. You can either make firstcombobox and secondcombobox global or final, or you can use a slightly alternate form where you take those arguments as inputs to a constructor:
firstcombobox.addActionListener(new ActionListener(firstcombobox, secondcombobox){
private JComboBox a;
private JComboBox b;
public ActionListner(JComboBox a, JComboBox b){
this.a = a;
this.b = b;
}
void actionPerformed(ActionEvent e){
// sets the selected item of a to be the value of b
// assuming a contains such a value.
b.setSelectedItem(a.getSelecteditem());
}
});

Your code above will only work if the selected item in the first JComboBox also exists in the second JComboBox; In other words there exists an object in the second ComboBoxModel returns true when compared to the selected item from the first JComboBox.
If the selected item is not in the list, the method call will have no effect, which is suspect is what's happening in your case.

If your two comboboxes share the same values, you should use the same model for them both. It would be cleaner than to use an ActionListener.
DefaultComboBoxModel model = new DefaultComboBoxModel();
combo1.setModel(model);
combo2.setModel(model);
//init your values in the combo here
Then, when you select an item in one of the comboBoxes, it will be selected in the other.

Although your minimal question length makes your question cryptical, you will probably need:
firstcombobox.addActionListener() {
// Do something with secondcombobox
}

Related

ComboBox not showing bound values

I have a comboBox cb and an ObservableList<StringProperty> data
I have bound the cb's Items to data as follows:
Bindings.bindContent(cb.getItems(), data);
Suppose data has the following items: str1, str2, str3, str4
When I change data, the combobox gets the new list without any problem.
But if str3 is selected in cb and I change the value of str3 to NewStr3 in data, that change is not getting displayed in cb. And sometimes the list displayed is also wrong (it shows str3 instead of NewStr3) eventhough underlying data it refers is correct.
How can I force combobox to display new values when the underlying model is changed?
The selected item in a combo box is not required to be an element of the combo box's items list. (For example, in an editable combo box, you can type in an item which is not in the list.) If you think about your example from this perspective, it's no surprise that it behaves as you describe.
If you want to force the selected value to be an element of the underlying list when that list may change, you need to define how the selected item should change if the list changes in a way in which it no longer contains the selected item (it is not obvious how you will do this, and probably depends on your application logic). Once you know what you want to do, you can implement it with a ListChangeListener:
cb.getItems().addListener((ListChangeListener.Change change) -> {
String newSelectedItem = ... ; // figure item that should be selected instead
cb.setValue(newSelectedItem);
});
The simplest implementation would be just cb.setValue(null);, which would mean no item was selected if the list changed so that it no longer contained the currently selected item.
Oops ... mis-read the comboBox for a choiceBox - while the basics of this answer apply to both combo- and choiceBox, I don't have a custom ComboBoxX - yet :-)
Basically, it's the responsibility of the SelectionModel to update itself on changes to the items. The intended behaviour implemented in core is to completely clear the selection - that is, null the selectedItem and set selectedIndex to -1 - if the old item was the selectedItem and is replaced or removed. The typical solution for custom behaviour is to implement a custom selection model and set it:
/**
* A SelectionModel that updates the selectedItem if it is contained in
* the data list and was replaced/updated.
*
* #author Jeanette Winzenburg, Berlin
*/
public static class MySelectionModel<T> extends ChoiceBoxSelectionModel<T> {
public MySelectionModel(ChoiceBoxX<T> cb) {
super(cb);
}
#Override
protected void itemsChanged(Change<? extends T> c) {
// selection is in list
if (getSelectedIndex() != -1) {
while (c.next()) {
if (c.wasReplaced() || c.wasUpdated()) {
if (getSelectedIndex() >= c.getFrom()
&& getSelectedIndex() < c.getTo()) {
setSelectedItem(getModelItem(getSelectedIndex()));
return;
}
}
}
}
// super expects a clean change
c.reset();
super.itemsChanged(c);
}
}
// usage
myChoiceBox.setSelectionModel(new MySelectionModel(myChoiceBox));
Unfortunately, core choiceBox doesn't play by the rule - it severely interferes with model's responsibilities (probably because the model implementation doesn't stand up to its duties) which requires a complete re-write of the whole collaborator-stack (choiceBox, -skin, copied -behaviour) such as ChoiceBoxX - which I did just to learn a bit, try remove some of its smells and fix some bugs.

Making a label editable depending on a variable in an array

I am making a registration page but I am fairly new to Java, I have a combo box for peoples Titles such as "Mr, Mrs, Miss, etc" one of the options is "Other..." And I have a text field next to the combo box to specify your title, I would like the text field to not be editable unless someone selects "Other..." in the combo box, How would I do this?
What it looks like at the moment:
I can't see what I'm doing wrong?
TitleSpecifyChoiceField.setEditable(false);
TitleSpecifyChoiceField.setText("Please specify title...");
TitleChoice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mr", "Mrs", "Miss", "Ms", "Dr", "Other..." }));
TitleChoice.setToolTipText("");
TitleChoice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (TitleChoice.getSelectedItem().equals("Other...")){
TitleSpecifyChoiceField.setEditable(true);
};
You would do this the same way you'd respond to any changes in a JComboBox -- by adding a listener to the JComboBox as per the Swing combo box tutorial. Inside the listener, change the setEnabled(...) setting on the JTextField depending on the selected item. i.e., by calling getSelectedItem() on the JComboBox and testing whether calling equalsIgnoreCase("other") is true.
Note that I recommend that you use setEnabled(...) not setEditable(...) as the former will give the user visual cues as to whether the JTextField should be edited or not.
Edit
Regarding your code:
TitleSpecifyChoiceField.setEditable(false);
TitleSpecifyChoiceField.setText("Please specify title...");
TitleChoice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mr", "Mrs", "Miss", "Ms", "Dr", "Other..." }));
TitleChoice.setToolTipText("");
TitleChoice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (TitleChoice.getSelectedItem().equals("Other...")){
TitleSpecifyChoiceField.setEditable(true);
}
}
});
Some problems and issues:
Does your JComboBox use Strings or does it hold other types of items?
You will want to add debugging code into your code to try to isolate the problem. For instance, inside of your ItemListener, add a System.out.println(...) to print out the selected item to be sure that the listener is working as expected.
You are checking if the item .equals("Other..."), a String literal. Instead consider making a String constant, OTHER that the JComboBox uses and that you test in the listener to be sure that the tested String and and the displayed are the same.
Again, I suggest you use setEnabled(...) not setEditable(...).
You should learn and follow Java naming conventions including beginning all variable names with lower case letter as this will help us to better understand your code.
You should fix your posted code indentation so that it is regular and makes sense (note my code above vs yours). Why do you want to make it harder for folks who are trying to help you to understand your code? Your job is to make ours as easy as possible as we're all volunteers.
Create and post an sscce to get the best and fastest help.
Add a listener to the combo box. When the selected item changes, call setEditable() on the text field.
You could try adding an ItemListener to your JComboBox and (as #HovercraftFullOfEels suggested) use setEnabled as opposed to setEditable. For a general idea, you could do something like this:
JTextField textField = ...;
JComboBox<String> comboBox = ...;
comboBox.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
final String selected = (String)comboBox.getSelectedItem();
textField.setEnabled(selected.equals("other"));
}
}
);
Or if you are using Java 8 you could use this:
JTextField textField = ...;
JComboBox<String> comboBox = ...;
comboBox.addItemListener(
e -> {
final String selected = (String)comboBox.getSelectedItem();
textField.setEnabled(selected.equals("other"));
}
);

JText string input, then display output to JList

I am pretty new in Java programming, I have been trying to solve this simple program
it reads user input, then the ADD button will simply display the typed string on the JList.
The remove button will simply remove the desired item in the JList.
I am quite confused how to put the action listener thing in the code, or get text whatever
it is. I'd really appreciate if you can help me solve this simple GUI.
It reads user input in JText (String) and when I click the add button (maybe action performed?) the String will be basically populated in JList. and the Remove button will
simply remove the selected String in JList.
Step 1
Bind the code to the specific event, using the addActionListener method.
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
// Bind the method to the button.
}
});
Step 2
Populate that method with the relevant code.
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list model that informs the JList.
Altogether
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list.
}
});
Useful Links
Here is a very good tutorial from Oracle detailing how to manipulate lists a million and one different ways.

How to insert items to a jcombobox at runtime and save it

I need to save the values in my jcombobox at the runtime. What I am trying to do is after clicking on a button, I am setting it to editable = true. Then type the value in the combobox, but it doesn't save.
private void btadbknameActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()== btadbkname){
cb_bkname.setEditable(true);
cb_bkname.getText();
cb_bkname.addItem(evt);
}else{
cb_bkname.setEditable(false);
}
}
I have already added some elements in it on the designing level, but it's limited if some random value comes then its a problem.
Because it is possible to add / remove Item(s) to / from the DefaultComboBoxModel underlaying the JComboBox, the same action (by default) is possible from outside.
You have to use MutableComboBoxMode to add / remove Item(s) to / from JComboBox that fires event from itself (view_to_model).
There are excellent examples of MutableComboBoxModel by #Robin here and here.
For better help sooner post an SSCCE, for future readers, otherwise search for extends AbstractListModel implements MutableComboBoxModel.
it can't possibly work the way you're trying it.
the comboBox has to be editable before you click the button then you just need this line
cb_bkname.addItem(((JTextField)cb_bkname.getEditor().getEditorComponent()).getText());
Try this
private void btadbknameActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()== btadbkname){
cb_bkname.setEditable(true);
String newItem=cb_bkname.getText();
cb_bkname.addItem(newItem);
}else{
cb_bkname.setEditable(false);
}
}

Removing all Items from a combo box in Java

I need to remove all items from the combo box
int itemCount = combo.getItemCount();
for(int i = 0; i < itemCount; i++){
combo.removeItemAt(0);
}
This code will remove all items except the last one. It gives a NullPointerException.
How to fix that?
The code in the question would normally work. However, it looks like a threading issue. Another thread may be messing with the items.
However, I sugeest you should better use the removeAllItems(); method:
combo.removeAllItems();
How about JComboBox.removeAllItems()?
You can use
this.combo.removeAllItems();
to remove all the items in JComboBox.
In second line:
combo.removeItemAt(0);
I think instead of 0 it should be i.
do it in reverse order as:
for(int i=combo.getItemCount()-1;i>=0;i--){
combo.removeItemAt(i);
}
But in my case combo.removeAllItems() works fine
use .removeAllItems() methods to remove all items from combo box.
The assumption that it is related to another thread is not always true. It can be the thread itself causing the issue.
This exception may happen because an event is triggered when a combo item is removed and in this event handling method you still refer to combobox items.
For example when you delete somewhere (other than in actionPeformed()) in your code the last item from a combo box with combo.removeItemAt(0) or removeAllItems() then still the event actionPerformed will be fired/executed. But very often the actionPerformed() method contains code to react on user actions (user clicked somewhere on the combobox). So, when the last item has been deleted there is no more item in the combobox and any reference to an item or index in actionPerformed() will cause an exception.
The solution to this is to move the code from actionPerformed() to e.g. mouseClicked() or another event handler depending on what you want to do.
removeAllItems() it does remove all things but after the add data to the combo box it will not show there ,the nullPointException will shows
Use this to remove all the elements from the combo box :
DefaultComboBoxModel model = (DefaultComboBoxModel) ComboBox.getModel();
model.removeAllElements();
Usually it happens because you have an event associated JComboBox. It is solved if you have control item in the JComboBox to act, for example:
jComboBoxExample.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
do_run ();
}
});
public void do_run() {
int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION
if (n> 0) {
String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString ();
}
}

Categories