简体   繁体   中英

Updating JComboBox in a single cell in JTable

I need to populate a specific cell in a JTable with a component (JComboBox) based on an action performed in the same table.

I have the JTable set up. All the cells in column A are populated with a JComboBox.

I would like to adapt my code for this (which can be found below), so that when a user selects an option in a JComboBox in a specific row, the next field in the same row (in column B) is populated with a new JComboBox with different items in it.

The problem here is that I do not want to populate the whole of column B with the same JComboBox. Each row in the table can have different options in the JComboBox in column B, based on the selection made in column A.

How could I change my code to do this?

String sql = "SELECT * from tblDepartment ORDER BY deptName";
    int size = 0;
    int count = 0;
    try {
        pst = conn.prepareStatement(sql);
        rs = pst.executeQuery();
        List<String> list = new ArrayList<>();
        while (rs.next()) {//adds each item to the list for the combo box
            list.add(rs.getString("deptName"));
        }
        count = list.size();
        String[] items = list.toArray(new String[list.size()]);
        JComboBox<String> jcb = new JComboBox<>(items);
        TableColumn tc = tblCon.getColumnModel().getColumn(2);
        TableCellEditor tce = new DefaultCellEditor(jcb);//adds the combo box to the relevant cell in the table.
        tc.setCellEditor(tce);
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e);
    }

You can override the getCellEditor(...) method of the JTable to return a specific editor.

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

In the example above the editor is simply determined by the row.

In your case the editor would be determined by the row and the data in the preceding column.

Have you tried with a custom TableCellEditor ? You can use the overridable method called getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) where you can define explicitly the row and column where the JComboBox should appear.

Here is an example with JCheckBox :

public class EditBoolean extends AbstractCellEditor implements TableCellEditor {

        private JCheckBox box;

        public EditBoolean() {
            // This is the component that will handle the editing of the cell value
            box = new JCheckBox();
        }

        // This method is called when editing is completed.
        // It must return the new value to be stored in the cell.
        @Override
        public Object getCellEditorValue() {
            return box.isSelected();
        }

        // This method is called when a cell value is edited by the user.
        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            if(column == 2 && row == 4){

               if (value instanceof Boolean) {
                   box.setSelected((Boolean) (value));
               } else {
                   box.setSelected(Boolean.getBoolean((String) value));
               }
               return box;
            }
       }
}

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