0

i have table documentfiles in which i have stored files path i'm retrieving the path from the database and then putting in JTable with cellRendering where i'm adding icon and text it is working fine but i'm facing problem with sort operation

here is my code

import java.awt.Component;
import java.awt.Dimension;
import java.io.File;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

public class GUI extends JPanel {
    static JTable table;
    static JPanel jPanel;
     private static ArrayList<ArrayList<?>> cells = new ArrayList<ArrayList<?>>();
     private static ArrayList<JLabel> columnNames =new ArrayList<JLabel>();

    public GUI(){
         columnNames.add(new JLabel("Name"));
            columnNames.add(new JLabel("Type"));
            columnNames.add(new JLabel("Size"));
            columnNames.add(new JLabel("FilePath"));
        table =new JTable();
        table.setAutoCreateRowSorter(true);
        jPanel=new JPanel();
        new TableForm();
        jPanel.setPreferredSize(new Dimension(300,300));

        add(jPanel);
    }
public static class TableForm {

        public TableForm() {
            try {
                System.out.println(".......");
           ResultSet rs;

              rs=InsertDB.s.executeQuery(" select filepath from documentfiles ");

             table.setModel(new ResultSetTableModel(rs, columnNames));
             table.setDefaultRenderer(JLabel.class, new CellRenderer());
               table.setAutoCreateRowSorter(true);

            JScrollPane jsp=new JScrollPane(table);


            jsp.revalidate();
            jsp.repaint();
            jPanel.add(jsp);

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        public static void showTable() {
            new TableForm();

        }
    }

    public static class ResultSetTableModel   implements TableModel{

        private int rowCount, columnCount=4;


        @Override
        public int getRowCount() {
            return rowCount;
        }
         public ResultSetTableModel(ResultSet resultSet, ArrayList<JLabel> titles) {
            try {
                ResultSetMetaData metaData = resultSet.getMetaData();
                columnCount = metaData.getColumnCount();

                cells = new ArrayList<ArrayList<?>>();

                while (resultSet.next()) {
                    ArrayList<Object> row = new ArrayList(columnCount);

                        row.add(resultSet.getString(1));
                    cells.add(row);
                }

                rowCount = cells.size();
                System.out.println(rowCount);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getColumnCount() {
            return columnCount;
        }

        @Override
        public String getColumnName(int columnIndex) {
            return columnNames.get(columnIndex).getText();
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {

            return JLabel.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return cells.get(rowIndex).get(columnIndex);
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

        }

        @Override
        public void addTableModelListener(TableModelListener l) {

        }

        @Override
        public void removeTableModelListener(TableModelListener l) {

        }


    }

    public static class CellRenderer extends JLabel implements TableCellRenderer {
         File f;
         public CellRenderer() {

         setOpaque(false);//MUST do this for background to show up.

         }

         public Component getTableCellRendererComponent(
              JTable table, Object color,
              boolean isSelected, boolean hasFocus,
              int row, int column) {
                 f=new File(table.getModel().getValueAt(row, column).toString());
         Icon icon= javax.swing.filechooser.FileSystemView.getFileSystemView().getSystemIcon(f);
         setIcon(icon);
         setText(f.getName());
         setToolTipText(f.getName());

         return this;
         }

         } 


     private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("TableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JComponent newContentPane = new GUI();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        }
    public static void main(String args[]){
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });

    }
}

well i'm not able to find out where i'm going wrong, i don't have any idea how to get it done so i'm looking for some help from someone

Thanks in advance

  • well there is a mistake in above code there is a need to change one line to make it work f=new File(table.getTableModel()...); to f=new File(color.toString()); BTW the cell Renderer code can changed with suggested answers it works absolutely fine :) – user2318813 May 01 '14 at 08:08

4 Answers4

1

"NOTE: When using a sorter, always remember to translate cell coordinates."

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

Try this one without extending JLabel

public static class CellRenderer extends DefaultTableCellRenderer{

    ...
    public Component getTableCellRendererComponent(JTable table, Object color,
            boolean isSelected, boolean hasFocus, int row, int column) {
        JLabel label = (JLabel)super.getTableCellRendererComponent(table, color, isSelected, hasFocus, row, column);
        // set icon and other properties of label
        ...
        return label;   
   }
}
Braj
  • 46,415
  • 5
  • 60
  • 76
  • Well i used table.setDefaultRenderer(Object.class,cellRenderer) still i can't sort, BTW the problem i think is with the JLabel, column is JLabel and Row is JLabel, so if it is string i can sort, it works fine but i miss icon at that time in JTable cell, so i'm not able to find a way to fix this. – user2318813 Apr 30 '14 at 17:19
  • use `extends AbstractTableModel` instead of `implements TableModel` if you don't want to override all the methods. – Braj Apr 30 '14 at 17:20
  • @user2318813 I have updated my post. Please have a look. – Braj Apr 30 '14 at 17:34
  • Please have a look at [Using TableCellRenderer and getColumnClass together](http://stackoverflow.com/questions/23369527/using-tablecellrenderer-and-getcolumnclass-together/23379326#23379326). – Braj Apr 30 '14 at 17:36
  • @user2318813 yes you are right the problem is with `JLabel`. Try my solution its working. – Braj May 01 '14 at 03:30
  • thanks for your answers well i tried all your suggestions but couldn't make it to work , there is nothing wrong in suggested code but you didn't identify one mistake which i did here, i didn't use object value that was the mistake i did so finally i have posted my solution to this. – user2318813 May 01 '14 at 07:31
  • @user2318813 I did single change in your code as mentioned above and its working fine for me. Now you have solved it yourself then go ahead with your changes. – Braj May 01 '14 at 07:59
0

The "value" of the cell is passed to the getTableCellRendererComponent by the (in your case color...?) parameter, there's no need to get the value from the table again.

This...

f=new File(table.getModel().getValueAt(row, column).toString());

is redundant...

Instead, you could use...

public Component getTableCellRendererComponent(
        JTable table, Object value,
        boolean isSelected, boolean hasFocus,
        int row, int column) {
    if (value instanceof File) {
        f= (File)value;
        Icon icon= javax.swing.filechooser.FileSystemView.getFileSystemView().getSystemIcon(f);
        setIcon(icon);
        setText(f.getName());
        setToolTipText(f.getName());
    } else {
        setText("Not a valid file");
    }

    return this;
}

If you really need to get a value from the table model, you should be using table.getValueAt(...) instead, as this will convert between the view and model indicies automatically.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

well i could make it to work BTW thanks for all the answers however none of the answers worked the mistake i did here is i neglected the object value instead of that i used value from table model i mean this is the line i changed which made it to work perfectly i changed

 f=new File(table.getModel()...)

to

   f=new File(color.toString());

now i'm able to sort