JTable with column spanning

Hi
Can anyone plz help me in creating a JTable which can span different columns in different rows.
Like i want the first row to be with 5 columns, second row to be with 3 columns and 3rd row to be with 4 columns. Can anyone plz help me in this.
Thanks

Look here
http://www2.gol.com/users/tame/swing/examples/SwingExamples.html

Similar Messages

  • Print JTable with column heading

    Hi,
    I'm very new to this JTable. I'm try to print a Jtable using the print() function (from JDK 1.5)
    JTable.print(JTable.PrintMode.FIT_WIDTH, new MessageFormat(
    _tabledata.getTitle() ),
    new MessageFormat("Page {0,number}"));
    The problem I have is that some time it print and other time it doens't print. Also, if it doesn't print, then the program become very slow or not respond. Is that the probelm with the new JDK or am I doing something wrong?
    Thanks for you help.

    Don't rely on JTable.print() methods too much.
    Sadly Sun didn't think anyone would need to print anything from java so support was added late and half heartedly (programmers hate printing stuff)
    If you are new to java you need to focus on something simpler than printing documents; unfortunatly printing is a tedious burdonsome task for experreineced developers
    for example: learn how to output your data from a table into an HTML formate/file; you can build beautiful reports/printouts easily and view them in java components easily but you will probably want to print them from a browser.
    Even if you find a class or two to help with your printing efforts on the net you will find you need to know many other generic complicated aspects of java to continue
    Sean

  • Column span and crashing

    Hi,
    Is anyone else facing this kind of problem? I have a page with various columns (three). The columns are hosting a narrow, but long table. The introductory paragraphs (title and legend) are spanned across the columns.
    Each time I do any edit (applying a text style, deleting a line) InDesign freezes. I get this kind of error in the Console:
    12/06/10 13:45:18 [0x0-0x36d36d].com.apple.Safari[30282] Sat Jun 12 13:45:18 MacBook-Pro-di-PaoloT.local Safari[30282] <Error>: CGImageDestinationCreate destination parameter is nil
    12/06/10 13:45:18 [0x0-0x36d36d].com.apple.Safari[30282]  
    12/06/10 13:46:56 /usr/sbin/spindump[91509] process 91490 is being monitored
    12/06/10 13:46:57 /usr/sbin/spindump[91509] process 91490 is being force quit
    12/06/10 13:46:59 kernel IOHIDSystem::relativePointerEventGated: Capping VBL time to 20000000 (was 26824595)
    12/06/10 13:47:03 com.apple.launchd[169] ([0x0-0x528127c].com.adobe.InDesign[91490]) Exited: Terminated
    12/06/10 13:47:29 SubmitReport[91514] missing kCRProblemReportProblemTypeKey
    12/06/10 13:47:31 /usr/sbin/ocspd[91517] starting
    12/06/10 13:47:33 SubmitReport[91514] Submitted compressed hang report for Adobe InDesign CS5
    12/06/10 13:50:32 /usr/sbin/spindump[91527] process 91518 is being monitored
    12/06/10 13:50:34 /usr/sbin/spindump[91527] process 91518 is being force quit
    12/06/10 13:50:38 com.apple.launchd[169] ([0x0-0x5287282].com.adobe.InDesign[91518]) Exited: Terminated
    I reported this to Adobe, but I would see if anyoady has a workaround. I solved using the old way (separated text frames), but this prevents one of the features of CS5.
    Paolo

    I tried to reproduce the crashing that Eugene reported, and could not. I have a decent C2D with 4 gigs of RAM, and with those specs all I could do was experience slightly-slower-than-expected performance when working with column-spanning headers. However, when I start my Ubuntu VM, and start the processes that cause it to consume about 2 gigs of RAM, then my system specs degrade to the minimum RAM acceptable to ID (just more than 2 gigs) and I start experiencing multi-second delays.
    My hunch is that this particular feature requires more resources than the minimum spec from Adobe... or that a buggy plugin is crashing when it doesn't do garbage collection quick enough to prevent the host system from running out of available RAM. Just a hunch, I'm not a developer at all, but the whole thing smells like a memory leak to me. I could never get it to crash, though, so perhaps I'm only muddying the path with my posts about my attempts to reproduce it.

  • JTable (dynamic columns)

    Well guys, voil� my problem...
    I've a Person class, who has some methods to get the person information, like getName(), getAge(), getAdresse(), etc... I would display the information of all the persons in the diary in a JTable... Ok, it's all right, i made a class who extends AbstractModelTable, overriding the getValueAt(int, int) with a switch:
    // private static final int COLUMN_NAME = 0;
    // private static final int COLUMN_NAME = 1;
    switch (column) {
            case COLUMN_NAME:
                  return cols[rowIndex].getName();
             case COLUMN_AGE:
                   return cols[rowIndex].getAge();
              default:
                    return;
    }The code it's something like that... I'm sorry i don't show the code, i've not the source here!
    It works very fine!... But now, i want to let the user choose witch columns to display...
    I made a lot of tries, but i could not get the solution... The only one thing I could, was to eliminate the columns with zero value in the conf file, but the headers were not in the correct order!... And there's another problem too, when I switch the columnIndex, if it equals to COLUMN_EMAIL = 15 means that JTree is getting the value of the 15th column, but if the user had removed the 2 column for example, the 15th column is not more the email column, it's the 15+1 columns :S... is it clair? I think it's a little difficult to explain, and as you see, i don't speak english very well :P...
    Summary: I would create a class extending JTable with columns configurables, i mean, let the user choose witch columns should be showed... Any idea ?... I can avoid the JTable component, so If you've another solution, it will be ok...
    Greetings and thank you guys...

    Your requirement is very general so we can't give you an exact solution, but I can try explaining how JTable works.
    The TableModel is used to store the data. The JTable is used to display the data. When a table is first created using a TableModel a TableColumnModel is created. Each TableColumn in the TableColumnModel maps directly to a column in the TableModel.
    Now what happens if the user moves column 15 to the first column in the table? The data hasn't changed, only the view of the data has changed. So even though the column is in column 0 of the table, the data must still come from column 15 in the TableModel. The TableColumns of the TableColumnModel do the mapping for you so you don't need to worry about the reordering of columns.
    However, if you have some code in your program that accesses the data directly, then you need to be aware of this situation. Fortunately JTable has some methods to make this mapping easy.
    table.getValueAt(...) will get data from the requested column in the view of the table
    table.getModel().getValueAt(...) will get data form the requested column in the TableModel.
    You can also do the mapping between "view" and "model" columns using the methods:
    table.convertColumnIndexToModel(...)
    table.convertColumnIndexToView(...) So what does this mean with dynamic columns? Well, you would build your table normally, then you would remove the TableColumns from the TableColumnModel that the user does not want to see.
    The following example is so code I wrote a while ago that will help in manipulating the TableColumnModel. Right click on the TableHeader to see the visible/hidden status of each column:
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableColumnManager implements MouseListener, ActionListener
         private static final String HIDDEN_COLUMN = "HiddenColumn:";
         //  Reference to the Singleton instance of this class
         private static TableColumnManager singleton;
         *  Use a private constructor so we can create a Singleton.
         private TableColumnManager()
         *  Get the Singleton instance of the <code>TableColumnManager</code>.
         *  @return  the Singlton instance of <code>TableColumnManager</code>
         private static TableColumnManager getInstance()
              if (singleton == null)
                   singleton = new TableColumnManager();
              return singleton;
         *  Add support for the management of visible <code>TableColumns</code>
         *  for a given <code>JTable</code>.
         *  @param  table the table to provide support for
         public static void install(JTable table)
              table.getTableHeader().addMouseListener( getInstance() );
         *  Remove support for the management of visible <code>TableColumns</code>
         *  for a given <code>JTable</code>.
         *  @param  table the table to remove support from
         public static void uninstall(JTable table)
              table.getTableHeader().removeMouseListener( getInstance() );
         *  Hide a column from view in the table.
         *  @param  table        the table from which the column is removed
         *  @param  modelColumn  the column index from the TableModel
         *                       of the column to be removed
         public static void hideColumn(JTable table, int modelColumn)
              int viewColumn = table.convertColumnIndexToView( modelColumn );
              if (viewColumn != -1)
                   TableColumn column = table.getColumnModel().getColumn(viewColumn);
                   hideColumn(table, column);
         *  Hide a column from view in the table.
         *  @param  table        the table from which the column is removed
         *  @param  columnName   the column name of the column to be removed
         public static void hideColumn(JTable table, String columnName)
              try
                   TableColumnModel tcm = table.getColumnModel();
                   int index = tcm.getColumnIndex( columnName );
                   TableColumn column = tcm.getColumn( index );
                   hideColumn(table, column);
              catch(IllegalArgumentException e) {}
         *  Hide a column from view in the table.
         *  @param  table   the table from which the column is removed
         *  @param  column  the TableColumn to be removed from the
         *                  TableColumnModel of the specified table
         public static void hideColumn(JTable table, TableColumn column)
              table.getColumnModel().removeColumn( column );
              //  Save the column so it can be redisplayed
              ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
              if (list == null)
                   list = new ArrayList();
                   table.putClientProperty(HIDDEN_COLUMN, list);
              list.add(column);
         *  Show a hidden column in the table.
         *  @param  table        the table to which the column is added
         *  @param  modelColumn  the column index from the <code>TableModel</code>
         *                       of the column to be added
         public static void showColumn(JTable table, int modelColumn)
              ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
              if (list == null) return;
              ListIterator it = list.listIterator();
              while (it.hasNext())
                   TableColumn column = (TableColumn)it.next();
                   if (column.getModelIndex() == modelColumn)
                        table.getColumnModel().addColumn( column );
                        it.remove();
                        break;
         *  Show a hidden column in the table.
         *  @param  table        the table to which the column is added
         *  @param  columnName   the column name from the <code>TableModel</code>
         *                       of the column to be added
         public static void showColumn(JTable table, String columnName)
              ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
              if (list == null) return;
              ListIterator it = list.listIterator();
              while (it.hasNext())
                   TableColumn column = (TableColumn)it.next();
                   if (column.getHeaderValue().equals(columnName))
                        table.getColumnModel().addColumn( column );
                        it.remove();
                        break;
         //  Implement the MouseListener
         public void mousePressed(MouseEvent e)
              checkForPopup( e );
         public void mouseReleased(MouseEvent e)
              checkForPopup( e );
         public void mouseClicked(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         private void checkForPopup(MouseEvent e)
              if (e.isPopupTrigger())
                   JTableHeader header = (JTableHeader)e.getComponent();
                   int column = header.columnAtPoint( e.getPoint() );
                   showPopup(header.getTable(), column);
         *  Show a hidden column in the table.
         *  @param  table        the table to which the column is added
         *  @param  columnName   the column name from the <code>TableModel</code>
         *                       of the column to be added
         public static void showPopup(JTable table, int tableColumn)
              int columns = table.getModel().getColumnCount();
              JCheckBoxMenuItem[] items = new JCheckBoxMenuItem[columns];
              //  Create menu items for hidden columns
                 ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
                 if (list != null)
                   ListIterator it = list.listIterator();
                   while (it.hasNext())
                        TableColumn column = (TableColumn)it.next();
                        String columnName = column.getHeaderValue().toString();
                        JCheckBoxMenuItem item = new JCheckBoxMenuItem( columnName );
                        item.setSelected( false );
                        item.addActionListener(getInstance());
                        items[column.getModelIndex()] = item;
              //  Create menu items for visible columns
              TableColumnModel columnModel = table.getColumnModel();
              int columnCount = columnModel.getColumnCount();
              for (int i = 0; i < columnCount; i++)
                   TableColumn column = columnModel.getColumn(i);
                   String columnName = column.getHeaderValue().toString();
                   JCheckBoxMenuItem item = new JCheckBoxMenuItem( columnName );
                   item.setSelected( true );
                   item.addActionListener(getInstance());
                   items[column.getModelIndex()] = item;
              //  Create popup menu from array of menu items.
              //  Override the setSelected method to select the
              //  specified menu item. (ie. this is a bug fix)
              JPopupMenu popup = new JPopupMenu()
                   public void setSelected(Component sel)
                        int index = getComponentIndex( sel );
                        getSelectionModel().setSelectedIndex(index);
                        final MenuElement me[] = new MenuElement[2];
                        me[0]=(MenuElement)this;
                        me[1]=getSubElements()[index];
                        SwingUtilities.invokeLater(new Runnable()
                             public void run()
                                  MenuSelectionManager.defaultManager()
                                       .setSelectedPath(me);
              for (int i = 0; i < items.length; i++)
                   if (items[i] != null)
                        popup.add( items[i] );
              //  Display the popup below the TableHeader
              JTableHeader header = table.getTableHeader();
              Rectangle r = header.getHeaderRect( tableColumn );
              popup.show(header, r.x, r.height);
              int modelColumn = table.convertColumnIndexToModel( tableColumn );
              popup.setSelected( items[modelColumn] );
         *  Responsible for processing the ActionEvent. A column will either be
         *  added to the table or removed from the table depending on the state
         *  of the menu item that was clicked.
         * @param event the ActionEvent.
         public void actionPerformed(ActionEvent event)
              JMenuItem item = (JMenuItem)event.getSource();
              JPopupMenu popup = (JPopupMenu)item.getParent();
              JTableHeader header = (JTableHeader)popup.getInvoker();
              JTable table = header.getTable();
              if (item.isSelected())
                   showColumn(table, item.getText());
              else
                   hideColumn(table, item.getText());
         public static void main(String[] args)
              JTable table = new JTable( new DefaultTableModel(5, 10) );
              TableColumnManager.install(table);
              TableColumnManager.hideColumn(table, 2);
              TableColumnManager.hideColumn(table, "E");
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( new JScrollPane(table) );
              frame.pack();
              frame.setVisible( true );
    }Hopefully I've made some sense.

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Can we create JTable with multiple rows with varying number of columns ?

    Hi All,
    I came across a very typical problem related to JTable. My requirement is that cells should be added dynamically to the JTable. I create a JTable with initial size of 1,7 (row, columns) size. Once the 7 columns are filled with data, a new row should be created. But the requirement is, the new row i.e. second row should have only one cell in it initially. The number of cells should increase dynamically as the data is entered. The table is automatically taking the size of its previous row when new row is added. I tried by using setColumnCount() to change the number of columns to '1' for the second row but the same is getting applied to the first row also.
    So can you please help me out in this regard ? Is it possible to create a JTable of uneven size i.e. multiple rows with varying number of columns in each row ?
    Thanks in Advance.

    Well a JTable is always going to paint the same number of columns for each row. Anything is possible if you want to rewrite the JTable UI to do this, but I wouldn't recommend it. (I certainly don't know how to do it).
    A simpler solution might be to override the isCellEditable(...) method of JTable and prevent editing of column 2 until data in column 1 has been entered etc., etc. You may also want to provide a custom renderer that renderers the empty column differently, maybe with a grey color instead of a white color.

  • Horizontal scrolling in a JTable with fixed-size columns

    Hello,
    I have come to a roadblock concerning the following issue. Perhaps someone can share their ideas...
    I have a JTable with three fixed-size columns. I implemented a JScrollPane with vertical and horizontal scrolling. However, the text inserted into the last column is too long to fit in the specified column width. I would like to be able to scroll the table so that I can view all of the text in the last column. Right now, the text cuts off and ends with three dots (...). Is there a way in which a horizontal scroll bar can be implemented to view all the text in the last column?
    Here is a portion of my code:
    num_of_rows_Table2 = (int) Math.pow(3, num_of_vars);
    String[] colunmNames_Table2 = {"Decimal Identifier", "Ternary Identifier", "Cancellation of nonimplicants"};
    dataModel2 = new DefaultTableModel(colunmNames_Table2, num_of_rows_Table2);
    SpaceOfTermsTable = new JTable(dataModel2);
    for (int z = 0; z < num_of_rows_Table2; z++)
    SpaceOfTermsTable.setRowHeight(z, row_height);
    SpaceOfTermsTable.setBounds(new Rectangle(x1_Table2, y1_Table2, width_of_pane2, height_pane2));
    SpaceOfTermsTable.getTableHeader().setReorderingAllowed(false);
    for (int i = 0; i < 2; i++)
    TableColumn col = SpaceOfTermsTable.getColumnModel().getColumn(i);
    col.setMinWidth(colwidth_Table2);
    col.setMaxWidth(colwidth_Table2);
    col.setPreferredWidth(colwidth_Table2);
    TableColumn lastcol = SpaceOfTermsTable.getColumnModel().getColumn(2); lastcol.setMinWidth(lastcol_Table2);
    lastcol.setMaxWidth(lastcol_Table2);
    lastcol.setPreferredWidth(lastcol_Table2);
    SpaceOfTermsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    scrollPanel2 = new JScrollPane(SpaceOfTermsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPanel2.setAutoscrolls(true);
    scrollPanel2.setBounds(new Rectangle(x1_Table2, y1_Table2, width_of_pane2, height_pane2));
    Thanks in advance for all of the help!

    Hi, I hava a similar problem than yours - can you tell me how you sorted out yer's?

  • Creating a JTable with resizeable columns and Horizontal Scrollbar

    Hi,
    I would like to create a JTable with about 24 columns in it. The problem is, my ViewPort in my JScrollPane is about 3-400pixels wide, and the JTable tries to cram itself into the ViewPort. This makes the columns too tiny to read. I'd like it to do something a little more sensible, like use the PreferredSize of the columns. Can anyone point me in the right direction to keep JTable from creating scrunched up little columns, so that it creates columns that are at least partially readable? Thanks.
    BTW, I suppose I could set NO_AUTO_RESIZE but I would rather not do that. I like being able to resize columns. Basically what I want to do is control the JTable's width and not worry about the ViewPort's width.

    This made it impossible to resize columns. Works fine for me:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableHorizontal extends JFrame
        public TableHorizontal()
            JTable table = new JTable(5, 10);
            table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            table.getColumnModel().getColumn(0).setPreferredWidth(10);
            table.getColumnModel().getColumn(1).setPreferredWidth(20);
            table.getColumnModel().getColumn(2).setPreferredWidth(30);
            table.getColumnModel().getColumn(3).setPreferredWidth(40);
            table.getColumnModel().getColumn(4).setPreferredWidth(50);
        public static void main(String[] args)
            TableHorizontal frame = new TableHorizontal();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • JTable with a JCheckBox in a header column

    Hi everybody,
    I have implemented a JTable with a JCheckbox in one of the header columns. For this I have used the following code from the Internet for rendering the table cell:
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent;
         protected int column;
         protected boolean mousePressed = false;
         public CheckBoxColumnHeader(ItemListener itemListener) {   
              rendererComponent = this;
              rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (table != null) {     
                   JTableHeader header = (ExtendedJTableHeader)table.getTableHeader();
                   if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());
                        rendererComponent.setBackground(header.getBackground());
                        rendererComponent.setFont(header.getFont());
                        header.addMouseListener(rendererComponent);
              setColumn(column);
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));
              return rendererComponent;
    From a technical point of view, the checkbox works as expected. However, I have problems with the graphical layout of the checkbox in the header column:
    1) The checkbox seems to be bigger than the height of the header column. It overlays the border lines of the table. When I increase the preferred size of the header row, the checkbox also increases its size and still overlays the table border lines.
    2) The checkbox has a diffferent background shading than the other columns in the header.
    Any help for solving these two layout problems are greatly appreciated.
    Thanks, Walter

    Hi,
    here is now the complete code
    package main;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Arrays;
    import java.util.Vector;
    import javax.swing.table.*;
    * <p>�berschrift: </p>
    * <p>Beschreibung: </p>
    * <p>Copyright: Copyright (c) 2007</p>
    * <p>Organisation: </p>
    * @author unbekannt
    * @version 1.0
    public class MainFrame extends JFrame {
         JTable table3;
         JScrollPane scp3; 
      //Den Frame konstruieren
      public MainFrame() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      //Initialisierung der Komponenten
      private void jbInit() throws Exception  {
        this.setSize(new Dimension(500, 320));
        this.setTitle("Action List");
        Vector<Object> rowData = new Vector<Object>();
        for (int i=0; i<3; i++) {
             Vector<Object> colData = new Vector<Object>(Arrays.asList("Data R" + i + "C0", "Data R" + i + "C1", "Data R" + i +"C2", (i%2 == 0) ? Boolean.TRUE : Boolean.FALSE));
             rowData.add(colData);
        Vector<Object> hdr = new Vector<Object>(Arrays.asList("Column 0", "Column 1", "Column 2 (MyO)", "Column 3"));
         DefaultTableModel tableM = new DefaultTableModel(rowData, hdr);
        table3 = new JTable(tableM);
        TableColumn tc = table3.getColumnModel().getColumn(3);   
        tc.setCellEditor(table3.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(table3.getDefaultRenderer(Boolean.class));
        tc.setHeaderRenderer(new CheckBoxColumnHeader(table3, new MyItemListener()));
        scp3 = new JScrollPane(table3);
         scp3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         scp3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
         this.add(scp3);
      //�berschrieben, so dass eine Beendigung beim Schlie�en des Fensters m�glich ist
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent; 
         protected int column; 
         protected boolean mousePressed = false; 
         protected JTable myTable;
         public CheckBoxColumnHeader(JTable t, ItemListener itemListener) {   
              rendererComponent = this;   
              rendererComponent.addItemListener(itemListener);
              myTable = t;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              JTableHeader header = null;
              if (table != null) {     
                   header = (JTableHeader)table.getTableHeader();     
                    if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());       
                        rendererComponent.setBackground(header.getBackground());       
                        rendererComponent.setFont(header.getFont());       
                        header.addMouseListener(rendererComponent); 
              setColumn(column);   
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));   
              return rendererComponent; 
         protected void setColumn(int column) {this.column = column; } 
         public int getColumn() {return column; }
         protected void handleClickEvent(MouseEvent e) {
              if (mousePressed) {
                   mousePressed=false;     
                   JTableHeader header = (JTableHeader)(e.getSource());
                   JTable tableView = header.getTable();
                   TableColumnModel columnModel = tableView.getColumnModel();
                   int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                   int column = tableView.convertColumnIndexToModel(viewColumn);
                   if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
                        doClick();
         public void mouseClicked(MouseEvent e) {   
              handleClickEvent(e);   
              ((JTableHeader)e.getSource()).repaint(); 
         public void mousePressed(MouseEvent e) {   
              mousePressed = true; 
         public void mouseReleased(MouseEvent e) {  }
         public void mouseEntered(MouseEvent e) {  }
         public void mouseExited(MouseEvent e) {  }
         public JTable getTable() {return myTable; }
    public class MyItemListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
             CheckBoxColumnHeader source = (CheckBoxColumnHeader)e.getSource();
             if (source instanceof AbstractButton == false) return;
             boolean checked = e.getStateChange() == ItemEvent.SELECTED;
             for (int x = 0, y = source.getTable().getRowCount(); x < y; x++) {
                  source.getTable().setValueAt(new Boolean(checked),x,3);     
    As originally said, the checkbox in the header column overlays the table borders and also has a different background shading than the other header columns.

  • JTable with JCheckbox problems

    Ok so I have a couple of questions. I have a JTable with a column represented as a checkbox.
    1. If I put the checkbox column as the first in the table, the rest of the cells are blank/null. Any idea what the reason is?
    2. What is the best workaround to having draggable columns, meaning icons/checkboxes don't render if you move the columns around?
    3. Does anyone have some links to good resources on JTables and things like custom components in them. I have googled but don't get many good links so would appreciate any help
    Code snippet as follows:
    public class ClobberTableCellRenderer implements TableCellRenderer
    private JPanel renderPanel = new JPanel(new BorderLayout());
    private JLabel renderLbl = new JLabel("");
    private JCheckBox checked = new JCheckBox();
    private Icon successIcon;
    private Icon errorIcon;
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column)
    String columnName = table.getModel().getColumnName(column);
    if (value == null)
    return null;
    else if ("Status".equals(columnName) && "ok".equals(value))
    renderLbl.setIcon(successIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Status".equals(columnName) && "error".equals(value))
    renderLbl.setIcon(errorIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Active".equals(columnName))
    renderLbl.setText("");
    renderPanel.add(checked);
    renderPanel.setBackground(Color.white);
    else
    renderLbl.setHorizontalAlignment(value instanceof Date || value instanceof Number ? JLabel.RIGHT : JLabel.LEFT);
    renderLbl.setIcon(null);
    renderLbl.setText(value instanceof Date ? df.format((Date)value) : value.toString());
    renderLbl.setToolTipText(null);
    renderPanel.setToolTipText(null);
    renderPanel.remove(checked);
    if (isSelected)
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.selectionBackground"));
    else
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.background"));
    return renderPanel;
    }

    Hi :) I have also worked on JTables and JCheckBoxes before. This article
    helped me a lot: http://www-128.ibm.com/developerworks/java/library/j-jtable/

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • How do I create a jtable with horizontalScroll bar,plz help me!

    I created a jtable component,Because my table's columns has 50 items,I must need a horizontalScroll Bar.
    but I find the horizontalScroll don't display,when I add record to the jtable,the verticalScroll Bar is showed.How do I create a jtable with horizontalScroll bar,can u help me!
    thank you in advance!

    Hi,
    This piece of code will help :
         //Get the Component Adapter for taking action against resizing of
    //of Panel
    ComponentListenerAdapter componentAdapter =
    new ComponentListenerAdapter()
    //Get the scrollbar or remove the scrollbar upon resizing
    protected void resizingAction()
    Container tableParent = table.getParent();
    if (tableParent instanceof JViewport)
    //Check if the width of the Table Parent Container
    //is less than the Preferred Size of the Table
    if (tableParent.getSize().getWidth() <
    table.getPreferredSize().getWidth())
    //Yes it is
    //Remove the Auton Resize Function and get the
    //Scrollbar
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
    else
    //No it is not
    //Get the Auto Resize functionality back in place
    table.setAutoResizeMode(
    JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    //Add the component Adapter to the Table Header
    table.getTableHeader().addComponentListener(componentAdapter);
    private abstract class ComponentListenerAdapter
    implements ComponentListener
              * The <code>componentHidden<code> method has no implementation
              * @param event The Event occured whenever the Component is Hidden
              public void componentHidden(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentShown</code> method has no implementation
              * @param event The Event occured whenever the Component is Shown
              public void componentShown(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentMoved</code> method has no implementation
              * @param event The Event occured whenever the Component is Moved
              public void componentMoved(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentResized</code> method is invoked whenever the
              * component is resized. The resizing action will set the columns and
              * scrollbar to act properly
              * @param event The Event occured whenever the Component is Resized
              public void componentResized(ComponentEvent event)
                   resizingAction();
    * Subclasses of this override this method to determine what is to be
    * done once the Component has been Resized
    protected abstract void resizingAction();
    Hope this will solve all your JTable horizontal resizing problems
    --j                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JTable Moving Columns and keeping the index for re-display

    I have a JTable with data. The data in the table is refreshed every two minutes. The user is allowed to move the columns around, but when the refresh happens, the columns go back to their original layout. I have a TableColumnModelListener attached to the table and I know that there is a columnMoved method and I can capture the the "toIndex" but where do I set this new index in the model?

    The TableColumnModel controls the ordering of the the Table columns.
    When you use the setModel(...) method the fireTableStructureDataChanged() event is fired. This causes the TableColumnModel to be recreated. However you can turn this off, assuming the structure of the TableModel is the same, and only the data has changed. After creating the table the first time you can use:
    table.setAutoCreateColumnsFromModel( false );

  • JTable with ImageIcons does not react to even handling

    Hi.
    I have a populated JTable with ONLY ImageIcons in it. I need to generate event responses on mouseClicks. However, any event listener I associate with this, nothing seems to be happening.
    (Somehow, I'm guess the ImageIcons - which are rendered on a JLabel, are/is the source of all troubles!!)
    The code is below :
    import java.io.File;
    import java.awt.Point;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Container;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    *     Entry point for the Images Table.
    *     @author Raj Gaurav
    public class SpecialCharacterDialog extends JDialog{
         String collectionString[] = null;
         ImageIcon suite[] = null;
         public SpecialCharacterDialog() {
              Container contentPane = getContentPane();
              //     Create the Table Model and create the Table from the model
              MyTableModel model = new MyTableModel();
              JTable table = new JTable(model);
              table.setDefaultRenderer(ImageIcon.class, new CustomCellRenderer());
              table.setCellSelectionEnabled(true);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
              //     Add the table to the contentPane
              JScrollPane pane = new JScrollPane(table);
              contentPane.add(pane);
    *     This class contains all the DATA information, the ImageIcons
    *     needed for display.
    class SymbolCollection {
         final static int NUMBER_OF_COLUMNS = 15;
         private String collectionString[] = null;
         private ImageIcon suite[] = null;
         *     Constructor : Initialises all the ImageIcon and their Names.
         public SymbolCollection() {
              File f = new File("C:\\Test\\Images");
              collectionString = f.list();
              int numberOfImages = collectionString.length;
              suite = new ImageIcon[numberOfImages];
              for(int i = 0;i < numberOfImages; i++) {
                   suite[i] = new ImageIcon("C:\\Test\\images" + File.separator + collectionString);
         *     Returns the total number of images in "images" folder.
         public int getTotalNumberOfImages() {
              return suite.length;
         *     Returns the target ImageIcon.
         public ImageIcon getImageIconAt(int number) {
              return suite[number];
         *     Returns the target ImageIcon Name.
         public String getImageIconNameAt(int number) {
              return collectionString[number];
         *     Returns an array of ALL the ImageIcons available.
         public ImageIcon[] getImageIcons() {
              return suite;
         *     Returns an array of ALL the ImageIcon names available
         public String[] getImageIconNames() {
              return collectionString;
         *     Returns TRUE for all cells
         public boolean isEditable(int row, int col) {
              return true;
    *     Defines the table model for the tabel.
    class MyTableModel extends AbstractTableModel {
         private SymbolCollection collection = null;
         private Object data[][] = null;
         *     Constructor for the TableModel. Initialises the "data" field for table.
         public MyTableModel() {
              int countOfImages = 0;
              collection = new SymbolCollection();
              data = new Object[getRowCount()][SymbolCollection.NUMBER_OF_COLUMNS];
              for(int i = 0; i < getRowCount(); i++) {
                   for(int j = 0; j < SymbolCollection.NUMBER_OF_COLUMNS; j++) {
                        if(countOfImages == collection.getTotalNumberOfImages()) {
                             break;
                        data[i][j] = collection.getImageIconAt(countOfImages);
                        countOfImages++;
         *     Returns the number of rows for this table.
         *     It is calculated as : TotalNumber/NumberOfColumns if remainder is ZERO or,
         *                              TotalNumber/NumberOfColumns + 1 if not.
         public int getRowCount() {
              int numberOfRows = collection.getTotalNumberOfImages()/SymbolCollection.NUMBER_OF_COLUMNS;
              if(numberOfRows == 0) {
                   return numberOfRows;
              else {
                   return numberOfRows + 1;
         *     Returns the number of Columns for this table
         public int getColumnCount() {
              return SymbolCollection.NUMBER_OF_COLUMNS;
         *     Returns the CLASS data type for this table
         public Class getColumnClass(int col) {
              return collection.getImageIconAt(0).getClass();
         *     Returns the table data at (row, col).
         public Object getValueAt(int row, int col) {
              return data[row][col];
    *     Renders the table to display images in individual cells
    class CustomCellRenderer extends JLabel implements TableCellRenderer {
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
              setIcon((ImageIcon)value);
              return this;

    Hi.
    I have a populated JTable with ONLY ImageIcons in it. I need to generate event responses on mouseClicks. However, any event listener I associate with this, nothing seems to be happening.
    (Somehow, I'm guess the ImageIcons - which are rendered on a JLabel, are/is the source of all troubles!!)
    The code is below :
    import java.io.File;
    import java.awt.Point;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Container;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    *     Entry point for the Images Table.
    *     @author Raj Gaurav
    public class SpecialCharacterDialog extends JDialog{
         String collectionString[] = null;
         ImageIcon suite[] = null;
         public SpecialCharacterDialog() {
              Container contentPane = getContentPane();
              //     Create the Table Model and create the Table from the model
              MyTableModel model = new MyTableModel();
              JTable table = new JTable(model);
              table.setDefaultRenderer(ImageIcon.class, new CustomCellRenderer());
              table.setCellSelectionEnabled(true);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
              //     Add the table to the contentPane
              JScrollPane pane = new JScrollPane(table);
              contentPane.add(pane);
    *     This class contains all the DATA information, the ImageIcons
    *     needed for display.
    class SymbolCollection {
         final static int NUMBER_OF_COLUMNS = 15;
         private String collectionString[] = null;
         private ImageIcon suite[] = null;
         *     Constructor : Initialises all the ImageIcon and their Names.
         public SymbolCollection() {
              File f = new File("C:\\Test\\Images");
              collectionString = f.list();
              int numberOfImages = collectionString.length;
              suite = new ImageIcon[numberOfImages];
              for(int i = 0;i < numberOfImages; i++) {
                   suite[i] = new ImageIcon("C:\\Test\\images" + File.separator + collectionString);
         *     Returns the total number of images in "images" folder.
         public int getTotalNumberOfImages() {
              return suite.length;
         *     Returns the target ImageIcon.
         public ImageIcon getImageIconAt(int number) {
              return suite[number];
         *     Returns the target ImageIcon Name.
         public String getImageIconNameAt(int number) {
              return collectionString[number];
         *     Returns an array of ALL the ImageIcons available.
         public ImageIcon[] getImageIcons() {
              return suite;
         *     Returns an array of ALL the ImageIcon names available
         public String[] getImageIconNames() {
              return collectionString;
         *     Returns TRUE for all cells
         public boolean isEditable(int row, int col) {
              return true;
    *     Defines the table model for the tabel.
    class MyTableModel extends AbstractTableModel {
         private SymbolCollection collection = null;
         private Object data[][] = null;
         *     Constructor for the TableModel. Initialises the "data" field for table.
         public MyTableModel() {
              int countOfImages = 0;
              collection = new SymbolCollection();
              data = new Object[getRowCount()][SymbolCollection.NUMBER_OF_COLUMNS];
              for(int i = 0; i < getRowCount(); i++) {
                   for(int j = 0; j < SymbolCollection.NUMBER_OF_COLUMNS; j++) {
                        if(countOfImages == collection.getTotalNumberOfImages()) {
                             break;
                        data[i][j] = collection.getImageIconAt(countOfImages);
                        countOfImages++;
         *     Returns the number of rows for this table.
         *     It is calculated as : TotalNumber/NumberOfColumns if remainder is ZERO or,
         *                              TotalNumber/NumberOfColumns + 1 if not.
         public int getRowCount() {
              int numberOfRows = collection.getTotalNumberOfImages()/SymbolCollection.NUMBER_OF_COLUMNS;
              if(numberOfRows == 0) {
                   return numberOfRows;
              else {
                   return numberOfRows + 1;
         *     Returns the number of Columns for this table
         public int getColumnCount() {
              return SymbolCollection.NUMBER_OF_COLUMNS;
         *     Returns the CLASS data type for this table
         public Class getColumnClass(int col) {
              return collection.getImageIconAt(0).getClass();
         *     Returns the table data at (row, col).
         public Object getValueAt(int row, int col) {
              return data[row][col];
    *     Renders the table to display images in individual cells
    class CustomCellRenderer extends JLabel implements TableCellRenderer {
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
              setIcon((ImageIcon)value);
              return this;

  • Print Jtable with multiline header?

    i want to print jtable with multi-lines header and footer
    using the print function that takes MessageFormat as header and footer
    i used MessageFormat header = new MessageFormat("hello\r\nworld");and i used '\n' only
    but it was printed all in the same line
    thnx in advance

    You can try something on the below lines. Set your custom renderer for the tableheader.
    public class MultiLineHeaderRenderer extends DefaultTableCellRenderer{
            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.setText("<html>a<br>b</html>");
                        return label;
        }Not the best way to do it. And might need to some modifications too to set the font position etc.

Maybe you are looking for

  • What happened to video playback using AirPlay?

    Before upgrading to iOS 6, AirPlay worked seamlessly. Using the iOS-native YouTube app, I was able to have it play on my AppleTV. With that app no longer available, and having downloaded the Google YouTube app, using AirPlay will only allow audio to

  • What is the best uk in car cigarette lighter charger for my ipad 4?

    Do apple produce an in car charger for the ipad 4?

  • N8 Camera focus ?!

    Hey! My camera on N8 doesn't focus at al. Its blurry on the Screen and on the pictures. And the red light before the light works sometimes. Before this problems started so did it work every time. And the focus on camera. I have restored the settings

  • BADI inconcistent called

    Hello friends, Does anyone have an idea on why a certain BADI is inconsistently called during the same process??? I'm trying to post GR using transaction MIGO and been wondering why does the BADI I used (MB_MIGO_BADI) is functioning as expected for t

  • Can't read email attachments that are .doc files

    Can someone help please. My dad has a PC and I have a G4. He sends me .doc and .xls files and I can't open them. I don't have any windows type software for my MAC. What should I do? Thanks for the help. The biggest problem today is trying to open a f