在自定义渲染中设置可编辑JComboBox中的文本字段

时间:2012-05-27 18:51:38

标签: java swing jcombobox

enter image description here

两个comboBox使用相同的代码,唯一的例外是“combo 1”设置为可编辑而“Combo 2”不设置。两者都选择了“第1项”。如您所见,“组合1”在组合文本字段中打印“[Ljava.lang.Object; @ 77905258”,“组合2”打印所选名称。

“组合1”如何在组合框文本域中打印相同的文本作为“组合2”?

符合E :(参见附图)  如果单击“组合1”,您将看到项目1,项目2的列表...但是当选择项目时,文本组将显示“[Ljava.lang.Object; @ 77905258”(此处为项目1被选中)。

如果单击“组合2”,您将看到项目1,项目2的列表...当选择“项目1”时,不可编辑的文本字段将显示“项目1”。

以下是代码:

我正在使用自定义渲染器:

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;
    } 
 }

以下是设置2个组合框列表的代码:

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());       
}

这是事件的代码。这会为每个所选项目设置文本字段:

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());  
}

这是完整的代码,可以通过SC和C来剪切和过去。不要忘记添加自定义渲染器“MyListRenderer”类。 (使用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());       
}
}

2 个答案:

答案 0 :(得分:5)

最后......为了做到这一点,我必须添加一个基本的自定义ComboBox编辑器,并在我的原始代码中将自定义编辑器设置为我的组合框(包括在我的问题中):

cmbMyCombo.setEditor(new MyComboEditor());

自定义组合框编辑器类需要实现ComboBoxEditor。我有6个方法来覆盖。但这里有3个主要的。在getEditorComponent中,我返回一个文本字段,但我可以返回任何类型的组件。

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

然后我根据setItem()中选定的对象数据[1]在textFeild中设置文本(请注意,我将保留原始对象以便稍后返回“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;
     }
}

如果从列表中选择了原始对象,或者如果已经编辑了文本字段,则返回自定义对象。

@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()};
    }
}

这对于组合框来说是很多工作,但在我的情况下它是值得的。希望这可以帮助别人。

以下是对这项工作的回应: http://www.java2s.com/Code/Java/Swing-JFC/AfancyexampleofJComboBoxwithacustomrendererandeditor.htm http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html 以下是自定义组合编辑器“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);
}    
}

答案 1 :(得分:2)

  

我设置了myComboBox.setRenderer(new MyListRenderer());我在列表中选择的内容返回组合文本字段中的对象。注意:我的Object [] {id,nomClient}中的id是我对数据库的反应。

RendererJTableJListJComboBox的相同概念)用于格式化已存在的值(Color,{{1} },FontBackground),Foregroundaddputchange modify内的任何内容

  

我该如何解决这个问题?

将数据Renderer直接添加到Items,在您的情况下更新ComboBoxModel,注意JComboBoxaddputchange必须在Event Dispatch Thread

上完成