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);
Adding items dynamically to JComboBox
This looks wrong to me
int len=projects.size()-1;
String[] pro_string=new String[len];
for(int j=0;j<=len;j++)
{
pro_string[j]=projects.get(j);
}
I think it should be
int len=projects.size();
String[] pro_string=new String[len];
for(int j=0;j<len;j++)
{
pro_string[j]=projects.get(j);
}
Editing item in JCombobox dynamically
Instead of ...
getStrings().remove(position);
fireIntervalRemoved(this, position, position);
getStrings().add(position, newString);
fireIntervalAdded(this, position, position);
Which has a number of efficiency issues related to it, you could try...
getStrings().set(position, newString);
fireContentsChanged(this, position, position);
instead...
You current StringModel
seems like a waste, as DefaultComboBoxModel
already has a backing model of it's own. Instead, you could simple extend from AbstractListModel
and implement ComboBoxModel
which would give you a cleaner base class to start from, for example...
public class StringComboBoxModel extends AbstractListModel<String> implements ComboBoxModel<String> {
private List<String> values;
private String selectedItem;
public StringComboBoxModel() {
this(new ArrayList<String>(25));
}
public StringComboBoxModel(List<String> values) {
this.values = values;
}
@Override
public int getSize() {
return values.size();
}
@Override
public String getElementAt(int index) {
return values.get(index);
}
@Override
public void setSelectedItem(Object anItem) {
if (anItem instanceof String) {
selectedItem = (String) anItem;
} else {
selectedItem = null;
}
}
@Override
public Object getSelectedItem() {
return selectedItem;
}
protected List<String> getValues() {
return values;
}
}
public class MutableStringComboBoxModel extends StringComboBoxModel {
public MutableStringComboBoxModel() {
}
public MutableStringComboBoxModel(List<String> values) {
super(values);
}
public boolean contains(String value) {
return getValues().contains(value);
}
public void addValue(String value) {
getValues().add(value);
fireIntervalAdded(this, getSize() - 1, getSize() - 1);
}
public void replaceString(String oldString, String newString) {
if (contains(oldString)) {
int position = getValues().indexOf(oldString);
getValues().set(position, newString);
fireContentsChanged(this, position, position);
} else {
addValue(newString);
}
}
// Other management methods...
}
Dynamically change JComboBox
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>( yourStringArray );
comboBox.setModel( model );
Dynamically Updating JComboBox Items when another ComoboBox Changes Indexes
Change the model of the second combo box when an event happens in the first combo box. Something like:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JPanel implements ActionListener
{
private JComboBox<String> mainComboBox;
private JComboBox<String> subComboBox;
private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox<String>( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
add( mainComboBox );
// Create sub combo box with multiple models
subComboBox = new JComboBox<String>();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
add( subComboBox );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ComboBoxTwo() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
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.
Dynamic add items to JComboBox (value + icon = jlabel)
I did it & it works now just fine :) Basicaly 1. I've used a DefaultComboBoxModel, 2. I've added it to my JComboBox, 3. I've added a custom ListCellRenderer which 'translates' taken string (e.g. '#FFFFFF') to a icon & proper text and at the end creates a JLabel with that newborn icon and text.
/**
* Main Class
*/
public class ColorChooser {
...
public ColorChooser() {
...
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
JComboBox combobox = new JComboBox<String>(model);
combobox.setEditable(false);
cobobox.setRenderer(new ComboRenderer());
...
}
...
}
/**
* Renderer Class
*/
public class ComboRenderer extends JLabel implements ListCellRenderer<Object> {
public ComboRenderer() {
}
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
setFont(newFont("Consolas", Font.PLAIN, 14));
setOpaque(true);
String hex;
if (value != null) {
/*
* So basically I add to my 'model' in ColorChooser main class only Strings
* which I get e.g. from some JTextField.
* On base of this String I create icon for future JLabel
* and I set String 'value' as text for it.
*/
hex = value.toString();
Color color = HexToRgb(hex); //Method which translates String to Color
ColorSwatch icon = new ColorSwatch(10, true); // ColorSwatch is a method which creates specific square icon (in this case a little square)
icon.setColor(color);
setText(hex);
setIcon(icon);
}
return this;
}
/*
* My translate method which translates given String to a specific color value
* (RGB/RGBA)
*/
public Color HexToRgb(String colorStr) {
Color color = null;
// For String hex value '#RRGGBB'
if (colorStr.length() == 7) {
color = new Color(
Integer.valueOf(colorStr.substring(1, 3), 16),
Integer.valueOf(colorStr.substring(3, 5), 16),
Integer.valueOf(colorStr.substring(5, 7), 16));
// For String hex value '#AARRGGBB'
} else if (colorStr.length() == 9) {
color = new Color(
Integer.valueOf(colorStr.substring(3, 5), 16),
Integer.valueOf(colorStr.substring(5, 7), 16),
Integer.valueOf(colorStr.substring(7, 9), 16),
Integer.valueOf(colorStr.substring(1, 3), 16));
// For String hex value '0xRRGGBB'
} else if (colorStr.length() == 8) {
color = new Color(
Integer.valueOf(colorStr.substring(2, 4), 16),
Integer.valueOf(colorStr.substring(4, 6), 16),
Integer.valueOf(colorStr.substring(6, 8), 16));
// For String hex value '0xAARRGGBB'
} else if (colorStr.length() == 10) {
color = new Color(
Integer.valueOf(colorStr.substring(4, 6), 16),
Integer.valueOf(colorStr.substring(6, 8), 16),
Integer.valueOf(colorStr.substring(8, 10), 16),
Integer.valueOf(colorStr.substring(2, 4), 16));
} else
JOptionPane.showMessageDialog(null, "Something wen wrong... :|");
return color;
}
}
And with renderer like this I can just add items to my combobox...
try {
String hex = jtextfield.getText();
boolean canI = CheckHexValue(hex); //Method for checkin' if 'hex' String fits some specific terms
if (canI) {
combobox.insertItemAt(hex, 0);
combobox.setSelectedIndex(0);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
...and we are home now. Hope that code will help someone :)
How To Initialize a JComboBox Whose Items are added Dynamically?
Make sure elements are added into the comboBox
, using addItem()
.
Here's a small snippet:
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Demo {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox jComboBox1 = new JComboBox();
jComboBox1.addItem("Item 0");
jComboBox1.addItem("Item 1");
jComboBox1.addItem("Item 2");
jComboBox1.addItem("Item 3");
jComboBox1.addItem("Item 4");
jComboBox1.addItem("Item 5");
Object cmboitem = jComboBox1.getSelectedItem();
System.out.println(cmboitem);
frame.add(jComboBox1);
jComboBox1.setSelectedIndex(4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
EDIT
Adding from a linkedList
for(int i = 0; i < linkedList.size(); i++)
comboBox.addItem(linkedList.get(i).toString());
Related Topics
Include External Jar When Running Java -Jar
What Is the Purpose of Mavens Dependency Declarations Classifier Property
Java Byte Array Contains Negative Numbers
Why Does Hibernate Disable Insert Batching When Using an Identity Identifier Generator
How to Compile Jrxml to Get Jasper
Understanding Scanner's Nextline(), Next(), and Nextint() Methods
Difference Between an Unbound Wildcard and a Raw Type
Why Does My Aes Encryption Throws an Invalidkeyexception
Spring Security's Securitycontextholder: Session or Request Bound
How to Change the Name of a Java Application Process
Functional Interface That Takes Nothing and Returns Nothing
Display Blob (Image) Through Jsp
Java:Read Last N Lines of a Huge File