java JTable 单元格中的 JComboBox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3256086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:01:10  来源:igfitidea点击:

JComboBox in a JTable cell

javaswingjtablejcombobox

提问by anna-k

I have a JTable created using a model, which is based on a matrix of objects. For each row, I want to put in a specific column (the 5th) some information using a JComboBox. I have tried the following:

我有一个使用模型创建的 JTable,该模型基于对象矩阵。对于每一行,我想使用 JComboBox 在特定列(第 5 列)中放入一些信息。我尝试了以下方法:

for(int i=0; i < n ; i++) {  
    .....  
    data[i][5] = new JComboBox(aux); // aux is a Vector of elements I wanna insert  
}  
table.setModel(new MyTableModel()); // MyTableModel() already takes into consideration the data[][] object  

The problem is that data[i][5] = new JComboBox(aux); does not create a JComboBox object in that specific cell of the JTable, but pastes a code into the row. What can I do to solve this problem?

问题是 data[i][5] = new JComboBox(aux); 不会在 JTable 的特定单元格中创建 JComboBox 对象,而是将代码粘贴到行中。我能做些什么来解决这个问题?

Thank you.

谢谢你。

回答by camickr

One way is to override the getCellEditor() method to return an appropriate editor. Here is an example to get you started:

一种方法是覆盖 getCellEditor() 方法以返回适当的编辑器。这是一个让您入门的示例:

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.*;

public class TableComboBoxByRow extends JFrame
{
    List<TableCellEditor> editors = new ArrayList<TableCellEditor>(3);

    public TableComboBoxByRow()
    {
        // Create the editors to be used for each row

        String[] items1 = { "Red", "Blue", "Green" };
        JComboBox comboBox1 = new JComboBox( items1 );
        DefaultCellEditor dce1 = new DefaultCellEditor( comboBox1 );
        editors.add( dce1 );

        String[] items2 = { "Circle", "Square", "Triangle" };
        JComboBox comboBox2 = new JComboBox( items2 );
        DefaultCellEditor dce2 = new DefaultCellEditor( comboBox2 );
        editors.add( dce2 );

        String[] items3 = { "Apple", "Orange", "Banana" };
        JComboBox comboBox3 = new JComboBox( items3 );
        DefaultCellEditor dce3 = new DefaultCellEditor( comboBox3 );
        editors.add( dce3 );

        //  Create the table with default data

        Object[][] data =
        {
            {"Color", "Red"},
            {"Shape", "Square"},
            {"Fruit", "Banana"},
            {"Plain", "Text"}
        };
        String[] columnNames = {"Type","Value"};
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model)
        {
            //  Determine editor to be used by row
            public TableCellEditor getCellEditor(int row, int column)
            {
                int modelColumn = convertColumnIndexToModel( column );

                if (modelColumn == 1 && row < 3)
                    return editors.get(row);
                else
                    return super.getCellEditor(row, column);
            }
        };
        System.out.println(table.getCellEditor());

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
    {
        TableComboBoxByRow frame = new TableComboBoxByRow();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

Edit: code updated to use trashgod's suggestion.

编辑:代码更新为使用垃圾神的建议。

回答by Riduidel

For the JComboBoxto be disaplyed, you have to use a TableCellRenderer. Take a look at Using a Combo Box as an Editor.

要使JComboBoxdisaplyed,您必须使用TableCellRenderer. 看看使用组合框作为编辑器

回答by Javaguru

Hehe, it's not to be used like you proposed.

呵呵,不能像你说的那样用。

You have to create a custom TableCellRenderer or TableCellEditor. Then you can specify for which class it will be used:

您必须创建自定义 TableCellRenderer 或 TableCellEditor。然后您可以指定它将用于哪个类:

JTable.setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)
JTable.setDefaultEditor(Class<?> columnClass, TableCellEditor editor)

A detailed description can be found here: http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/table.html#combobox

可以在此处找到详细说明:http: //download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/table.html#combobox

For a custom renderer in a specific row & column, you can simply use:

对于特定行和列中的自定义渲染器,您可以简单地使用:

final int specialRow = 1;
final int specialColumn = 5;

JTable table = new JTable(myModel) {
   private TableCellEditor mySpecialCellEditor = new SpecialCellEditor( ... );

   public TableCellEditor getCellEditor(int row, int column) {
      int modelColumn = convertColumnIndexToModel(column);
      int modelRow = convertRowIndexToModel(row);
      if (modelColumn == specialColumn && row == specialRow ) {
         return mySpecialCellEditor;
      } else {
         return super.getCellEditor(row, column);
      }
   }
};

回答by Adrian

Try something like this:

尝试这样的事情:

 public void example(){  

      TableColumn tmpColum =table.getColumnModel().getColumn(1);
      String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
      JComboBox comboBox = new JComboBox(DATA);

      DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
      tmpColum.setCellEditor(defaultCellEditor);
      tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
      table.repaint();
   }


/**
   Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
        JComboBox combo;
        public CheckBoxCellRenderer(JComboBox comboBox) {
            this.combo = new JComboBox();
            for (int i=0; i<comboBox.getItemCount(); i++){
                combo.addItem(comboBox.getItemAt(i));
            }
        }
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            combo.setSelectedItem(value);
            return combo;
        }
    }