Dynamic Jcomboboxes

Dynamic JComboBoxes

Yes, simply create a DefaultComboBoxModel for each set, and do setModel() on JComboBox2 when JComboBox1 changes.

Addendum: For example,

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ComboTest extends JPanel implements ActionListener, Runnable {

private final JComboBox combo1 = new JComboBox(
new String[]{"Course 1", "Course 2", "Course 3"});
private final JComboBox combo2 = new JComboBox();
private ComboBoxModel[] models = new ComboBoxModel[3];

public ComboTest() {
models[0] = new DefaultComboBoxModel(
new String[]{"A1", "A2"});
models[1] = new DefaultComboBoxModel(
new String[]{"B1", "B2", "B3", "B4"});
models[2] = new DefaultComboBoxModel(
new String[]{"C1", "C2"});

combo2.setModel(models[0]);
this.add(combo1);
this.add(combo2);
combo1.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
int i = combo1.getSelectedIndex();
combo2.setModel(models[i]);
}

@Override
public void run() {
JFrame f = new JFrame("ComboTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new ComboTest());
}
}

Java Swing dynamic JComboBox

DefaultComboBoxModel model = new DefaultComboBoxModel(yourstringarray);
item_combobox.setModel( model );

n ma problem get solved....

Dynamic JComboBox Size

The following code seems to work

Not really because you change the size of the combo box which would cause the combo box to overwrite any component display on the right of it. Also, the combo box arrow is drawn in the middle of the combo box.

Check out Combo Box Popup. This solution also uses a PopupMenuListener (so you were on the right track) but it only increases the width of the popup when it is displayed, not the combo box as well.

Dynamically adding items to a JComboBox

How about using ComboBoxModel? Something like this....

    JFrame frame = new JFrame("Combo Box Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLayout(new FlowLayout());

Vector comboBoxItems=new Vector();
comboBoxItems.add("A");
comboBoxItems.add("B");
comboBoxItems.add("C");
comboBoxItems.add("D");
comboBoxItems.add("E");
final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
JComboBox comboBox = new JComboBox(model);
frame.add(comboBox);

JButton button = new JButton("Add new element in combo box");
frame.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
model.addElement("F");
}
});

frame.setVisible(true);

Dynamically change JComboBox

DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>( yourStringArray );
comboBox.setModel( model );

JComboBox dynamically updating values

Your XMLtoExcelGUI variable, call, is local to the setMeasureValues(...) method. Any changes made to the object that it refers to will only be reflected in this local object and not on any other object of similar type. A guess, but perhaps you want to pass into the method a valid reference to the displayed XMLtoExcelGUI object. Otherwise if this doesn't help, you're going to likely have to improve your question by telling and showing more.


Yes, I was right -- you're setting the model of a combo box in a completely different non-displayed XMLtoExcelGUI instance. Changing the state of one instance will not and should not have an effect on another. The solution is to change the state of the correct displayed instance.

Change this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();

TestVDT call = new TestVDT(file);
jTextPane1.setText(file.toString());

}

}

to something like this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();

TestVDT call = new TestVDT(this, file); // ****** changed
jTextPane1.setText(file.toString());

}

And then this

public class TestVDT {

public int setNumberOfMeasures = 0;
public String[] Measures = new String[30];

public TestVDT(java.io.File FName) {

to something like:

public class TestVDT {

public int setNumberOfMeasures = 0;
public String[] Measures = new String[30];
private XMLtoExcelGUI gui;

public TestVDT(XMLtoExcelGUI gui, java.io.File FName) {
this.gui = gui;

This way your method can use a reference to the actual displayed GUI:

public void setMeasureValues(String S[], int length) {
Vector comboBoxItems = new Vector();
for (int i = 1; i < length; i++) {
comboBoxItems.add(S[i]);
}

// XMLtoExcelGUI call = new XMLtoExcelGUI(); // **** no!
DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(comboBoxItems);

// give XMLtoExcelGUI a public method that sets
// its own combo box's model
gui.setComboModel(defaultComboBoxModel);



}

Dynamic JComboBoxes from the same enum

Add an ActionListener to the first combo box. When the action is triggered, reset the model on the second combo box to the full list of roles, and then use removeItem(Object) to remove the already selected role from the second box. Alternately, empty the model and re-add all items except for the selected one:

private enum Roles {CODER, MANAGER, USER}

JComboBox box1 = new JComboBox(Roles.values());
JComboBox box2 = new JComboBox();
public RoleSelection() {
box1.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
box2.removeAllItems();
box2.addItem(null); // For those with only one role
for (Roles role : Roles.values()) {
if (role != box1.getSelectedItem()) {
box2.addItem(role);
}
}
}
});
// Trigger a selection even to update the second box
box1.setSelectedIndex(0);

add(box1, BorderLayout.NORTH);
add(box2, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {
new RoleSelection().setVisible(true);
}

Dynamic jcombobox items inside jtable

Table has two columns both are rendered as JComboBox. Now, selection of Column-2 items are dependent on the Column-1 selection.

JComboBox Selction

import java.awt.Component;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;


public class ComboBoxExample {

private void createUI() {

JFrame frame = new JFrame();

Object[] columNames = {"Combo-1", "Combo-2"};
Object[][] data = {{"", ""}, {"", ""}, {"", ""}, {"", ""}};

JTable table = new JTable(data, columNames);

table.getColumnModel().getColumn(0).setCellEditor(new CustomComboBoxEditor());
table.getColumnModel().getColumn(1).setCellEditor(new CustomComboBoxEditor());

frame.add(new JScrollPane(table));
frame.setTitle("Column -2 based on Column - 1 ComboBox Selection.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
Runnable r = new Runnable() {

@Override
public void run() {
new ComboBoxExample().createUI();
}
};

EventQueue.invokeLater(r);
}

}

class CustomComboBoxEditor extends DefaultCellEditor {

// Declare a model that is used for adding the elements to the `ComboBox`
private DefaultComboBoxModel model;

private List<String> obtainedList;

public CustomComboBoxEditor() {
super(new JComboBox());
this.model = (DefaultComboBoxModel)((JComboBox)getComponent()).getModel();
obtainedList = new ArrayList<String>();

obtainedList.add("One");
obtainedList.add("Two");
obtainedList.add("Three");
obtainedList.add("Four");
obtainedList.add("Five");
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {


if(column == 0) {
model.removeAllElements();
for(int i = 0; i < obtainedList.size(); i++) {
model.addElement(obtainedList.get(i));
}
} else {

model.removeAllElements();
String selectedItem = (String) table.getValueAt(row, 0);
for(int i = 0; i < obtainedList.size(); i++) {
if(!selectedItem.equals(obtainedList.get(i)))
model.addElement(obtainedList.get(i));
}
} // Close else

return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}

How can I dynamically change the number of items in a JComboBox

As a thought...Instead of doing all these conversions from integer to string and string to back to integer in order to fill your combo box, why not just have a combo box of Integer? You're dealing initially with integer quantity values anyways:

JComboBox<Integer> cb = new JComboBox<>();
int len = storeManager.getInv().getStockAmount(prodId);
for (int i = 1; i <= len; i++) {
cb.addItem(i);
}
cb.setSelectedIndex(0);

Your action listener might look something like this now:

okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Product p1 = storeManager.getInv().getProd(prodId);
int quantity = (int) cb.getSelectedItem();
/* This 'if' statement below would be moot if the Combo-Box
is properly updated unless editing is allowed in the combo
which in this case...disable that feature. */
if (quantity > storeManager.getInv().getStockAmount(prodId)) {
System.out.println("Not Enough Stock.");
} else {
storeManager.getCart().addToCart(p1, quantity);
len = storeManager.getInv().removeStockAmount(prodId, quantity);
cb.removeAllItems();
for (int i = 1; i <= len; i++) { cb.addItem(i); }
cb.setSelectedIndex(0);
}
}
});

Possibly better yet would be to utilize the JSpinner component instead of a Combo Box. A drop-down list in this use case always seems a bit obtrusive in my opinion.



Related Topics



Leave a reply



Submit