0

I am new to Swing and seeking some help here. I need to show the data from an .xls file in a jTable. Below is my code which I followed from here :-

jbClick.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent arg0) { 
        jChooser.showOpenDialog(null); 
        File file = jChooser.getSelectedFile(); 
        if(!file.getName().endsWith("xls")){ 
            JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",JOptionPane.ERROR_MESSAGE);
            } 
        else { 
                fillData(file); 
                model = new DefaultTableModel(data, headers); 
                tableWidth = model.getColumnCount() * 150; 
                tableHeight = model.getRowCount() * 25;
                table.setPreferredSize(new Dimension( tableWidth, tableHeight));
                table.setModel(model); 
                jbClick.setVisible(false);
                jbText.setVisible(true);
                } 
        } 
    }); 

    JPanel chooserPanel = new JPanel(); 
    JPanel filterPanlel = new JPanel();
    //filterPanlel.add(jbText,"OLa");

    final Color alternate = new Color(186,246,244);
    table = new JTable(); 
    table.setAutoCreateRowSorter(true); 
    model = new DefaultTableModel(data, headers); 
    table.setModel(model); 
    table.setBackground(alternate); 
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
    table.setEnabled(false); 
    table.setRowHeight(25); 
    table.setRowMargin(4); 
    tableWidth = model.getColumnCount() * 200;
    tableHeight = model.getRowCount() * 25;
    table.setPreferredSize(new Dimension( tableWidth, tableHeight)); 
    scroll = new JScrollPane(table); 
    scroll.setBackground(alternate); 
    scroll.setPreferredSize(new Dimension(500, 500)); 
    scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
    scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 
    getContentPane().add(buttonPanel, BorderLayout.NORTH); 
    getContentPane().add(scroll, BorderLayout.CENTER); 
    //setSize(600, 600); 
    setResizable(true); 
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    //setUndecorated(true);
    setVisible(true); 
    } 


    /** * Fill JTable with Excel file data. * * @param file * file :contains xls file to display in jTable */ 
    @SuppressWarnings({ "unchecked", "rawtypes" })
    void fillData(File file) { 
        Workbook workbook = null; 
        try { 
            try { 
                workbook = Workbook.getWorkbook(file); 
                } 
            catch (IOException ex) { 
                Logger.getLogger( excelTojTable.class. getName()).log(Level.SEVERE, null, ex); 
                } 
            Sheet sheet = workbook.getSheet(0);
            headers.clear(); 
            for (int i = 0; i < sheet.getColumns(); i++) 
            { 
                Cell cell1 = sheet.getCell(i, 0);
                headers.add(cell1.getContents()); 
            } 
            data.clear(); 
            for (int j = 1; j < sheet.getRows(); j++) 
            { 
                Vector d = new Vector(); 
                for (int i = 0; i < sheet.getColumns(); i++) 
                { 
                    Cell cell = sheet.getCell(i, j); 
                    d.add(cell.getContents()); 
                } 
                d.add("\n");
                data.add(d); 
                } 
            } 
        catch (BiffException e) { 
            e.printStackTrace(); 
            } 
        } 

Problem :- Now I need to add a editable checkbox in-front of each row in the table.

Please help.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Partha Chetry
  • 136
  • 1
  • 9
  • I removed the iText tag, because I don't see anything that is related to PDF. Moreover: `PdfGraphics2D` (the iText class that can render Swing objects to PDF) doesn't support interactive form fields. – Bruno Lowagie Jan 03 '15 at 16:47
  • `I need to add a editable checkbox in-front of each row in the table.` I'm guessing this question is about adding an extra column to the table that is not found in the Excel file. Before your loops that create the "header" and "d" Vectors, you need to add your Boolean information. So for the header you might do: `header.add("Select");` and for each row: `d.add( Boolean.FALSE );`. Then you would need to set the default renderer for the first column of the table by updating the `TableColumn` of the `TableColumnModel` using `table.getDefaultRenderer(Boolean.Class)` – camickr Jan 03 '15 at 17:16
  • @BrunoLowagie : thank you .. indeed there was no need of iText tag – Partha Chetry Jan 03 '15 at 17:18
  • @camickr :- thank you for the comment ... but can you please provide a code snippet please !!! – Partha Chetry Jan 03 '15 at 17:19
  • @camickr : i got a new column in my table but its not a checkbox ... but it has all entries as false ... i am new to swing .. so please help – Partha Chetry Jan 03 '15 at 17:36
  • @ParthaChetry, a more complete answer has been added. – camickr Jan 03 '15 at 20:06

1 Answers1

2

I need to add a editable checkbox in-front of each row in the table.

Before your loops that create the "header" and "d" Vectors, you need to add your Boolean information.

So for the header you might do:

headers.clear(); 
header.add("Select"); 

and for each row:

Vector d = new Vector(); 
d.add( Boolean.FALSE );. 

i got a new column in my table but its not a checkbox

Then you would need to set the default renderer for the first column of the table by updating the TableColumn of the TableColumnModel using the default renderer for the Boolean class:

TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellRenderer( table.getDefaultRenderer( Boolean.class ) );

i am new to swing

Start with the Swing tutorial on [How to Use Table] (http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) for the basics of renderers.

Edit:

A simple SSCCE that demonstrate the solution:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        Vector<String> header = new Vector<String>();
        header.add("Select");
        header.add("Column1");
        header.add("Column2");
        header.add("Column3");

        Vector<Vector<Object>> data = new Vector<Vector<Object>>();

        for (int row = 0; row < 5; row++)
        {
            Vector<Object> d = new Vector<Object>();
            d.add( Boolean.FALSE );

            for (int column = 0; column < 3; column++)
            {
                d.add(row + " : " + column);
            }

            data.add(d);
        }

        DefaultTableModel model = new DefaultTableModel(data, header);
        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        TableColumn tc = table.getColumnModel().getColumn(0);
        tc.setCellRenderer( table.getDefaultRenderer( Boolean.class ) );
        tc.setCellEditor( table.getDefaultEditor( Boolean.class ) );

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new SSCCE() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}
camickr
  • 321,443
  • 19
  • 166
  • 288
  • :- ArrayIndexOutOfBoundsException at line "TableColumn tc = table.getColumnModel().getColumn(0);" – Partha Chetry Jan 03 '15 at 20:16
  • @ParthaChetry, you have to do this AFTER you add the TableModel to the table. The TableColumns can only be created once the table knows how many columns are in the TableModel. – camickr Jan 03 '15 at 20:40
  • :- thanks for you help but it doesn't seem to work ... i added the code after "table.setModel(model);" – Partha Chetry Jan 03 '15 at 21:03
  • @ParthaChetry `it doesn't seem to work`. When something doesn't work then post a proper [SSCCE](http://sscce.org/) that demonstrates the problem. Since we don't have access to your Excel data, the SSCCE should NOT contain logic related to that. Instead the SSCCE should demonstrate the "concept" of what you are trying to do. I posted a SSCCE that shows that the concept does work. I don't know how your code is different. – camickr Jan 03 '15 at 21:36
  • I will keep that it mind ... however i got it working now .. thanks for you help ... next i need to make the checkbox editable :) – Partha Chetry Jan 03 '15 at 21:47
  • @ParthaChetry `next i need to make the checkbox editable' - and my example shows how to do that. Did you not even test my example? – camickr Jan 03 '15 at 22:03