Setting cellSpan in JTable

You most likely are familular with tame's swing examples at http://www2.gol.com/users/tame/swing/examples/SwingExamples.html which have proven most helpful.
In JTable Examples 4 in the Multi-Span Example it is easy to find how tame combines multiple cells into one. The cells are selected after the table is created and then an Action Listener on a button calls cellAtt.combine.
But what if one wants to combine cells based on the data they are using to build the table. So when the tablemodel is being built, that is before we have cellAtt and before we render the table, how can we combine cells.
I tried to capture the number of rows I wanted to span when I built my tablemodel and then when I render cells (getTableCellRendererComponent) if cellAtt instanceof CellSpan I call cellAtt.combine. But this doesn't work.
Sorry no code as it is just to long to make sense here and I am really looking for the theory behind this rather than exatly what code is needed.

JScrollPane scrollPane = new JScrollPane( table );
//scrollPane.add(table); // this is wrongYou never add a component directly to the scrollpane. You either
a) create the scroll pane with the component as a parameter (as you did correctly)
b) set the view of the viewport with your component
JTable table = this.tv.getTable();
AssignmentsTableModel atm = (AssignmentsTableModel)table.getModel();
atm.fireTableDataChanged();
scrollToVisible(table, row, 0); This code makes no sense.
a) The variable row doesn't have a value.
b) Why would clicking on the table header cause you to invoke "fireTableDataChanged"? You haven't changed any of the data.
viewport.scrollRectToVisible(rect);I always invoke the scrollRectToVisible(... ) method on the component added to the scrollpane (ie. the table).
For more help create a [url http://sscce.org]SSCCE, that demonstrates the incorrect behaviour.

Similar Messages

  • How Can I set up a JTable columns?

    Dear All,
    How can I set up my JTable columns to have the amount the user specifies?
    for example when the user types in 50 in JTextField 1 I want the JTables columns to then set to 50.
    How can this be done?
    Thanks
    lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

    As you can see I have tried this, but no success.
    If I am doing something wrong please accept my apology, and address me in the right direction.
    Thanks
    Lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
         ((DefaultTableModel)perstab.getModel()).setColumnCount(Integer.parseInt(name.getText()));
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

  • How to set height of JTable Header ?

    How to set height of JTable Header and set the text to another size ?

    You can set the font of the header as you can for any component. The font will dictate the preferred height of the header. If you don't like the preferred height, you can set that as well.
    // add table to a scroll pane or the header will not appear
    JTable table = new JTable(...);
    container.add(new JScrollPane(table));
    // get a reference to the header, set the font
    JTableHeader header = table.getTableHeader();
    header.setFont(new Font(...));
    // set the preferred height of the header to 50 pixels.
    // the width is ignored by the scroll pane.
    header.setPreferredSize(new Dimension(1, 50));Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • How to set background of jtable in no data?

    How to set background of jtable in no data?
    I use table.setBackground(Color.black) but no successful
    Please help me. thanks very much

    maybe, you don't understand me.
    I have below jtable:
    ============================
    I column1 name l column2 name I
    ============================
    l data l data l
    ============================
    l data l data l
    ============================
    XXX
    ============================
    I wrote:
    table.setBackground(Color.black) then only data area has black colour, but XXX area hasn't black colour.
    How to XXX area also has black colour?
    help me, thanks very much.

  • Setting Focus in JTable

    How can i set the focus to the first editable cell in a JTable?

    how about
    editCellAt(row, column) method at JTable ?

  • Problem in setting focus in JTable

    Hi,
    In my application I am using JTable with a customized table model. The table has two columns. First column has jcombobox as its editor and the second column has the customized editor developed by me. This particular table appears in a wizard. When this wizard page (which contains the above JTable) is shown I set the keyboard focus on the JTable using JTable's requestFocus() method (I even tried with grabFocus()method but got the same result). But the focus does not appear on the JTable. Even none of the cells get the focus. Also no matter how many time I press tab key the focus does not shift to the next component in the page which happens to be a JButton. I have set the next focussable element for the JTable as that JButton. When I manually put the focus on one of the cells by clicking on it and then if I press either arrow key or tab key the focus is lost and it does not go either on the next cell or the JButton.
    If anybody can shed some light on what exactly needs to be done to give proper keyboard navigation for JTable please let me know.
    Regards
    Atul

    Hi Atul,
    I suspect your problem is with your cell renderer. The DefaultTableCellRenderer class has code in the getTableCellRendererComponent method that provides the visual indication as to which cell has the focus. You will want to do something similar in your JPanel-subclassed renderer - perhaps change the border or the background color to indicate whether a cell is selected or not.
    Note also that there is a difference between a cell that has "isSelected" set to true, which indicates that the cell is part of the current selection, and a cell that has "hasFocus" set to true, which indicates that the cell is the last one to be clicked on. Actually, it seems to be a bit more complicated than that, but that's at least part of what "hasFocus" indicates. A cell can be selected and not have the focus, and a cell can have the focus but not be selected. You may want to setup your renderer to clearly indicate which of these states are set and then run your app and play with the table selection to get a feel for how it works.
    Hope that helps.
    - Tyler

  • Easier way to set post-constructor JTable column names?

    I have a class that extends JTable. It also has a pair of inner classes that extend DefaultTableCellRenderer and AbstractTableModel so I can dynamicaly adjust the number of rows and their contents. That's not the problem - that part works fine. The problem is the column headers. My table doesn't currently have any but I want to add them.
    The column quantity is constant at 3 and should always be the same 3 Strings. It would be nice if I could use the JTable constructors that take a Vector or Object[] of column names from the start in my new class' constructor. But I don't think I can because at that point I don't know how many rows there will be or what they'll contain. Trying to set rowData to null just caused runtime exceptions.
    So the alternative seems to be to call setColumnModel() within the constructor, passing it a DefaultTableColumnModel. Which then requires I call addColumn() three times. Each time passing it a new TableColumn object. Each of which requires that I separately call setHeaderValue() after I construct it to set the header name. Am I right in that is the only way to do it? It just seems overly complex.

    I'll post a streamlined version of my class in case that will help...
    public class TotalsTable extends JTable
       private static int NUM_COLUMNS = 3;
       static final public String columnNames[] = {
             "Col Name 1", "Col Name 2", "Col Name 3"};
       protected Vector data = null;
       private TotalsModel tableModel;
       public TotalsTable()
          tableModel = new TotalsModel();
          setModel(tableModel);
          TableCellRenderer renderer = new TotalsCellRenderer();
          setDefaultRenderer(Object.class, renderer);
       public void updateTable(Vector pData)
          data = pData;
          tableModel.update();
       class TotalsCellRenderer extends DefaultTableCellRenderer
          public Component getTableCellRendererComponent
             (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
             super.getTableCellRendererComponent(table, value, isSelected,
                                                 hasFocus, row, column);
             if (column == 0) {
                setForeground(Color.blue);
             else {
                setForeground(Color.black);
             return this;
       class TotalsModel extends AbstractTableModel
          public TotalsModel()
             super();
          protected void update()
             fireTableStructureChanged();
           * Retrieves number of columns
           * (Necessary for AbstractTableModel implementation)
          public synchronized int getColumnCount()
             return NUM_COLUMNS;
          public synchronized int getRowCount()
             if (playerData == null)
                System.out.println("No rows found in table");
                return 0;
             else
                return playerData.size();
           * Returns cell information of a record at location row,column
           * (Necessary for AbstractTableModel implementation)
          public synchronized Object getValueAt(int row, int column)
             try
                MyObject p = (MyObject) data.elementAt(row);
                switch (column)
                   case 0:
                      return p.getName();
                   case 1:
                      return ("" + p.getDataItem2());
                   case 2:
                      return ("" + p.getDataItem3());
                   default:
                      System.out.println("getValueAt() Error: Invalid column");
             catch (Exception e)
                System.out.println("Exception in getValueAt(): " +
                                   e.getMessage());
             return "";
          public String getColumnName(int col)
             if (col < NUM_COLUMNS)
                return columnNames[col];
             else
                return "";
          public Class getColumnClass(int c)
             return getValueAt(0, c).getClass();
    }

  • Set font in JTable

    hello i just have an easy question that i am not smart enough to know yet...but how do u set a cell or a whole JTable to a specific font? Thanx Kevin

    Simple, call the setFont(Font font) method of the
    table or cell.
    e.g.
    theTable.setFont(new Font("serif", Font.BOLD, 12));
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JCo
    ponent.html#setFont(java.awt.Font)Just to complete the answer to the original question. For a single sell its pritty much the same. You need to get the cell you are interested in from the table e.g. theTable.getCellRenderer(int row, int column) you then need to get the actual rendering component. using getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) on the returned TableCellRenderer from the above snipit. You can then just call setFont on that.
    theTable.getCellRenderer(x, y).getTableCellRendererComponent(theTable, value, true, true, x, y).setFont(new Font("serif", Font.BOLD, 12));                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Setting size of JTable columns

    Hi everybody,
    Can anyone help me ?
    How can I set a column widths of a JTable, but also allow the user to resize them ?
    I tried with a code like
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
       if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setPreferredWidth(preferedSizeArray);
    But it doesn't work :(
    When i do [ define the minWidth and maxWidth ]
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
        if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setMinWidth(preferedSizeArray);
    tableColumnModel.getColumn(i).setMaxWidth(preferedSizeArray[i]);
    Columns's sizes are exactly what i want but ... the colums are no more resizable.
    So,
    if anyone can help me and tell me how can i set a predefined size for some colums and also allow the user to resize them ... that would be kind from him.
    Thanks

    Hi guys,
    It's me again ... but I tried your tricks and they don't work :(
    Look this example :
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    public class JTableResizing extends JFrame implements ActionListener {
        private JScrollPane scpnl = new JScrollPane();
        private JButton btnClose = new JButton();
        Object[][] data={   new Object[]{"Hi", "everybody", "this is ", "a row"},
                            new Object[]{"and ", "this ", "is the second", "row"},
                            new Object[]{"of a", "very ","usefull","jtable"}
        Object[] columnNames={"Column1", "Column2", "Column3", "Column4"};
        TableModel dataModel=new DefaultTableModel(data, columnNames);
        private JTable jTable = new JTable(dataModel);
        public JTableResizing() {
            try {
                /* We don't care about this code !! just see the code below !
                 * It has been made really quick [and dirty :D]
                this.setSize(new Dimension(530, 400));
                this.getContentPane().setLayout(new GridBagLayout());
                btnClose.setText("close");
                btnClose.addActionListener(this);
                scpnl.getViewport().add(jTable, null);
                this.getContentPane().add(scpnl,    new GridBagConstraints(0, 0, 1, 1, 1.0, 0.5,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.BOTH,
                                                                        new Insets(50, 50, 50, 50),
                                                                        0, 0));
                this.getContentPane().add(btnClose, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.NONE,
                                                                        new Insets(0, 0, 20, 0),
                                                                        0, 0));
                /* is this really necessary ??? I really don't think so */
                JTableHeader headers = jTable.getTableHeader();
                if (headers != null) {
                    headers.setResizingAllowed(true);
                 * Start watching the code from here.
                 * I created a JTable [jTable] with n columns. Now, I want to fix
                 * a size for some columns and the question is how ?? 
                 * Maybe the easiest way is to create a method !!
                 setColumnsSizes(jTable, new int[]{0, 100, 0, 50});
            } catch(Exception e) {
                e.printStackTrace();
        /* I know, the code is not the best but I don't care !! This is a quick
         * and dirty sample code to make you understand my problem ...*/
        public static void setColumnsSizes(JTable jTable, int[] columnsSizes) {
            /* look the array supplied above.  columnsSizes =  int[]{0,100,0,50}
             * but any array can be supplied !!
             * This one means that the second and the fourth columns should take
             * resectively a width of 100 and 50 and the two others columns
             * the first one and the third one, fill as much as possible depending on
             * the available space in the scrollpane.
             * Also, when I resize the frame, the scrollpane is resized
             * (look the gridbagconstraints above, and also here columns with
             * no prefered size must be
            /* Which mode should I suplpy ? I need an autoresize only for columns
               where no prefered size has been defined and I don't think it exists */
            jTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            TableColumnModel tableColumnModel = jTable.getColumnModel();
            for (int i=0; i < columnsSizes.length; i++) {
                if (columnsSizes[i] > 0) {
                    /* If I define a minimum width, the colum will be resizeable but,
                       we will be unable to resize it under his minSize. This can be
                       a good behaviour !*/
                    tableColumnModel.getColumn(i).setMinWidth(columnsSizes);
    /* If I define a prefered width, I'm not sure it will be the
    width of the column.
    I mean, when I define a prefered size on a column, other
    columns are resized depending of the autoResizeMode !*/
    tableColumnModel.getColumn(i).setPreferredWidth(columnsSizes[i]);
    /* if I define a maxWidth (next line code) the column will be fixed */
    // tableColumnModel.getColumn(i).setMaxWidth(columnsSizes[i]);
    public static void main(String[] args) {
    JTableResizing jTableResizing = new JTableResizing();
    jTableResizing.setLocationRelativeTo(null);
    jTableResizing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jTableResizing.setVisible(true);
    * method performed when clicking on button close
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    Copy, paste and run it and you'll understand the problem.
    Also, try to read comments I added (I think they are understandable, although I know they are full of grammar mistakes, but this is another question ... )
    Thanks for your help.
    And may the force be with you

  • Setting viewport in jtable

    Hello i have a jtable with many rows in a jscrollpane. After calling the
    J
    JTable table = new JTable();
    table.addMouseListener(new ColumnHeaderListener( this ));
    JScrollPane scrollPane = new JScrollPane( table );
    scrollPane.add(table);
    scrollPane.getViewport().addChangeListener(this);When the user clicks on the table there are some actions and i have to repaint the table therefore I added a MouseListener.
    public class ColumnHeaderListener extends MouseAdapter
    @Override
         public void mouseReleased(MouseEvent e)
              JTable table = this.tv.getTable();
              AssignmentsTableModel atm = (AssignmentsTableModel)table.getModel();
                    atm.fireTableDataChanged();
                    scrollToVisible(table, row, 0);
    {After calling fireTableDataChanged() the JTable always scrolls back to the first row. I tried fireTableCellUpdated() but it doesn't work.
    public void scrollToVisible(JTable table, int rowIndex, int vColIndex)
              if (!(table.getParent() instanceof JViewport))
                   return;
              JViewport viewport = (JViewport)table.getParent();
              if(rowIndex == 0)
                   return;
              Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
              Point pt = viewport.getViewPosition();
              int newx = rect.x-pt.x;
              int newy = rect.y-pt.y;
              rect.setLocation(newx, newy);
              viewport.scrollRectToVisible(rect);
         }But the viewport does not move. I tried setting newx and newy with variable values but the table always jumps back to row 1.
    Kind regards,
    Chang

    JScrollPane scrollPane = new JScrollPane( table );
    //scrollPane.add(table); // this is wrongYou never add a component directly to the scrollpane. You either
    a) create the scroll pane with the component as a parameter (as you did correctly)
    b) set the view of the viewport with your component
    JTable table = this.tv.getTable();
    AssignmentsTableModel atm = (AssignmentsTableModel)table.getModel();
    atm.fireTableDataChanged();
    scrollToVisible(table, row, 0); This code makes no sense.
    a) The variable row doesn't have a value.
    b) Why would clicking on the table header cause you to invoke "fireTableDataChanged"? You haven't changed any of the data.
    viewport.scrollRectToVisible(rect);I always invoke the scrollRectToVisible(... ) method on the component added to the scrollpane (ie. the table).
    For more help create a [url http://sscce.org]SSCCE, that demonstrates the incorrect behaviour.

  • Setting cursor in JTable TableCellRenderer

    I'm trying to get the cursor to change (hand cursor) when mousing over a cell in a JTable. I've tried making my own TableCellRenderer as such:
    public class DrillDownCellRenderer extends DefaultTableCellRenderer {
      public Component getTableCellRendererComponent(JTable table, Object value,
                  boolean isSelected, boolean hasFocus, int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        setText((String)value);
        setForeground(Color.blue);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        return this;
        * draws line under text
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(getForeground());
        g.fillRect(0,getHeight()-2,getFontMetrics(getFont()).stringWidth(getText()),1);
    }This doesn't seem to affect the cursor at all. Am I missing something?
    Maybe I'm going about this wrong from the start. I'd like some of the columns to appear like a "Link" which will let the user click and open up a new JFrame or some other action (It's my intention to fire this off through some sort of listener in the JTable but I havn't gotten that far yet). Maybe there's a better way to accomplish this?

    u can try this if you like its a slight enhancement with overidding getToolTipText(MouseEvent me) compile and run and watch behaviour
    good luck
    krishna
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class DrillDownCellRenderer extends DefaultTableCellRenderer
    public static final String HTML_START = "<html><a href=#>";
    public static final String HTML_END = "</a></html>";
    public static final DrillDownCellRenderer DDCR = new DrillDownCellRenderer();
    public DrillDownCellRenderer()
    super();
    public static void main(String[] args) throws Exception
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    JFrame f = new JFrame();
    DefaultTableModel dtm = new DefaultTableModel(10, 4);
    Date d = null;
    for(int i = 0; i < dtm.getRowCount(); i++)
    d = new Date();
    dtm.setValueAt(new Integer(i + 1), i, 0);
    dtm.setValueAt(d, i, 1);
    dtm.setValueAt(new Long(d.getTime()), i, 2);
    if(i % 2 == 0)
    dtm.setValueAt("http://www.yahoo.com" + d.getTime(), i, 3);
    else
    dtm.setValueAt("http://javasoft.com" + d.getTime(), i, 3);
    JTable t = new JTable(dtm)
    public TableCellRenderer getCellRenderer(int row, int col)
    if(super.convertColumnIndexToModel(col) == 3)
    return DDCR;
    return super.getCellRenderer(row, col);
    public String getToolTipText(MouseEvent me)
    int col = super.columnAtPoint(me.getPoint());
    if(super.convertColumnIndexToModel(col) == 3)
    int row = super.rowAtPoint(me.getPoint());
    Rectangle rec = super.getCellRect(row, col, false);
    String value = (String)super.getValueAt(row, col);
    int x = rec.x + DDCR.getFontMetrics(DDCR.getFont()).
    stringWidth(value);
    if(me.getPoint().x <= x)
    super.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    else
    super.setCursor(Cursor.getDefaultCursor());
    else
    super.setCursor(Cursor.getDefaultCursor());
    return super.getToolTipText(me);
    JScrollPane jsp = new JScrollPane(t);
    JLabel l = new JLabel(HTML_START + "http://javasoft.com" + HTML_END);
    f.getContentPane().add(l, BorderLayout.SOUTH);
    f.getContentPane().add(jsp);
    f.pack();
    f.show();
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    super.getTableCellRendererComponent
    (table, value, isSelected, hasFocus, row, column);
    setForeground(Color.blue);
    // can use html if you like
    // setText(HTML_START + value + HTML_END);
    return this;
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    g.setColor(getForeground());
    g.fillRect(0, getHeight() - 2, getFontMetrics(getFont()).
    stringWidth(getText()),1);
    }

  • Setting borders for JTable cells

    How can i create custom / user defined borders for cells in JTable (swing).I need to have borders like only top/bottom,left/right borders for cells. I came to know that it could be possible with paintBorder() method of AbstractBorder interface. But i need a sample code of how it has been done.
    Thanks & Regards
    M.Shanthakumari

    You need to create a custom table cell renderer to do what you are asking. It is what actually draws the cells. Just subclass the DefaultTableCellRenderer and override the getTableCellRendererComponent() method. Look at the source for that class, and just change it to add your logic to use a different border depending on the cell to be drawn.

  • Adding a Column to a JTable

    I have a simple gui where I query a database and return a result set in a JTable using a table model. I would like to be able to add a new column with checkboxes as the first column in the table. I've seen examples using checkboxes with boolen data from the database, but this column is not being returned from the database it is a new added column.
    The first task is to add the column and I am struggling with this. My code is below.
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class DatabaseTest extends JFrame {
      private QueryTableModel qtm;
      public DatabaseTest()
        super("JTable Test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 200);
        qtm = new QueryTableModel();
        JTable table = new JTable(qtm);
        JScrollPane scrollpane = new JScrollPane(table);
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(3, 2));
        p1.add(new JLabel("Click here to Query the DB: "));
        JButton jb = new JButton("Search");
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
            qtm.Query();
        p1.add(jb);
        getContentPane().add(p1, BorderLayout.NORTH);
        getContentPane().add(scrollpane, BorderLayout.CENTER);
      public static void main(String args[]) {
        DatabaseTest tt = new DatabaseTest();
        tt.setVisible(true);
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.table.AbstractTableModel;
    class QueryTableModel extends AbstractTableModel {
      Vector cache;
      private int colCount;
      private String[] headers;
      Statement statement;
      private static Connection conn = null;
      public QueryTableModel() {
        cache = new Vector();
      public String getColumnName(int i) {
        return headers;
    public int getColumnCount() {
    return colCount;
    public int getRowCount() {
    return cache.size();
    public Object getValueAt(int row, int col) {
    return ((String[]) cache.elementAt(row))[col];
    public void Query() {
    cache = new Vector();
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:*****","******","*******");
    statement = conn.createStatement();
    ResultSet rs = statement.executeQuery("Select username from dba_users where rownum < 6");
    ResultSetMetaData meta = rs.getMetaData();
    colCount = meta.getColumnCount();
    // Now we must rebuild the headers array with the new column names
    headers = new String[colCount];
    for (int h = 1; h <= colCount; h++) {
    headers[h - 1] = meta.getColumnName(h);
    while (rs.next()) {
    String[] record = new String[colCount];
    for (int i = 0; i < colCount; i++) {
    record[i] = rs.getString(i + 1);
    cache.addElement(record);
    fireTableChanged(null);
    // Add column code here?
    } catch (Exception e) {
    cache = new Vector(); // blank it out and keep going.
    e.printStackTrace();
    }Not sure how to add the column. I've tried a few variations of the following code with no luck:TableColumn tc = new TableColumn(0, 120);
    tc.setHeaerValue("Name");
    table.getColumnModel().addColumn(tc);Any help would be appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    The first task is to add the column Well, I like the suggestions from the link given in the above posting :-) It shows you how to dynamically alter the TableModel after its initial creation, and is probably the best generic solution.
    But, just so you understand better how a TableModel works I"ll just put another thought in your mind. Maybe in this case you just create the TableModel correctly the first time so you don't need to do a dynamic change. The TableModel doesn't know where the data came from. It doesn't care that it came from a ResultSet. All it knows it that you have data in an array. So whats to prevent you from hard coding the first column to contain Boolean data?
    {code}headers = new String[colCount+1];
    headers[0] = "Boolean Column";
    for (int h = 1; h <= colCount; h++)
    headers[h] = meta.getColumnName(h);
    while (rs.next())
    String[] record = new String[colCount+1];
    record[0] = new Boolean.FALSE;
    for (int i = 1; i <= colCount; i++)
    record[i] = rs.getString(i);
    }{code}

  • JTable column headers not displaying using custom table model

    Hi,
    I'm attempting to use a custom table model (by extending AbstractTableModel) to display the contents of a data set in a JTable. The table is displaying the data itself correctly but there are no column headers appearing. I have overridden getColumnName of the table model to return the correct header and have tried playing with the ColumnModel for the table but have not been able to get the headers to display (at all).
    Any ideas?
    Cheers

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            super();
            pubManager = pm;
        public int getColumnCount()
            return GUISettings.getDisplayedFieldCount();
        public int getRowCount()
            return pubManager.getPublicationCount();
        public Class getColumnClass(int columnIndex)
            Object o = getValueAt(0, columnIndex);
            if (o != null) return o.getClass();
            return (new String()).getClass();
        public String getColumnName(int columnIndex)
            System.out.println("asked for column name "+columnIndex+" --> "+GUISettings.getColumnName(columnIndex));
            return GUISettings.getColumnName(columnIndex);
        public Publication getPublicationAt(int rowIndex)
            return pubManager.getPublicationAt(rowIndex);
        public Object getValueAt(int rowIndex, int columnIndex)
            Publication pub = (Publication)pubManager.getPublicationAt(rowIndex);
            String columnName = getColumnName(columnIndex);
            if (columnName.equals("Address"))
                if (pub instanceof Address) return ((Address)pub).getAddress();
                else return null;
            else if (columnName.equals("Annotation"))
                if (pub instanceof Annotation) return ((Annotation)pub).getAnnotation();
                else return null;
            etc
           else if (columnName.equals("Title"))
                return pub.getTitle();
            else if (columnName.equals("Key"))
                return pub.getKey();
            return null;
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;
        public void setValueAt(Object vValue, int rowIndex, int colIndex)
        }Class GUISettings:
    public class GUISettings {
        private static Vector fields = new Vector();
        private static Vector classes = new Vector();
        /** Creates a new instance of GUISettings */
        public GUISettings() {
        public static void setFields(Vector f)
            fields=f;
        public static int getDisplayedFieldCount()
            return fields.size();
        public static String getColumnName(int columnIndex)
            return (String)fields.elementAt(columnIndex);
        public static Vector getFields()
            return fields;
    }GUISettings.setFields has been called before table is displayed.
    Cheers,
    garsher

  • Update JTable cells via setValueAt

    Hello all,
    I'm trying to implement a setValueAt method using an arrayList.....no success.What listeners should I have set up(For JTable or my table model)? I am new at this and I'm trying to update the JTable cells after a query from some db. Could anyone help?
    When trying to change the a value in the table I get these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at CachingResultSetTableModel.getValueAt(CachingResultSetTableModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

    I would think that everone who starts off with JTable will have a couple of concept problems. I am also going thru this learnig curve. It looks to me ( the blind leading the blind etc) like your basic table has strange data in it. The problem is occuring when the JTable is trying to setup the data from the table model.
    I don't think its anything to do with setValueAt.
    I kept going back to TableMap, TableSorter and JDBCAdaptor examples and copying the code from them to come right.> I debug by putting a System.out .... in all the methods until I get to where the code is giving trouble.
    Good luck [email protected]
    Hello all,
    >
    I'm trying to implement a setValueAt method using an
    arrayList.....no success.What listeners should I have
    set up(For JTable or my table model)? I am new at
    this and I'm trying to update the JTable cells after a
    query from some db. Could anyone help?
    When trying to change the a value in the table I get
    these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at
    CachingResultSetTableModel.getValueAt(CachingResultSetT
    bIleModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at
    javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt
    method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

Maybe you are looking for

  • Adobe Creative Suite Confusion. Want to Create a Website

    I am so confused by all the information or should I say I am overwhelmed. I am wanting to create a website. I have an idea of the layout of the website. It is basically using a PNG image that I had created as the background. Some rounded rectangle sh

  • Can't turn off Hand tool

    I was working on 2 different illustrator documents and combined them into one, stepped away for a while and came back to not being able to remove the hand tool no matter what tool I click on. I noticed in the title bar that in parens it reads (cmyk/p

  • Dynamically changing state of JToggleButton

    Hey people, Im total newb to Java and i need some help. i have 4 JToggleButton's next to each other inside a JToolBar. When one is selected, other 3 must be unselected, im setting action listener on each of those like this: button1.addActionListener(

  • SSRS Weekly View Calendar empty textboxes

    Hi everyone  I've prepared a weekly view calendar report. When I execute it displays all events right but, there are empty textboxes. So, there are many unneccessary empty fields in the matrix.  You can  see an overview of the report. The empty boxes

  • Pages open up with everything to the right, sometimes out of sight. Just started happening when I downloaded the latest version. HELP!!

    Ever since I downloaded the latest version of Firefox a few days ago, whenever I open a web page the whole page is on the extreme right. I have to move the resizing tool at the bottom right of my window and then the page immediately pops back to the