简体   繁体   中英

java jcombobox inside a listCellRenderer

I would like to create a list containing items with data and a jCombobox. I use this listCellRenderer :

public class DeliveryListCellRenderer extends JPanel implements ListCellRenderer{

     JLabel[] lbl = new JLabel[2];  
     JComboBox combo;

  public DeliveryListCellRenderer()  
  {  
    setLayout(new GridLayout(0,2,15,0));  
    lbl[0] = new JLabel("",JLabel.RIGHT);  
    add(lbl[0]);  
    lbl[1] = new JLabel("",JLabel.LEFT);  
    add(lbl[1]);
    String[] timeZones = {"timeZone 1", "timeZone 2", "timeZone 3", "timeZone 4"};

    combo = new JComboBox(timeZones); 
    combo.setSelectedIndex(1);

    add(combo);
  }  
  public Component getListCellRendererComponent(JList list,Object value,  
                      int index,boolean isSelected,boolean cellHasFocus)  
  {  
    Delivery delivery = (Delivery)value;  
    lbl[0].setText("X : "+delivery.getNode().getX());  
    lbl[1].setText("Y : "+delivery.getNode().getY());
    if(isSelected) setBackground(Color.CYAN);  
    else setBackground(Color.WHITE);  
    return this;  
  }  
}

When I run the application, everything appears ok, but nothing happens when I click on the combobox.

Does anybody have an idea ? Thanks in advance.

When I run the application, everything appears ok, but nothing happens when I click on the combobox.

You need to map the content to display in the ComboBox with your Object.

I would advice the following: (T being the type of your Object).

    public class CustomComboBoxRenderer extends JLabel implements ListCellRenderer<T> {

    @Override
    public Component getListCellRendererComponent(JList<? extends T> list, T value, int index, boolean isSelected, boolean cellHasFocus) {

    if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
    }
    else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
    }
    if (index == -1) {
        setOpaque(false);
        setForeground(list.getForeground());
    }
    else {
        setOpaque(true);
    }
    setFont(list.getFont());

    if (value != null) {
        setText(value.getName());
    }

    return this;
    }
}

ComboBox creation:

    JComboBox<T> comboBox = new JComboBox<T>();
    comboBox.setRenderer(new CustomComboBoxRenderer ());
    add(comboBox);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM