简体   繁体   English

如何从给定列中的JTable下拉列表制作单个单元格

[英]How to make single cell from a given column as drop down in JTable

I have a drop down and simple text field in my JTable and based on the specific value selected in the drop down, I want to change the text field to drop down as well. 我的JTable中有一个下拉菜单和简单的文本字段,并且根据下拉菜单中选择的特定值,我也想将文本字段更改为下拉菜单。

Below is the code which I am using for the same and I am able to convert the text field to drop down based on the selection but the problem is that it convert all the text fields in the column to drop down. 以下是我用于相同代码的代码,我可以根据选择将文本字段转换为下拉菜单,但问题是它将列中的所有文本字段转换为下拉菜单。 I just want to change the selected row to drop down, rest should remain as text field. 我只想将所选行更改为下拉菜单,其余应保留为文本字段。

        comboBox2.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) {

            String properties = (String) comboBox2.getSelectedItem();
            try {

                switch (properties) {
                case "Choose Object":
                    dd_OR = table.getColumnModel().getColumn(3);

                    model1 = new DefaultComboBoxModel<String>();
                    model1.addElement("");
                    model1.addElement("Snowboarding");
                    model1.addElement("Rowing");
                    model1.addElement("Knitting");

                    JComboBox comboBox3 = new JComboBox<String>(model1);
                    AutoCompleteDecorator.decorate(comboBox3);
                    dd_OR.setCellEditor(new DefaultCellEditor(comboBox3));
                    break;

                }

One way is to override the getCellEditor(...) method of the JTable so you can dynamically determine which editor to use. 一种方法是重写JTablegetCellEditor(...)方法,以便您可以动态确定要使用的编辑器。

Here is a simple example to get your started: 这是一个入门的简单示例:

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

public class TableComboBoxByRow extends JPanel
{
    List<String[]> editorData = new ArrayList<String[]>(3);

    public TableComboBoxByRow()
    {
        setLayout( new BorderLayout() );

        // Create the editorData to be used for each row

        editorData.add( new String[]{ "Red", "Blue", "Green" } );
        editorData.add( new String[]{ "Circle", "Square", "Triangle" } );
        editorData.add( new String[]{ "Apple", "Orange", "Banana" } );

        //  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)
                {
                    JComboBox<String> comboBox1 = new JComboBox<String>( editorData.get(row));
                    return new DefaultCellEditor( comboBox1 );
                }
                else
                    return super.getCellEditor(row, column);
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
//      table.getColumnModel().getColumn(1).setCellRenderer(new ComboBoxRenderer2() );
    }
/*
    class ComboBoxRenderer2 extends DefaultTableCellRenderer
    {
        @Override
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            label.setIcon(UIManager.getIcon("Table.descendingSortIcon"));
            return label;
        }
    }
*/
    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("Table Combo Box by Row");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new TableComboBoxByRow() );
        frame.setSize(200, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

Setting the cell Editor to DefaultCellEditor will apply to all the rows in the column 3. Please your above code like in given below 将单元格编辑器设置为DefaultCellEditor将应用于列3中的所有行。

TableColumn column = table.getColumnModel().getColumn(3);
column.setCellEditor(new CustomTableCellEditor());

And the CustomTableEditor will be 并且CustomTableEditor将是

import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;

public class CustomTableCellEditor extends AbstractCellEditor implements TableCellEditor {

/**
 * 
 */
private static final long serialVersionUID = -6924557080981304281L;
private JComboBox<String> editor;
private String [] values = {"","Snowboarding", "Rowing", "Knitting"};

public CustomTableCellEditor() {
    // Create a new Combobox with the array of values.
    editor = new JComboBox<String>(values);
}

@Override
public Object getCellEditorValue() {
    // TODO Auto-generated method stub
    return editor.getSelectedItem();
}



@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int colIndex) {
    // Set the model data of the table
    if(isSelected)
    {
        // Do Whatever you want
    }

    return editor;
}

}

Hope it will help you 希望对您有帮助

Thanks Rajkumar 感谢Rajkumar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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