Results 1 to 3 of 3
  1. #1
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default Showing different values in JComboBox inside JTable

    Hello everyone

    I have successfully created a table that displays comboboxes inside one of the columns. The issue is that i need some of them to display different choices based on the value in another column. Here's some of my code :

    renderer class :

    Java Code:
    class ComboTableCellRenderer extends DefaultTableCellRenderer implements ListCellRenderer, TableCellRenderer 
        {
            DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();
            DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();
            
            public ComboTableCellRenderer()
            {
                setHorizontalAlignment(SwingConstants.CENTER);
            }
    
            private void configureRenderer(JLabel renderer, Object value) 
            {
                if ((value != null) && (value instanceof SubType)) 
                {
                    renderer.setText(((SubType)value).getName());
                } 
            }
    
            public Component getListCellRendererComponent(JList list, Object value, int index,
                    boolean isSelected, boolean cellHasFocus) 
            {
                listRenderer = (DefaultListCellRenderer) listRenderer.getListCellRendererComponent(list, value,
                        index, isSelected, cellHasFocus);
                configureRenderer(listRenderer, value);
                return listRenderer;
            }
    
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) 
            {
                tableRenderer = (DefaultTableCellRenderer) tableRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                configureRenderer(tableRenderer, value);
                return tableRenderer;
            }
        }
    Code portion where i create the combobox :

    Java Code:
    ComboTableCellRenderer renderer = new ComboTableCellRenderer();
    JComboBox comboBox = new JComboBox(subFolders.toArray());
    comboBox.setRenderer(renderer);
    comboBox.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                comboAction(e);
            }
        });
    TableCellEditor editor = new DefaultCellEditor(comboBox);
    TableColumn column = getColumnModel().getColumn(4);
    column.setCellRenderer(renderer);
    column.setCellEditor(editor);
    the subfolder variable is an arraylist containing different string values based on the second column. The issue i see is that you have to set the editor/renderer on a COLUMN basis, not a CELL. How would i go about changing the values inside that combobox? Right now it displays correctly but it always has the same values regardless of what the other column contains, which in a way makes sense since i'm adding the data row by row and i run those previous instructions on every row. Here's my showFiles() method :


    Java Code:
    private void showFiles()
        {
            File folder = new File(folderPath);
            File[] folders = folder.listFiles();
            int liI = 0;
            int liLength = folders.length;
            while (liI < liLength)
            {
                File file = folders[liI];
                setValueAt(file.getName(), liI, 0);
                String fileType = getFileType(file);
                if (file.isDirectory())
                {
                    setValueAt(new JLabel("Directory"), liI, 1);
                }
                else
                {
                    setValueAt(new JLabel(fileType), liI, 1);
                    if (fileType.compareTo("Other") != 0)
                    {
                        FileAssociation fta = getFileAssociation(fileType);
                        setValueAt(fta.getTargetPath(), liI, 3);
                        ArrayList subFolders = fta.getSubFolders();
                        if (subFolders.size() > 0)
                        {
                            ComboTableCellRenderer renderer = new ComboTableCellRenderer();
                            JComboBox comboBox = new JComboBox(subFolders.toArray());
                            comboBox.setRenderer(renderer);
                            comboBox.addActionListener(new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e)
                                {
                                    comboAction(e);
                                }
                            });
                            TableCellEditor editor = new DefaultCellEditor(comboBox);
                            TableColumn column = getColumnModel().getColumn(4);
                            column.setCellRenderer(renderer);
                            column.setCellEditor(editor);
                        }
                    }
                }
                setValueAt(new Date(file.lastModified()), liI, 2);
                liI++;
            }
        }
    Any help would be greatly appreciated!

    Martin

  2. #2
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default

    I found this article :

    Java Tip 102: Add multiple JTable cell editors per column - JavaWorld

    I will try it and see if it works!

  3. #3
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default

    Well the example works but i'm unable to integrate it in my project. Here's my whole FolderTable class (yes, it's huge)

    Java Code:
    package Utils.folderTable;
    
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import javax.swing.DefaultCellEditor;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.RowSorter;
    import javax.swing.SortOrder;
    import javax.swing.SwingConstants;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableRowSorter;
    
    public class FolderTable extends JTable
    {
        private String folderPath;
        private String folderIconPath;
        private String originalFolderPath;
        ArrayList fileTypeAssociations = new ArrayList();
        private Font font = new Font("Helvetica", Font.BOLD, 14);
        protected RowEditorModel rm;
    
        public FolderTable(String folderPath, String folderIconPath)
        {
            this.folderPath = folderPath;
            this.originalFolderPath = folderPath;
            this.folderIconPath = folderIconPath;
            rm = null;
            loadAssociations();
            prepareTable();
            addListeners();
            showFiles();
            packColumns();
        }
    
        public void back()
        {
            String oldPath = getFolderPath();
            String newPath = oldPath.substring(0, oldPath.lastIndexOf("\\"));
            if (oldPath.length() > originalFolderPath.length())
            {
                setFolderPath(newPath);
                prepareTable();
                showFiles();
                packColumns();
            }
        }
    
        private void prepareTable()
        {
            setModel(new FolderTableModel());
            JTableHeader header = getTableHeader();
            header.setFont(font);
            setRowHeight(100);
            RowEditorModel tableRM = new RowEditorModel();
            setRowEditorModel(tableRM);
            setSorters();
            setRenderers();
        }
        
        private void setSorters()
        {
            TableRowSorter sorter = new TableRowSorter(getModel());
            Comparator comp = new FolderTableSorter(false);
            sorter.setComparator(0, comp);
            sorter.setComparator(1, comp);
            sorter.setComparator(2, comp);
            List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
            sortKeys.add(new RowSorter.SortKey(1, SortOrder.ASCENDING));
            sorter.setSortKeys(sortKeys);
            sorter.toggleSortOrder(1);
            setRowSorter(sorter);
            ((FolderTableModel)getModel()).fireTableDataChanged();
            revalidate();
        }
    
        private void setRenderers()
        {
            JLabelRenderer labelRenderer = new JLabelRenderer();
            StringRenderer stringRenderer = new StringRenderer();
            TableColumn tc0 = getColumnModel().getColumn(0);
            tc0.setCellRenderer(stringRenderer);
            TableColumn tc1 = getColumnModel().getColumn(1);
            tc1.setCellRenderer(labelRenderer);
            TableColumn tc2 = getColumnModel().getColumn(2);
            tc2.setCellRenderer(stringRenderer);
            TableColumn tc3 = getColumnModel().getColumn(3);
            tc3.setCellRenderer(stringRenderer);
        }
    
        private void showFiles()
        {
            File folder = new File(folderPath);
            File[] folders = folder.listFiles();
            int liI = 0;
            int liLength = folders.length;
            while (liI < liLength)
            {
                File file = folders[liI];
                setValueAt(file.getName(), liI, 0);
                String fileType = getFileType(file);
                if (file.isDirectory())
                {
                    setValueAt(new JLabel("Directory"), liI, 1);
                }
                else
                {
                    setValueAt(new JLabel(fileType), liI, 1);
                    if (fileType.compareTo("Other") != 0)
                    {
                        FileAssociation fta = getFileAssociation(fileType);
                        setValueAt(fta.getTargetPath(), liI, 3);
                        ArrayList subFolders = fta.getSubFolders();
                        if (subFolders.size() > 0)
                        {
                            try
                            {
                                JComboBox cb = new JComboBox(subFolders.toArray());
                                cb.addActionListener(new ActionListener()
                                {
                                    public void actionPerformed(ActionEvent e)
                                    {
                                        comboAction(e);
                                    }
                                });
                                DefaultCellEditor ed = new DefaultCellEditor(cb);
                                rm.addEditorForRow(liI,ed);
                            }
                            catch (Exception ex)
                            {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
                setValueAt(new Date(file.lastModified()), liI, 2);
                liI++;
            }
        }
        
        private void comboAction(ActionEvent e)
        {
            Object value = ((JComboBox)e.getSource()).getSelectedItem();
            if (value != null)
            {
                RowJComboBox cmb = (RowJComboBox)e.getSource();
                System.out.println(cmb.getSelectedItem().toString() + " row " + cmb.getRow());
            }
            else
            {
                
            }
        }
    
        private FileAssociation getFileAssociation(String displayName)
        {
            int liI = 0;
            int liLength = fileTypeAssociations.size();
            while (liI < liLength)
            {
                FileAssociation fta = (FileAssociation)fileTypeAssociations.get(liI);
                if (fta.getDisplayName().compareTo(displayName) == 0)
                {
                    return fta;
                }
                liI++;
            }
            return null;
        }
    
        private String getFileType(File file)
        {
            String type = "";String extension = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
            int liI = 0;
            boolean found = false;
            int liLenght = fileTypeAssociations.size();
            while ((liI < liLenght)&&(!found))
            {
                FileAssociation fta = (FileAssociation)fileTypeAssociations.get(liI);
                ArrayList specificAssociations = fta.getExtensions();
                if ((specificAssociations.contains(extension)) || (specificAssociations.contains(extension.toLowerCase())))
                {
                    found = true;
                    type = fta.getDisplayName();
                }
                liI++;
            }
            if (!found)
            {
                type = "Other";
            }
            return type;
        }
    
        private void loadAssociations()
        {
            File folder = new File("config\\fileTypes");
            int nbrFiles = folder.listFiles().length;
            File files[] = folder.listFiles();
            if (nbrFiles > 0)
            {
                for (int liI = 1; liI <= nbrFiles; liI++)
                {
                    File file = files[liI - 1];
                    String path = folder.getPath()+ "\\" + file.getName();
                    FileAssociation fta = null;
                    try
                    {
                        fta = FileAssociation.unserializeXML(path);
                    }
                    catch (IOException ex)
                    {
    
                    }
                    fileTypeAssociations.add(fta);
                }
            }
        }
    
        private void addListeners()
        {
            addMouseListener(new java.awt.event.MouseAdapter()
            {
                @Override
                public void mouseClicked(java.awt.event.MouseEvent evt)
                {
                    if ((evt.getClickCount() == 2) && (evt.getButton() == 1))
                    {
                        int row = rowAtPoint(evt.getPoint());
                        String newFolder = getValueAt(row, 0).toString();
                        String newPath = getFolderPath() + "\\" + newFolder;
                        File folder = new File(newPath);
                        if (folder.isDirectory())
                        {
                            setFolderPath(newPath);
                            prepareTable();
                            showFiles();
                        }
                    }
                    else if (evt.getButton() == 3)
                    {
                        back();
                    }
                }
            });
        }
    
        private void packColumns()
        {
            for (int c=0; c<getColumnCount(); c++)
            {
                packColumn(c);
            }
        }
    
        private void packColumn(int vColIndex)
        {
            try
            {
                DefaultTableColumnModel colModel = (DefaultTableColumnModel)getColumnModel();
                TableColumn col = colModel.getColumn(vColIndex);
                int width = 0;
                TableCellRenderer renderer = col.getHeaderRenderer();
                if (renderer == null)
                {
                    renderer = getTableHeader().getDefaultRenderer();
                }
                Component comp = renderer.getTableCellRendererComponent(
                    this, col.getHeaderValue(), false, false, 0, 0);
                width = comp.getPreferredSize().width;
                for (int r=0; r<getRowCount(); r++)
                {
                    renderer = getCellRenderer(r, vColIndex);
                    comp = renderer.getTableCellRendererComponent(
                        this, getValueAt(r, vColIndex), false, false, r, vColIndex);
                    width = Math.max(width, comp.getPreferredSize().width);
                }
                width += 4;
                col.setPreferredWidth(width);
            }
            catch (Exception ex)
            {
    
            }
        }
    
        @Override
        public Component prepareRenderer(TableCellRenderer renderer,
                                                 int rowIndex, int vColIndex)
        {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (c instanceof JComponent)
            {
                JComponent jc = (JComponent)c;
                Object cellComponent = getValueAt(rowIndex, vColIndex);
                if (cellComponent instanceof String)
                {
                    jc.setToolTipText((String)getValueAt(rowIndex, vColIndex));
                }
                else if (cellComponent instanceof Date)
                {
                    jc.setToolTipText(((Date)getValueAt(rowIndex, vColIndex)).toString());
                }
                else if (cellComponent instanceof JLabel)
                {
                    JLabel label = (JLabel)getValueAt(rowIndex, vColIndex);
                    jc.setToolTipText(label.getText());
                }
                else
                {
                    jc.setToolTipText("");
                }
                c.setFont(font);
            }
            return c;
        }
    
        @Override
        public boolean isCellEditable(int row, int column)
        {
            boolean editable = true;
            if(column != 4)
            {
                editable = false;
            }
            return editable;
        }
    
        public String getFolderIconPath() 
        {
            return folderIconPath;
        }
    
        public void setFolderIconPath(String folderIconPath) 
        {
            this.folderIconPath = folderIconPath;
        }
    
        public String getFolderPath() 
        {
            return folderPath;
        }
    
        public void setFolderPath(String folderPath) 
        {
            this.folderPath = folderPath;
        }
    
        public RowEditorModel getRm() 
        {
            return rm;
        }
    
        public void setRm(RowEditorModel rm) 
        {
            this.rm = rm;
        }
        
        public void setRowEditorModel(RowEditorModel rm) 
        {
            this.rm = rm;
        }
    
        public RowEditorModel getRowEditorModel() 
        {
            return rm;
        }
        
        @Override
        public TableCellEditor getCellEditor(int row, int col) 
        {
            TableCellEditor tmpEditor = null;
            if (rm != null) 
            {
                tmpEditor = rm.getEditor(row);
            }
            if (tmpEditor != null) 
            {
                return tmpEditor;
            }
            return super.getCellEditor(row, col);
        }
    
        private class FolderTableModel extends DefaultTableModel
        {
            private HashMap lookup;
            private int rows;
            private int columns;
            private String[] headers;
    
            public FolderTableModel()
            {
                this.rows = getFileCount();
                this.headers = new String[]{"Name", "Type", "Last Modified", "Target Path", "Subfolder"};
                this.columns = headers.length;
                lookup = new HashMap();
            }
    
            @Override
            public int getColumnCount()
            {
                return columns;
            }
    
            @Override
            public Class getColumnClass(int columnIndex)
            {
                if (columnIndex == 1)
                {
                    return JLabel.class;
                }
                else if (columnIndex == 4)
                {
                    return JComboBox.class;
                }
                else
                {
                    return Object.class;
                }
            }
    
            @Override
            public int getRowCount()
            {
                return rows;
            }
    
            @Override
            public String getColumnName(int column)
            {
                return headers[column];
            }
    
            @Override
            public Object getValueAt(int row, int column)
            {
                return lookup.get(new Point(row, column));
            }
    
            @Override
            public void setValueAt(Object value, int row, int column)
            {
                if ((rows < 0) || (columns < 0))
                {
                    throw new IllegalArgumentException("Invalid row/column setting");
                }
                if ((row < rows) && (column < columns))
                {
                    lookup.put(new Point(row, column), value);
                }
            }
    
            private int getFileCount()
            {
                File folder = new File(folderPath);
                File[] folders = folder.listFiles();
                return folders.length;
            }
        }
    
        private class StringRenderer extends DefaultTableCellRenderer
        {
            public StringRenderer()
            {
                setHorizontalAlignment(SwingConstants.CENTER);
            }
    
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            {
                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
        }
    
        private class JLabelRenderer extends DefaultTableCellRenderer
        {
            public JLabelRenderer()
            {
                setHorizontalAlignment(SwingConstants.CENTER);
            }
    
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            {
                JLabel label = (JLabel)value;
                label.setOpaque(true);
                if (label.getText().compareTo("Directory") == 0)
                {
                    label.setIcon(new ImageIcon(folderIconPath));
                }
                else
                {
                    try
                    {
                        FileAssociation fta = getFileAssociation(label.getText());
                        label.setIcon(fta.getImage());
                    }
                    catch (NullPointerException ex)
                    {
                        label.setIcon(new ImageIcon("images\\other.jpg"));
                    }
                }
                fillColor(table,label,isSelected);
                return label;
            }
    
            public void fillColor(JTable t,Component c,boolean isSelected )
            {
                JLabel l = (JLabel)c;
                if(isSelected)
                {
                    l.setBackground(t.getSelectionBackground());
                    l.setForeground(t.getSelectionForeground());
                }
                else
                {
                    l.setBackground(t.getBackground());
                    l.setForeground(t.getForeground());
                }
            }
        }
    
        private class FolderTableSorter implements Comparator
        {
            private boolean isAscOrder;
    
            public FolderTableSorter(boolean isAscOrder)
            {
                this.isAscOrder = isAscOrder;
            }
    
            public int compare (Object o1, Object o2)
            {
                if ((o1 instanceof JLabel) && (o2 instanceof JLabel))
                {
                    JLabel label1 = (JLabel)o1;
                    JLabel label2 = (JLabel)o2;
                    if (label1.getText().compareTo("Directory") == 0)
                    {
                        return -1;
                    }
                    else if (label2.getText().compareTo("Directory") == 0)
                    {
                        return 1;
                    }
                    else if (label1.getText().compareTo("Other") == 0)
                    {
                        return 1;
                    }
                    else if (label2.getText().compareTo("Other") == 0)
                    {
                        return -1;
                    }
                    else
                    {
                        return label1.getText().compareTo(label2.getText());
                    }
                }
                else if ((o1 instanceof Date) && (o2 instanceof Date))
                {
                    Date d1 = (Date)o1;
                    Date d2 = (Date)o2;
                    return d1.compareTo(d2);
                }
                else if ((o1 instanceof String) && (o2 instanceof String))
                {
                    String s1 = o1.toString();
                    String s2 = o2.toString();
                    return s1.compareTo(s2);
                }
                return 0;
            }
        }
    }

Similar Threads

  1. jtable showing limited rows
    By pink123 in forum AWT / Swing
    Replies: 6
    Last Post: 04-26-2011, 07:29 PM
  2. JTable is there, but not showing
    By Ambergahill in forum New To Java
    Replies: 1
    Last Post: 12-04-2010, 11:26 PM
  3. JComboBox in Jtable
    By maneesh in forum AWT / Swing
    Replies: 3
    Last Post: 12-09-2009, 09:37 PM
  4. JComboBox in JTable and Cant get Focus...
    By markw8500 in forum New To Java
    Replies: 1
    Last Post: 03-30-2009, 12:35 AM
  5. showing records in Jtable
    By Shivraj in forum NetBeans
    Replies: 0
    Last Post: 03-21-2009, 08:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •