简体   繁体   中英

ComboBox as a CellRenderer of JTable

I want to draw several JTables, each of which has a ComboBox as a cell renderer. Each cell in each table represents a list of data items and I want the list to be displayed each time I click on the ComboBox arrow. My problem is that the ComboBox does not react to mouse clicks, ie the drop-down list does not appear.

How can I activate the drop boxes?

I added below the picture of my GUI and the code.

I am new to java.swing. Any help will be highly appreciated.

我的GUI // Some code borrowed from how to add checkbox and combobox in table cell?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class MyGUI extends JPanel {
    private int _nTables;
    private int _nRows; 
    private int _nCols;
    private String[] _tableInfo;
    private String[][][][] _clusters; 
    private String[][][][] _clustersIntersections;

    public MyGUI(int nTables, int nRows, int nCols, String[] tableInfo, 
            String[][][][] clusters, 
            String[][][][] clustersIntersections) {
        super();
        _nTables = nTables;
        _nRows = nRows;
        _nCols = nCols;
        _clusters = clusters;
        _clustersIntersections = clustersIntersections;

        GridLayout layout = new GridLayout(0, 2);
        layout.setHgap(30);
        layout.setVgap(30);
        setLayout(layout); 

        for(int t=0; t<_nTables; t++){
            JPanel innerPanel = new JPanel(new BorderLayout());
            innerPanel.setBorder(new LineBorder(Color.black));
            JLabel label = new JLabel(tableInfo[t]);
            label.setOpaque(true);
            label.setBackground(Color.WHITE);
            innerPanel.add(label, BorderLayout.PAGE_START);

            JTable table = new JTable(new MyModel(_nRows, _nCols, 
                                              _clusters[t], 
                                              _clustersIntersections[t]));
            table.setBorder(new LineBorder(Color.black));
            table.setMinimumSize(new Dimension(300,80));    
            table.setMaximumSize(new Dimension(300,80));    
            table.setRowHeight(36);         
            table.setFillsViewportHeight(true);
            table.setCellSelectionEnabled(true);

            for(int c=0; c<nCols; c++){
                table.getColumnModel().getColumn(c).setCellRenderer(new ComboBoxCellRenderer());
            }
            innerPanel.add(table, BorderLayout.PAGE_END);

            add(innerPanel);            
        }       
    }

    class MyModel extends AbstractTableModel{   
        int _nRows;
        int _nCols;
        String[][][] _clusters; 
        String[][][] _clustersIntersections;    

        MyModel(int nRows, int nCols, 
                String[][][] clusters, 
                String[][][] clustersIntersections){
            _nRows = nRows;
            _nCols = nCols;
            _clusters = clusters;
            _clustersIntersections = clustersIntersections;
        }

        public int getColumnCount() {
            return _nCols;
        }

        public int getRowCount() {
            return _nRows;
        }

        public Object getValueAt(int row, int col) {
            return _clusters[row][col];
        }

        public Object getAdditionalInfo(int row, int col) {
            return _clustersIntersections[row][col];
        }

        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }   

    class ComboBoxPanel extends JPanel {
        protected JComboBox<String> comboBox;

        public ComboBoxPanel() {
            super();
            comboBox = new JComboBox<String>() {
            @Override 
            public Dimension getPreferredSize() {
                Dimension d = super.getPreferredSize();
                return new Dimension(80, d.height);
            }
        };
        setOpaque(true);
        comboBox.setEnabled(true);
        comboBox.setEditable(false);
        add(comboBox);
      }
    }

    class ComboBoxCellRenderer extends ComboBoxPanel
                                                  implements TableCellRenderer {
        public ComboBoxCellRenderer() {
            super();
            setName("Table.cellRenderer");
        }

        @Override 
        public Component getTableCellRendererComponent(JTable table, Object value, 
                                                       boolean isSelected,
                                                       boolean hasFocus, 
                                                       int row, int column) {
            setBackground(isSelected?table.getSelectionBackground()
                                                        :table.getBackground());

            if(value!=null) {
                String[] clustersList = (String[]) value;
                comboBox.removeAllItems();
                for(String cluster:clustersList){
                    comboBox.addItem(cluster);
                }               
                System.out.print("Items count = "+comboBox.getItemCount());             
                System.out.print("    Items: {");
                int count = comboBox.getItemCount();
                for(int i = 0; i<count; i++){
                    System.out.print(comboBox.getItemAt(i)+" ");
                }
                System.out.print("}");              
                System.out.println("");
            }

            if(value!=null) {
                comboBox.setSelectedIndex(0);
            }
            return this;
        }
    }   

    public void draw(){

    }   

    public static void main(String[] args) {
        int nTables = 4;
        int nRows = 2;
        int nCols = 2; 
        String[] tableInfo = new String[nTables];
        String[][][][] clusters = new String[nTables][nRows][nCols][];
        String[][][][] clustersIntersections = new String[nTables][nRows][nCols][];
        for(int t=0; t<nTables; t++){
            tableInfo[t] = new String("   Info");
            for(int row=0; row<nRows; row++){
                for(int col=0; col<nCols; col++){
                    clusters[t][row][col] = 
                    new String[]{"   "+new Integer(t).toString(), 
                                  new Integer(row).toString(), 
                                  new Integer(col).toString()};

                    clustersIntersections[t][row][col] = 
                            new String[]{new Integer(t).toString(), 
                                          new Integer(row).toString(), 
                                          new Integer(col).toString()};
                }
            }
        }       
        //Create and set up the window.
        JFrame frame = new JFrame("MyGUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

        //Create and set up the content pane.       
        MyGUI gui = new MyGUI(nTables, nRows, nCols, tableInfo, clusters, clustersIntersections);
        gui.setOpaque(true); //content panes must be opaque

        JScrollPane scrollPane = new JScrollPane(gui);
        frame.setContentPane(scrollPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
}

Be default cells are not editable.

You need to override the isCellEditable(...) method of your custom model to return true to make the cell editable.

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