marcb
marcb

Reputation: 152

Setting the text field in editable JComboBox from custom render

enter image description here

Both comboBox use the same code, the only exeption is that "combo 1" is set as editable and "Combo 2" is not. Both have "item 1" selected. As you can see, "Combo 1" is printing "[Ljava.lang.Object;@77905258" in the combo text feild and "Combo 2" print the selected name.

How can "Combo 1" print the same text in the combo box text feild as "Combo 2"?

To comply with E:(refer to attached image) If you click on "Combo 1" you will see the list of item 1, item 2... But the Text feild will show "[Ljava.lang.Object;@77905258" when item is selected (here it is item 1 that is selected).

If you click on "Combo 2" you will see the list of item 1, item 2... And the non-editable Text feild will show "item 1" when "item 1" is selected.

Here is the code:

I'm using a custom renderer:

public class MyListRenderer extends JLabel 
 implements ListCellRenderer{
  @Override
  public Component getListCellRendererComponent(
   JList list, Object value,
   int index, boolean isSelected,
   boolean cellHasFocus) {

    Object[] itemData =(Object[])value;        
    setText((String)itemData[1]);
    return this;
    } 
 }

Here is the code to set the 2 combo boxes list:

private void iniCombobox() {            
   cmbMyCombo.addItem(new Object[] {"1", "Item 1"});
   cmbMyCombo.addItem(new Object[] {"2", "Item 2"});
   cmbMyCombo.addItem(new Object[] {"3", "Item 3"});

   cmbMyCombo2.addItem(new Object[] {"1", "Item 1"});
   cmbMyCombo2.addItem(new Object[] {"2", "Item 2"});
   cmbMyCombo2.addItem(new Object[] {"3", "Item 3"});

   cmbMyCombo.setRenderer(new MyListRenderer());
   cmbMyCombo2.setRenderer(new MyListRenderer());       
}

Here is the code of the events. This set the text feilds per selected item:

private void cmbMyComboActionPerformed(
 java.awt.event.ActionEvent evt) {
    Object mySelectedItem = cmbMyCombo.getSelectedItem();
    Object myObject[] = (Object[])mySelectedItem;
    txtID.setText(myObject[0].toString());
    txtName.setText(myObject[1].toString());        
}

private void cmbMyCombo2ActionPerformed(
 java.awt.event.ActionEvent evt) {
    Object mySelectedItem = cmbMyCombo.getSelectedItem();
    Object myObject[] = (Object[])mySelectedItem;
    txtID1.setText(myObject[0].toString());
    txtName1.setText(myObject[1].toString());  
}

Here is the full code that can be cut and past to Comply with SC and C. Do not forget to add the custom renderer "MyListRenderer" class. (compiled with NetBean 7.1) :

package combobox;

public class MyComboBox extends javax.swing.JFrame {

public MyComboBox() {
    initComponents();
    iniCombobox();
}
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    cmbMyCombo = new javax.swing.JComboBox();
    lblId = new javax.swing.JLabel();
    txtID = new javax.swing.JTextField();
    lblName = new javax.swing.JLabel();
    txtName = new javax.swing.JTextField();
    jPanel2 = new javax.swing.JPanel();
    cmbMyCombo2 = new javax.swing.JComboBox();
    txtID1 = new javax.swing.JTextField();
    lblId1 = new javax.swing.JLabel();
    txtName1 = new javax.swing.JTextField();
    lblName1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants
    .EXIT_ON_CLOSE);

    jPanel1.setBorder(javax.swing.BorderFactory
    .createTitledBorder("Combo 1"));

    cmbMyCombo.setEditable(true);
    cmbMyCombo.addActionListener(new java.awt.event
    .ActionListener() {
        public void actionPerformed(java.awt.event
        .ActionEvent evt) {
            cmbMyComboActionPerformed(evt);
        }
    });

    lblId.setText("ID:");
    lblName.setText("Name:");

    javax.swing.GroupLayout jPanel1Layout = new javax
    .swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax
        .swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(
             javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout
                 .Alignment.TRAILING,
         jPanel1Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(cmbMyCombo, javax
                     .swing.GroupLayout.PREFERRED_SIZE,
                     141,
         javax.swing.GroupLayout
         .PREFERRED_SIZE)
                    .addGap(40, 40, 40))
                .addGroup(jPanel1Layout
                .createSequentialGroup()
                    .addGroup(jPanel1Layout
                     .createParallelGroup(
                       javax.swing.GroupLayout
                       .Alignment.LEADING)
                        .addGroup(jPanel1Layout
                         .createSequentialGroup()
                            .addComponent(lblId)
                            .addGap(28, 28, 28)
                            .addComponent(txtID, javax
                              .swing.GroupLayout
                              .PREFERRED_SIZE, 66,
                               javax.swing.GroupLayout
                              .PREFERRED_SIZE)
                            .addPreferredGap(javax
                             .swing.LayoutStyle
             .ComponentPlacement.RELATED,
             81,
             javax.swing.GroupLayout
             .PREFERRED_SIZE))
                        .addGroup(jPanel1Layout
                         .createSequentialGroup()
                            .addComponent(lblName)
                            .addPreferredGap(javax
                             .swing.LayoutStyle
                             .ComponentPlacement.RELATED)
                            .addComponent(txtName,
                             javax.swing.GroupLayout
                               .PREFERRED_SIZE,
                                147, javax.swing
                               .GroupLayout
                               .PREFERRED_SIZE)))
                    .addContainerGap(
                      35, Short.MAX_VALUE))))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax
        .swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(cmbMyCombo, javax.swing
             .GroupLayout.PREFERRED_SIZE,
      javax.swing.GroupLayout.DEFAULT_SIZE,
      javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle
             .ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(
              javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(txtID, 
                  javax.swing.GroupLayout
                   .PREFERRED_SIZE, javax.swing
                   .GroupLayout.DEFAULT_SIZE, 
                   javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(lblId))
            .addPreferredGap(javax.swing.LayoutStyle
             .ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(
             javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblName)
                .addComponent(txtName, 
                 javax.swing.GroupLayout.PREFERRED_SIZE,
                  javax.swing.GroupLayout.DEFAULT_SIZE,
                  javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(javax.swing.GroupLayout
             .DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jPanel2.setBorder(javax.swing.BorderFactory
    .createTitledBorder("Combo 2"));

    cmbMyCombo2.setToolTipText("");
    cmbMyCombo2.addActionListener(
     new java.awt.event.ActionListener() {
        public void actionPerformed(
         java.awt.event.ActionEvent evt) {
            cmbMyCombo2ActionPerformed(evt);
        }
    });

    lblId1.setText("ID:");

    lblName1.setText("Name:");

    javax.swing.GroupLayout jPanel2Layout = 
      new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(
         javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGroup(jPanel2Layout.createParallelGroup(
              javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                   jPanel2Layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addComponent(
                      cmbMyCombo2,
                      javax.swing.GroupLayout
                      .PREFERRED_SIZE, 135,
                      javax.swing.GroupLayout
                      .PREFERRED_SIZE))
                .addGroup(
                 jPanel2Layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addGroup(jPanel2Layout
                     .createParallelGroup(
                       javax.swing.GroupLayout
                       .Alignment.LEADING)
                        .addGroup(
                          jPanel2Layout
                          .createSequentialGroup()
                            .addComponent(lblId1)
                            .addGap(28, 28, 28)
                            .addComponent(txtID1,
                             javax.swing.GroupLayout
                             .PREFERRED_SIZE,
                              66,
                              javax.swing.GroupLayout
                              .PREFERRED_SIZE)
                            .addPreferredGap(
                             javax.swing.LayoutStyle
                             .ComponentPlacement.RELATED,
                             81, javax.swing.GroupLayout
                             .PREFERRED_SIZE))
                        .addGroup(jPanel2Layout
                         .createSequentialGroup()
                            .addComponent(lblName1)
                            .addPreferredGap(
                             javax.swing.LayoutStyle
                             .ComponentPlacement.RELATED)
                            .addComponent(txtName1,
                             javax.swing.GroupLayout
                             .PREFERRED_SIZE,
                              147,
                              javax.swing.GroupLayout
                             .PREFERRED_SIZE)))))
            .addContainerGap(25, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(
         javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(
              cmbMyCombo2,
              javax.swing.GroupLayout.PREFERRED_SIZE,
              javax.swing.GroupLayout.DEFAULT_SIZE,
              javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle
             .ComponentPlacement.RELATED)
            .addGroup(jPanel2Layout.createParallelGroup(
             javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(
                 txtID1,
                 javax.swing.GroupLayout.PREFERRED_SIZE,
                 javax.swing.GroupLayout.DEFAULT_SIZE,
                 javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(lblId1))
            .addPreferredGap(
             javax.swing.LayoutStyle.ComponentPlacement
             .RELATED)
            .addGroup(
              jPanel2Layout.createParallelGroup(
               javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblName1)
                .addComponent(txtName1,
                javax.swing.GroupLayout.PREFERRED_SIZE,
                javax.swing.GroupLayout.DEFAULT_SIZE,
                javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(
             javax.swing.GroupLayout.DEFAULT_SIZE,
             Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = 
     new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(
         javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(
             jPanel1,
             javax.swing.GroupLayout.PREFERRED_SIZE,
             javax.swing.GroupLayout.DEFAULT_SIZE,
             javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(
              jPanel2,
              javax.swing.GroupLayout.DEFAULT_SIZE,
              javax.swing.GroupLayout.DEFAULT_SIZE,
              Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(
         javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(
             javax.swing.GroupLayout.Alignment.LEADING,
              false)
                .addComponent(
                 jPanel1,
                 javax.swing.GroupLayout.DEFAULT_SIZE,
         javax.swing.GroupLayout.DEFAULT_SIZE,
         Short.MAX_VALUE)
                .addComponent(
         jPanel2,
         javax.swing.GroupLayout.DEFAULT_SIZE,
         javax.swing.GroupLayout.DEFAULT_SIZE,
         Short.MAX_VALUE))
            .addContainerGap(
     javax.swing.GroupLayout.DEFAULT_SIZE,
     Short.MAX_VALUE))
    );

    pack();
}

private void cmbMyComboActionPerformed(
java.awt.event.ActionEvent evt) {
    Object mySelectedItem = cmbMyCombo.getSelectedItem();
    Object myObject[] = (Object[])mySelectedItem;
    txtID.setText(myObject[0].toString());
    txtName.setText(myObject[1].toString());        
}

private void cmbMyCombo2ActionPerformed(
java.awt.event.ActionEvent evt) {
    Object mySelectedItem = cmbMyCombo2.getSelectedItem();
    Object myObject[] = (Object[])mySelectedItem;
    txtID1.setText(myObject[0].toString());
    txtName1.setText(myObject[1].toString());
}

public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new MyComboBox().setVisible(true);
        }
    });
}

private javax.swing.JComboBox cmbMyCombo;
private javax.swing.JComboBox cmbMyCombo2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JLabel lblId;
private javax.swing.JLabel lblId1;
private javax.swing.JLabel lblName;
private javax.swing.JLabel lblName1;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtID1;
private javax.swing.JTextField txtName;
private javax.swing.JTextField txtName1;
// End of variables declaration

private void iniCombobox() {

   cmbMyCombo.addItem(new Object[] {"1", "Item 1"});
   cmbMyCombo.addItem(new Object[] {"2", "Item 2"});
   cmbMyCombo.addItem(new Object[] {"3", "Item 3"});

   cmbMyCombo2.addItem(new Object[] {"1", "Item 1"});
   cmbMyCombo2.addItem(new Object[] {"2", "Item 2"});
   cmbMyCombo2.addItem(new Object[] {"3", "Item 3"});

   cmbMyCombo.setRenderer(new MyListRenderer());
   cmbMyCombo2.setRenderer(new MyListRenderer());       
}
}

Upvotes: 1

Views: 12367

Answers (2)

marcb
marcb

Reputation: 152

Finally...To accomplish this, I had to add a basic custom ComboBox editor and set the custom editor to my combobox in my original code (included in my question):

cmbMyCombo.setEditor(new MyComboEditor());

The custom Combo Box Editor class need to implement ComboBoxEditor. i had 6 method to override. But here are the 3 main one. In getEditorComponent, i return a text feild, but i could return any type of component.

@Override
public Component getEditorComponent() {
    return textFeild;
}

Then I set the text in the textFeild as per my selected object data[1] in setItem() (note that I’m keeping my original objet to be return later "myReturnObject"):

 @Override
 public void setItem(Object anObject) {

    if(anObject != null){
        myObject = (Object[])anObject;
        myReturnObject = anObject;
        //I can now set whatever i want in the text feild            
        textFeild.setText(myObject[1].toString());//<--
     }
     else{ 
       myReturnObject = anObject;
     }
}

I then return the original object if it selected from list or a custom object if the text feild has been edited.

@Override
public Object getItem() {
    String objectTxt = myObject[1].toString();
    String feildTxt = textFeild.getText();

    if(objectTxt.equals(feildTxt)){
        return myReturnObject;
    }
    else{
        //Creating and returning custom object with the Feild text
        //and setting the contnent of the text feild in the object
        return new Object[]{"0",textFeild.getText()};
    }
}

This is a lot of work for a combo box, but it worth it in my case. Hope this can help someone else.

Here are referance for this work: http://www.java2s.com/Code/Java/Swing-JFC/AfancyexampleofJComboBoxwithacustomrendererandeditor.htm http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html Here is the full code for the custom combo editor "MyComboEditor()":

package combobox;

import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.JTextField;

public class MyComboEditor implements ComboBoxEditor {
  JTextField textFeild;
  Object myObject[];
  Object myReturnObject;

public MyComboEditor(){
    textFeild = new JTextField();     
}

@Override
public Component getEditorComponent() {
    return textFeild;
}

@Override
public void setItem(Object anObject) {

    if(anObject != null){
        myObject = (Object[])anObject;
        myReturnObject = anObject;            
        textFeild.setText(myObject[1].toString());
     }
     else{ 
       myReturnObject = anObject;
     }
}

@Override
public Object getItem() {
    String objectTxt = myObject[1].toString();
    String feildTxt = textFeild.getText();

    if(objectTxt.equals(feildTxt)){
        return myReturnObject;
    }
    else{
        return new Object[]{"0",textFeild.getText()};
    }
}

@Override
public void selectAll() {
    throw new UnsupportedOperationException(
            "Not supported yet. in select All");
}

@Override
public void addActionListener(ActionListener l) {
    textFeild.addActionListener(l);     
}

@Override
public void removeActionListener(ActionListener l) {
    textFeild.removeActionListener(l);
}    
}

Upvotes: 6

mKorbel
mKorbel

Reputation: 109813

I do set myComboBox.setRenderer(new MyListRenderer()); What ever i chose in the list return the object in the combo Text field. Note: The id in my Object[]{id, nomClient} is my referance to the database.

Renderer(the same concept for JTable, JList and JComboBox too) is for formatting value that already exist (Color, Font, Background, Foreground), don't add, put, change or modify whatever inside Renderer

How can i fix this?

put data as Items to the JComboBox directly, in your case to update the ComboBoxModel, notice add, put, change or modify must be done on Event Dispatch Thread

Upvotes: 2

Related Questions