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.

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 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.

  • 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 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.

  • How to get JTable to always show complete rows

    Is there any way to set up a JTable to resize itself properly so as to always display complete rows (no rows cut in half at the bottom or top) but still be able to change its size when it is in a flexible layout like GridBagLayout?

    Thanks for the response, but I was rather looking for the transpose of that solution; i.e. a kind of preferred scrollable viewport height that respects the row height so that it is always exactly equal to the height of an integral number of rows. That way only complete rows would be displayed.
    Obviously, displaying complete rows can't be strictly enforced when fine-grain scrolling is in effect, but the idea is that the scrollable viewport height is set to display an exact integral number of rows, and if the rows weren't cut off at the top, they wouldn't be at the bottom, either. If the table's available area increased in size, the scrollable viewport would only increase if there was enough room for one or more complete rows.
    I suppose I could trap resizing events and adjust the scrollable viewport size accordingly, but I was hoping there was a cleaner way...

  • Can't scroll to last row in a JTable

    I am having great difficulty in getting a scrollable
    JTable to scroll to the very last row.
    I've done the following:
    int lastRowIndex = table.getRowCount() - 1;
    Rectagle rect = table.getCellRect(lastRowIndex);
    table.scrollRectToVisible(rect, 0, true));
    BUT, it always scrolls the the row just prior to
    the last... never the last. I've checked, and my
    lastRowIndex is correct. I've even tried something
    as stupid as just increasing lastRowIndex by 1,
    and it still does not work.
    So, I am at a loss as to why this does not work.
    b.c

    Moving the scroll bar to the bottom (maximum) had
    no effect. In fact, doing that alone ought to
    acheive the same goal.
    However, I have discovered that if I do either
    (move scroll bar or set viewport to last cell's
    rectangle) TWICE, it works.
    I speculate that there is some kind of latency
    in the GUI "knowing" what the maximum extent really
    is. Trying to move to the end the first time fails,
    but it does cause the GUI to refresh itself
    immediately afterwards so that if I try this a
    second time, it works.
    I can achieve the same results if I simply
    ***force a re-paint before attempting to move
    the the last cell***. Then, it works.
    So, my solution was to do the following:
    __ int lastRowIndex = myTable.getRowCount() - 1;
    __ if (lastRowIndex > -1)
    _____ // repaint the window first.
    _____ Rectangle bounds = getBounds();
    _____ bounds.x = 0;
    _____ bounds.y = 0;
    _____ paintImmediately(bounds);
    _____ // Now, move to the last row
    _____ bounds = myTable.getCellRect(lastRowIndex, 0, true);
    _____ myTable.getScrollPane().getViewport(
    _____ ).scrollRectToVisible(bounds);

  • 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}

Maybe you are looking for