Refreshing JTable contents (rows and columns) handling.

Hi,
I have a general question related to refreshing the contents of JTable and handling some application specific requirements.In our application we are planning to refresh the contents of JTable automatically after certain period of time by fetching data from database and update the JTable contents or user has clicked refresh button.
But following scenarios we are planning to handle when refresh is called automatically or user has clicked refresh button.
1) User is working with data of JTable. Like rows of JTable has checkBoxes and user selects them and doing operation like viewing the details of selected rows in new details dialog. So if refreshing is done then the selection will be lost if I update the whole data in JTable.
a)Will it be possible to append the data at the end of JTable rows without disturbing the existing JTable contents.
b) Is it feasible to compare the data of existing rows and newly fetched rows and update only the rows whose values are changed in database or update specifically updated columns. But this comparision for finding changed values will result in performance problems.So are there any other alternatives of doing this, ideas are most welcome.
c) Simple way is to alert the user that data will be updated and everything will be refreshed will be the choice in worst case.
I guess many may have encountered such problems and may have solved it depending on the product requirements.
Ideas and suggestions are most welcome.
Regards.

Hi,
Here are my views and my assumptions.
Assumptions :
1) Your JTable is populated with list of Objects.
2) Your tables in database is having columns like created date, created time, updated date updated time
3) Order by clause for all the time will remain same.
If these assumptions are correct then I think you can achieve your goal.
Here how it is.
Your application session will maintain last db hit time and will maintain for every hit that applicate made to fetch data from db.
When object is created on the server side once it fetch data from table it will compare the created date/time or update date/time with the session varibale that holds last visit date/time. Based on this flag need to be set to indicate if this item is added/updated/deleted since last visit.
And when all these object is returned to your client, the table model will iterate through the list and based on object index in the list and and if object is changed will update only that perticular row.
Hope this is what you want to achieve.
Regards

Similar Messages

  • JTable fixed Row and Column in the same window

    Hi
    Could anyone tip me how to make fixed row and column in the same table(s).
    I know how to make column fixed and row, tried to combine them but it didnt look pretty.
    Can anyone give me a tip?
    Thanks! :)

    Got it to work!
    heres the kod.. nothing beautiful, didnt clean it up.
    * NewClass.java
    * Created on den 29 november 2007, 12:51
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package tablevectortest;
    * @author Sockan
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class FixedRowCol extends JFrame {
      Object[][] data;
      Object[] column;
      JTable fixedTable,table,fixedColTable,fixedTopmodelTable;
      private int FIXED_NUM = 16;
      public FixedRowCol() {
        super( "Fixed Row Example" );
        data =  new Object[][]{
            {      "","A","A","A","",""},
            {      "a","b","","","",""},
            {      "a","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "I","","W","G","A",""}};
        column = new Object[]{"A","B","C","D","E","F"};
        AbstractTableModel fixedColModel = new AbstractTableModel() {
          public int getColumnCount() {
            return 1;
          public int getRowCount() {
            return data.length;
          public String getColumnName(int col) {
            return (String) column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel    model = new AbstractTableModel() {
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col+1];
          public Object getValueAt(int row, int col) {
            return data[row][col+1];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col+1] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedTopModel = new AbstractTableModel() {
          public int getColumnCount() { return 1; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedModel = new AbstractTableModel() {     
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return FIXED_NUM; }
          public Object getValueAt(int row, int col) {
            return data[row + (data.length - FIXED_NUM)][col+1];
        table = new JTable( model );
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTable = new JTable( fixedModel );
        fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedColTable= new JTable(fixedColModel);
        fixedColTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedColTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTopmodelTable = new JTable(fixedTopModel);
        fixedTopmodelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTopmodelTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);   
        JScrollPane scroll      = new JScrollPane( table );
         scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
          public void setColumnHeaderView(Component view) {}
        fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        fixedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JScrollBar bar = scroll.getVerticalScrollBar();
        JScrollBar dummyBar = new JScrollBar() {
          public void paint(Graphics g) {}
        dummyBar.setPreferredSize(bar.getPreferredSize());
        scroll.setVerticalScrollBar(dummyBar);
        final JScrollBar bar1 = scroll.getHorizontalScrollBar();
        JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
        bar2.addAdjustmentListener(new AdjustmentListener() {
          public void adjustmentValueChanged(AdjustmentEvent e) {
            bar1.setValue(e.getValue());
        JViewport viewport = new JViewport();
        viewport.setView(fixedColTable);
        viewport.setPreferredSize(fixedColTable.getPreferredSize());
        fixedScroll.setRowHeaderView(viewport);
        fixedScroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColTable
            .getTableHeader());   
        JViewport viewport2 = new JViewport();
        viewport2.setView(fixedTopmodelTable);
        viewport2.setPreferredSize(fixedTopmodelTable.getPreferredSize());
        scroll.setRowHeaderView(viewport2);
        scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTopmodelTable
            .getTableHeader()); 
        scroll.setPreferredSize(new Dimension(600, 19));
        fixedScroll.setPreferredSize(new Dimension(600, 100)); 
        getContentPane().add(     scroll, BorderLayout.NORTH);
        getContentPane().add(fixedScroll, BorderLayout.CENTER);   
      public static void main(String[] args) {
        FixedRowCol frame = new FixedRowCol();
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent e ) {
            System.exit(0);
        frame.pack();
        frame.setVisible(true);
    }

  • How to save data from JTable multiple rows and columns

    Hi Y_Not thanks for your help before...
    But what should I do if I want to get/save many data from many column and rows??

    i don't quite understand your (repeated) question. what is the problem with "multiple rows and columns". Y_NOT and i have shown you ways to access them.
    all you need are 2 loops: one around your number of rows and one around the number of columns or vice versa depending in which order you want to save things:
    for (int col = 0; col < data.size(); col++) {
        for (int row = 0 ; row < data[col].size(); row++) {
            // save your data
            saveData(data[col].getElementAt(row));
            // or use yourtable.getValueAt(row, col);
    }this is not a problem of Swing/Java but of simple algorithm...
    thomas

  • Mapping of JTable Rows and columns and paint it to the JPanel

    Hi,
    I am using JTable and graphics object to draw the JTable on JPanel. But due to some lack of measurement I am not able to draw table cells correctly.
    Apart from this on changing the fontSize I have to redraw it according to the requirement. But when the data size increases it draws absurdly.
    I am using jTable.getCellRect() api to get the row width and height. Please help to redraw a JTable cell row and height on JPanel.
    I am also attaching a sample code with this mail.
    Thanks,
    Ajay
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.table.*;
    import java.util.*;
    import java.awt.*;
    public class SimpleTableDemo extends JPanel {
        private boolean DEBUG = false;
           private int spacing = 6;
           private Map columnSizes = new HashMap();
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
             {"Kathy", "Smith",
              "SnowboardingXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", new Integer(5), new Boolean(false)},
             {"John", "Doe",
              "Rowing", new Integer(3), new Boolean(true)},
             {"Sue", "Black",
              "Knitting", new Integer(2), new Boolean(false)},
             {"Jane", "White",
              "Speed reading", new Integer(20), new Boolean(true)},
             {"Joe", "Brown",
              "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
              Panel1 panel;
        public SimpleTableDemo() {
            super(new GridLayout(3,0));
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //table.setFillsViewportHeight(true);
            if (DEBUG) {
                table.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                        printDebugData(table);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            panel = new Panel1();
            Rectangle rect = table.getCellRect(0,0,true);
              panel.setX(table.getWidth());
              panel.setY(0);
            panel.setWidth(rect.width);
              panel.setHeight(rect.height);
            panel.setStr(table.getModel().getValueAt(0,0).toString());
              panel.setModel(table);
              add(panel);
            final JComboBox jNumberComboBoxSize = new JComboBox();
              jNumberComboBoxSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "11", "12", "14", "16", "18", "20", "24", "30", "36", "48", "72" }));
            jNumberComboBoxSize.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                   jNumberComboBoxSizeActionPerformed(jNumberComboBoxSize);
              JPanel panel2 = new JPanel();
              panel2.add(jNumberComboBoxSize);
              add(panel2);
              adjustColumns();
         private void jNumberComboBoxSizeActionPerformed(JComboBox jNumberComboBoxSize)
            int fontSize = Integer.parseInt(jNumberComboBoxSize.getSelectedItem().toString());
              table.setRowHeight(fontSize);
              table.setFont(new Font("Serif", Font.BOLD, fontSize));
              Rectangle rect = table.getCellRect(0,0,true);
              panel.setX(0);
              panel.setY(0);
           // panel.setWidth(rect.width);
              panel.setHeight(rect.height);
            panel.setStr(table.getModel().getValueAt(0,0).toString());
              panel.setModel(table);
              panel.repaint();
              table.revalidate();
        private void printDebugData(JTable table) {
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            System.out.println("Value of data: ");
            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + model.getValueAt(i, j));
                System.out.println();
            System.out.println("--------------------------");
          *  Adjust the widths of all the columns in the table
         public void adjustColumns()
              TableColumnModel tcm = table.getColumnModel();
              for (int i = 0; i < tcm.getColumnCount(); i++)
                   adjustColumn(i);
          *  Adjust the width of the specified column in the table
         public void adjustColumn(final int column)
              TableColumn tableColumn = table.getColumnModel().getColumn(column);
              if (! tableColumn.getResizable()) return;
              int columnHeaderWidth = getColumnHeaderWidth( column );
              int columnDataWidth   = getColumnDataWidth( column );
              int preferredWidth    = Math.max(columnHeaderWidth, columnDataWidth);
            panel.setWidth(preferredWidth);
              updateTableColumn(column, preferredWidth);
          *  Calculated the width based on the column name
         private int getColumnHeaderWidth(int column)
              TableColumn tableColumn = table.getColumnModel().getColumn(column);
              Object value = tableColumn.getHeaderValue();
              TableCellRenderer renderer = tableColumn.getHeaderRenderer();
              if (renderer == null)
                   renderer = table.getTableHeader().getDefaultRenderer();
              Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, column);
              return c.getPreferredSize().width;
          *  Calculate the width based on the widest cell renderer for the
          *  given column.
         private int getColumnDataWidth(int column)
              int preferredWidth = 0;
              int maxWidth = table.getColumnModel().getColumn(column).getMaxWidth();
              for (int row = 0; row < table.getRowCount(); row++)
                  preferredWidth = Math.max(preferredWidth, getCellDataWidth(row, column));
                   //  We've exceeded the maximum width, no need to check other rows
                   if (preferredWidth >= maxWidth)
                       break;
              return preferredWidth;
          *  Get the preferred width for the specified cell
         private int getCellDataWidth(int row, int column)
              //  Inovke the renderer for the cell to calculate the preferred width
              TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
              Component c = table.prepareRenderer(cellRenderer, row, column);
              int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
              return width;
          *  Update the TableColumn with the newly calculated width
         private void updateTableColumn(int column, int width)
              final TableColumn tableColumn = table.getColumnModel().getColumn(column);
              if (! tableColumn.getResizable()) return;
              width += spacing;
              //  Don't shrink the column width
              width = Math.max(width, tableColumn.getPreferredWidth());
              columnSizes.put(tableColumn, new Integer(tableColumn.getWidth()));
              table.getTableHeader().setResizingColumn(tableColumn);
              tableColumn.setWidth(width);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("SimpleTableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            SimpleTableDemo newContentPane = new SimpleTableDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    class Panel1 extends JPanel
        int x;
         int y;
         int width;
         int height;
         String str;
         JTable model;
        public void setModel(JTable model)
           this.model = model;
         public void setX(int x)
              this.x = x;
        public void setY(int y)
              this.y = y;
         public void setWidth(int w)
              this.width = w;
        public void setHeight(int h)
              this.height = h;
         public void setStr(String s)
              this.str = s;
        public void paint(Graphics g)
             super.paint(g);
              int initX= 0;
              for(int row=0;row < 5; ++row)
                   initX = x;
                   for (int col=0;col < 5;++col)
                        g.drawRect(x,y,width,height);
                        g.drawString(model.getModel().getValueAt(row,col).toString(),x + 10,y + 10);
                        x = x + width;
                x = initX;
                   y = y + height;
    };

    an easy way would be to use setSize()

  • How to set the Selected row and Column in JTable

    Hi,
    i have a problem like the JTable having one Method getSelectedRow() and getSelectedColumn to know the Selected row and Column but if i want to explicitly set the Selected Row and Column,then there is no such type of Methods.If anybody has any solution then i will be thankful to him/her.
    Praveen K Saxena

    Is that what you're looking for? :myTable.getSelectionModel().setSelectionInterval(row, row);
    myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column);

  • How to freeze row and column in JTable

    Hi,
    I need to freeze first two rows and columns in a large JTable. I found ways to freeze either a row or a column, but not both at the same time.
    Can any of you help ?
    Found this code which allows freezing a col. Similar method can be used to freeze column
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableModel;
    public class FrozenTablePane extends JScrollPane{
    public FrozenTablePane(JTable table, int colsToFreeze){
    super(table);
    TableModel model = table.getModel();
    //create a frozen model
    TableModel frozenModel = new DefaultTableModel(
    model.getRowCount(),
    colsToFreeze);
    //populate the frozen model
    for (int i = 0; i < model.getRowCount(); i++) {
    for (int j = 0; j < colsToFreeze; j++) {
    String value = (String) model.getValueAt(i, j);
    frozenModel.setValueAt(value, i, j);
    //create frozen table
    JTable frozenTable = new JTable(frozenModel);
    //remove the frozen columns from the original table
    for (int j = 0; j < colsToFreeze; j++) {
    table.removeColumn(table.getColumnModel().getColumn(0));
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //format the frozen table
    JTableHeader header = table.getTableHeader();
    frozenTable.setBackground(header.getBackground());
    frozenTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    frozenTable.setEnabled(false);
    //set frozen table as row header view
    JViewport viewport = new JViewport();
    viewport.setView(frozenTable);
    viewport.setPreferredSize(frozenTable.getPreferredSize());
    setRowHeaderView(viewport);
    setCorner(JScrollPane.UPPER_LEFT_CORNER, frozenTable.getTableHeader());
    }

    Hi,
    I need to freeze first two rows and columns in a large JTable. I found ways to freeze either a row or a column, but not both at the same time.
    Can any of you help ?
    Found this code which allows freezing a col. Similar method can be used to freeze column
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableModel;
    public class FrozenTablePane extends JScrollPane{
    public FrozenTablePane(JTable table, int colsToFreeze){
    super(table);
    TableModel model = table.getModel();
    //create a frozen model
    TableModel frozenModel = new DefaultTableModel(
    model.getRowCount(),
    colsToFreeze);
    //populate the frozen model
    for (int i = 0; i < model.getRowCount(); i++) {
    for (int j = 0; j < colsToFreeze; j++) {
    String value = (String) model.getValueAt(i, j);
    frozenModel.setValueAt(value, i, j);
    //create frozen table
    JTable frozenTable = new JTable(frozenModel);
    //remove the frozen columns from the original table
    for (int j = 0; j < colsToFreeze; j++) {
    table.removeColumn(table.getColumnModel().getColumn(0));
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //format the frozen table
    JTableHeader header = table.getTableHeader();
    frozenTable.setBackground(header.getBackground());
    frozenTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    frozenTable.setEnabled(false);
    //set frozen table as row header view
    JViewport viewport = new JViewport();
    viewport.setView(frozenTable);
    viewport.setPreferredSize(frozenTable.getPreferredSize());
    setRowHeaderView(viewport);
    setCorner(JScrollPane.UPPER_LEFT_CORNER, frozenTable.getTableHeader());
    }

  • Select row and column from header in jtable

    hello i have a problem to select row and column from header in jtable..
    can somebody give me an idea on how to write the program on it.

    Hi Vicky Liu,
    Thank you for your reply. I'm sorry for not clear question.
    Answer for your question:
    1. First value of Open is item fiels in Dataset2 and this value only for first month (january). But for other month Open value get from Close in previous month.
    * I have 2 Dataset , Dataset1 is all data for show in my report. Dataset2 is only first Open for first month
    2. the picture for detail of my report
    Detail for Red number:
    1. tb_Open -> tb_Close in previous month but first month from item field in Dataset2
    espression =FormatNumber(Code.GetOpening(Fields!month.Value,First(Fields!open.Value, "Dataset2")))
    2. tb_TOTAL1 group on item_part = 1
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)))
    3. tb_TOTAL2 group on item_part = 3 or item_part = 4
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) + ReportItems!tb_TOTAL1.Value )
    4. tb_TOTAL3 group on item_part = 2
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) - ReportItems!tb_TOTAL2 .Value)
    5. tb_Close -> calculate from tb_TOTAL3 - tb_Open
    expression =FormatNumber(Code.GetClosing(ReportItems!tb_TOTAL3.Value,ReportItems!tb_Open.Value))
    I want to calculate the value of tb_Open and tb_Close. I try to use custom code for calculate them. tb_close is correct but tb_Open is not correct that show value = 0 .
    My custom code:
    Dim Shared prev_close As Double
    Dim Shared now_close As Double
    Dim Shared now_open As Double
    Public Function GetClosing(TOTAL3 as Double,NowOpening as Double)
        now_close = TOTAL3 + NowOpening
        prev_close = now_close
        Return now_close
    End Function
    Public Function GetOpening(Month as String,NowOpen as Double)
        If Month = "1" Then
            now_open = NowOpen
        Else    
            now_open = prev_close
        End If
        Return now_open
    End Function
    Thanks alot for your help!
    Regards
    Panda A

  • Retreiving Point location with JTable row and column

    If I have the row and column in a JTable (in a JPanel), how do I get the Point location offset from the location Point of the JTable or JPanel ?

    I think that this may do it.
    Point objPoint = new Point( objTable_.getLocation() );
    int intRow = objTable_.getSelectedRow();
    int intColumn = objTable_.getSelectedColumn();
    int intColumnWidth = objTable_.getColumnModel().getColumn( intColumn ).getWidth();
    int intColumnMargin = objTable_.getColumnModel().getColumnMargin();
    int x = (int) objPoint.getX() + ( (intColumn+1) * intColumnWidth) );
    // perhaps * (intColumnWidth + intColumnMargin)
    int y = (int) objPoint.getY() + ( (intRow+1) * objTable_.getRowHeight());
    // perhaps * (objTable_.getRowHeight() + objTable_.getRowMargin())

  • JTable  - Rows and columns

    I have created a JTable that displays the results from a query. My question is how can I get the JTable to display only a given number of rows and columns and have a scrollbar to see the rest of the cells?
    Thank you

    an easy way would be to use setSize()

  • JTable - Swapping the Rows and Columns

    This issue was raised in the Java Programming forum. Received initially as a weird requirement, it now seems that it is more common than you might think. Under it's original title it was "JTable - Limitation or Not?"
    I introduced the topic here so that the thread perspective can include more experienced Swing developers.
    The JTable in it's default layout is intended to hold database tables with records in rows. But what if you want records in columns?
    Some have said why? Just accept the row layout. Others have said use a customised form. Both reasonable views. Despite this, others report that the inherrited power of the JTable is worth leveraging and they have been doing it for years. Albeit with messy code in certain cases.
    This is a clear candidate for a popular derived component. If the existing JTable were renamed as a JTableRecordPerRow I am describing a JTableRecordPerColumn. The corresponding Table Model must naturally have a getRowClass method and no getColumnClass method.
    Java is good at seperating data from display issues so essentially this is only a display issue. The data representation is unaffected.
    While this may be so, the TableModel for a JTable makes the link from the display to the data so it must have knowledge about cell type to trigger the correct cell editor for example.
    I think it is fair to say that the standard JTable has not be designed with alternative row/column or column/row displays in mind. Hence a single getColumnClass method. However implementing a Table model which exchanges columns for rows is a good start. This leaves a few loose ends where editting is concerned.
    While this may not be an ideal topic for anyone just learning Swing I have been encouraged to consider the general case within the limitations of the cell types normally supported by the default Table model.
    I would have a guess that this is an established component in many private Java libraries already.
    Views and experience on this topic extremely welcome.

    It appears to me that while interchanging the rows and columns of a JTable is not trivial it is still worthwhile as a workhorse component.
    Perhaps the original design could have allowed for an aternative layout manager of somekind but this could easily have made description of records/rows and fields/columns confusing.
    I will probably get this summary wrong but I aill attempt to collate the neatest approach as I see it. Criticisms or shorter steps welcome. My thanks to the original contributors traceable from this thread.
    In the descriptions below a distinction is made between the normal internal data model representation of a row, called "mrow", and the displayed form "row".
    Only the TableModel need be changed.
    1 Use row 0 to show the headers by a)disabling the normal TableHeader renderer b)setting the cell renderer for column 0 to the default renderer used by the TableHeader and c)using the getValueAt method to return mcol header values for the row entries.
    2 For other row, col values to getValueAt return the value at mcol, mrow where mcol==row-1 & mrow==col.
    3 Create a new getCellClass(col,row) method to return the class where mrow==0 and mcol==row-1. Note that I am only trying to immitate the common use of of a database record per mrow here.
    4 Override a)getCellRenderer and b)getCellEditor to use getCellClass
    Four steps with seven parts seems worth it to me.
    The power of Swing!
    Many thanks to all.

  • JTable: Selecting rows in columns independently

    Dear all,
    I have a JTable with two columns. I want the user to be able to select cells in columns independently. At present, the entire row gets marked as selected. Is it possible at all to, for instance, select row1 1 to 3 in column 1 and rows 4 to 5 in column 2? If so, where's the switch? Thanks a lot in advance!
    Cheers,
    Martin

    Are you trying to use a seperate table for each column.
    Thats not a good idear.
    Here is what you have to do.
    1. Create a sub class of JTable
    2. You will have to redefine how the selection is done so. You will need some sort of a collection to store the list of selected cells indexes
    2.1 Selecting a cell is simply adding the coordinations of the cell to the selection
    2.2 de selecting is just removing it from the collection.
    2.3 Here is what you have to override
         setColumnSelectionInterval()
         setColumnSelectionInterval()
         changeSelection()
         selectAll()
         getSelectedColumns()
         getSelectedColumn()
         getSelectedRows()
         getSelectedRow() You migh also need few new methods such as
         setCellSelected(int row, int column, boolean selected);
         boolean isCellSelected(int row, int column);
         clearSelection();
         int[][] getSelectedCells();You will have to implement the above in terms of your new data structure.
    3. Handle mouse events.
    Ex:- when user cicks on a cell if it is already selected it should be deselected (see 2.2)
    other wise current selected should be cleared and the clicked cell should be selected
    if your has pressed CTRL key while clicking the the cell should be selected without deselecting the old selection.
    ---you can use above using a MouseListener
    When the user hold down a button and move the mouse accross multiple cell those need to be selected.
    --- You will need a MouseMotionListener for this
    You might also need to allow selection using key bord. You can do that using a KeyListener
    4. Displaying the selection
    You have to make sure only the selected cells are high lighted on the table.
    You can do this using a simple trick.
    (Just override getCellEditor(int row, int column) and getCellRenderer(int row, int column) )
    Here is what you should do in getCellRenderer(int row, int column)
    public TableCellRenderer getCellRenderer(int row, int column)
      TableCellRenderer realRenderer = super.getCellRenderer(int row, int);
      return new WrapperRenderer(realRenderer,selectedCellsCollection.isCellSelected(row,column));
    static class WrapperRenderer implements TableCellRenderer{
        TableCellRenderer realRenderer;
        boolean selected;
        public WrapperRenderer(TableCellRenderer realRenderer, boolean selected){
           this.realRenderer = realRenderer;
           this.selected = selected;
        public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column){       
            return realRenderer.getTableCellRendererComponent(table,value,selected,hasFocus,row,column);
    }What the above code does is it simply created wrapper for the Renderer and when generating the rendering component it replaces the isSeleted flag with our on selected flag
    and the original renderer taken from the super class will do the rest.
    You will have to do the same with the TableCellEditor.
    By the way dont use above code as it is becouse the getCellRenderer method create a new instance of WrapperRenderer every time.
    If the table has 10000 cells above will create 10000 instances. So you should refine above code.
    5. Finnaly.
    Every time the selection is changes you should make the table rerender the respective cells in or der to make the changes visible.
    I'll leave that part for you to figure out.
    A Final word
    When implementing th above make sure that you do it in the java way of doing it.
    For the collection of selected cells write following classes
    TableCellSelectionModel  // and interface which define what it does
    DefaultTableCellSelectionModel //Your own implementation of above interface the table you create should use thisby default
    //To communicate the selection changes
    TableCellSelectionModelListener
    TableCellSelectionModelEventif you read the javadoc about similer classes in ListSelectionModel you will get an idear
    But dont make it as complex as ListSelectionModel try to keep the number of methods less than 5.
    If you want to make it completly genaric you will have to resolve some issues such as handling changes to the table model.
    Ex:- Rows and colums can be added and removed in the TableModle at the run time as a result the row and column indexes of some cells might change
    and the TableCellSelectionModel should be updated with those changes.
    Even though the todo list is quite long if you plan your implementation properly the code will not be that long.
    And more importantly you will learn lots more by trying to implementing this.
    Happy Coding :)

  • Method to locate row and column in TableView

    In a TableView.setOnMouseClicked ()
    How to capture that row and column were clicked?

    I am having problem in populating data from a table in one screen to a Text Field in the other screen. I have two classes FirstClass containing a textbox and a button. On pressing a button a second window is opened containing a Table of values. As the user double clicks a row the value of the second column of the row should be inserted into the textbox of the FirstClass. Code of both the classes is attached. Thanking you in anticipation.
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    public class FirstClass extends Application {
    public static void main(String[] args) {
         launch(args);
    @Override
    public void start(final Stage primaryStage) {
         primaryStage.setTitle("First Class");
    GridPane gridpane = new GridPane();
              gridpane.setPadding(new Insets(5));
              gridpane.setHgap(5);
              gridpane.setVgap(5);
    final TextField userNameFld = new TextField();
    gridpane.add(userNameFld, 1, 1);
    Button btn = new Button();
    btn.setText("Show Table");
    gridpane.add(btn, 1, 3);
    btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
         String a = TableClass.showDialog(primaryStage, true, "Table Window" );
         userNameFld.setText(a);
    StackPane root = new StackPane();
    Scene scene =new Scene(root, 300, 250);
    root.getChildren().addAll(gridpane);
    primaryStage.setScene(scene);
    primaryStage.show();
    import javafx.beans.property.SimpleStringProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    public class TableClass extends Stage {
         private static TableClass dialog;
         private static String value = "";
         public static class Person {
    private final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;
    private Person(String fName, String lName) {
    this.firstName = new SimpleStringProperty(fName);
    this.lastName = new SimpleStringProperty(lName);
    public String getFirstName() {
    return firstName.get();
    public void setFirstName(String fName) {
    firstName.set(fName);
    public String getLastName() {
    return lastName.get();
    public void setLastName(String fName) {
    lastName.set(fName);
         private TableView<Person> table = new TableView<Person>();
         private final ObservableList<Person> data =
         FXCollections.observableArrayList(
         new Person("JACK", "BROWN"),
         new Person("JOHN", "VIANNEYS"),
         new Person("MICHAEL", "NELSON"),
         new Person("WILLIAM", " CAREY")
         public TableClass(Stage owner, boolean modality, String title) {
              super();
              initOwner(owner);
              Modality m = modality ? Modality.APPLICATION_MODAL : Modality.NONE;
              initModality(m);
              setOpacity(1);
              setTitle(title);
              StackPane root = new StackPane();
              Scene scene = new Scene(root, 750, 750);
              setScene(scene);
              GridPane gridpane = new GridPane();
              gridpane.setPadding(new Insets(5));
              gridpane.setHgap(5);
              gridpane.setVgap(5);
              TableColumn firstNameCol = new TableColumn("First Name");
         firstNameCol.setMinWidth(100);
         firstNameCol.setCellValueFactory(
         new PropertyValueFactory<Person,String>("firstName")
         TableColumn lastNameCol = new TableColumn("Last Name");
         lastNameCol.setMinWidth(200);
         lastNameCol.setCellValueFactory(
         new PropertyValueFactory<Person,String>("lastName")
         table.setItems(data);
         table.getColumns().addAll(firstNameCol, lastNameCol);
         table.setOnMouseClicked(new EventHandler<MouseEvent>() {
                   public void handle(MouseEvent me) {
                        if (me.getClickCount() >= 2) {
                   String srr = table.getItems().get(table.getSelectionModel().getSelectedIndex()).getLastName();
                   value = srr;
                   dialog.hide();
         gridpane.add(table, 1, 5,1,20 );
              root.getChildren().add(gridpane);
         public static String showDialog(Stage stg, Boolean a , String title){
              dialog = new TableClass( stg,a, title);
              dialog.show();
              return value;
    }

  • Get Row and Column info from an Array Cluster

    I have an array with a cluster of 2 elements (string and double). Within my application, I am using the State Machine architecture with an Event Structure. When I click on a element within the cluster array, is there a way to retrieve the row and column? I seen the Coordinates within the Mouse Down event but I don't think that will work.
    Any ideas?
    Solved!
    Go to Solution.

    How To Return the Index of a Mouse-Select Array Element:
    https://decibel.ni.com/content/docs/DOC-6406
    Jean-Marc
    LV2009 and LV2013
    Free PDF Report with iTextSharp

  • Maximum number of rows and columns in data form

    Hi,
    I wanted to know if there is a limitation to the number of rows and columns that can be displayed in a data form, in Hyperion planning 11.1.2.1 ?
    And what would be the most appropriate number of rows and columns to be included for optimum performance.
    Thanks.

    Hi,
    While its a fun fact to determine how much one can stuff into a web form, the reality is: how much can a user reasonably consume in a web form?
    And what would be the most appropriate number of rows and columns to be included for optimum performance
    You will find that the answer to this is by "what design makes a web form most usable?" And no, the users don't really know what they want from a design perspective, they see it in their head, but usually what they ask for is something that would look entirely different (huge).
    The next thing to think about is the use of member selection functions in the page axis. IDescendants(Entity) in a dropdown could cause issues just as easily as too many rows - and again make the drop down unusable for a user.
    If your question is a bit more technical, then consider this (somewhat oversimplified): Web forms are constructed by a process on the server. Objects are created based on the form's definition and used by the process that builds the form. The process uses Cartesian looping (lots of iterations) to construct the form cell by cell, starting at the top left and finishing up in the bottom right. If the form has a million cells on it, then the loop and all the code within it runs a million times. The capability of the server has a lot to do with how well it can handle this request, and how many it can handle at one time.
    The result of this is gobs of HTML and JavaScript. All of this has to be sent over a network to the requesting client. The client starts receiving the web page code and has to render it in the browser and run the JavaScript. The ability to do this is limited by the browser, the OS, and the hardware that the client is running on.
    And that's just rendering the page for use.
    Now it has to be interacted with on the client machine, and changes parsed, packaged, and sent back to the server.
    So the technical answer is, there can be many limitations to how many rows and columns a data form can have - none of which can truly be anticipated by anyone. This is why I put the part about usability first in this post.
    Regards,
    Robb Salzmann

  • Setup for discoverer table for showing number of Rows and columns of Report

    As oracle discoverer report show "Rows 1-25 of"(Total rows) and "Column 1-6 Of"(Total Column).
    This total rows and columns information's is not appearing on our reports.
    Kindly let us know its setting/setups .
    This is very urgent to us, Any help will be highly appreciated.
    Thanks, Avaneesh

    Hmm, what version of Discoverer are you on? Do I understand you correctly that you are able to run a Discoverer report and see this rows and columns information? What software are you running when you do this - Viewer, Plus, or Desktop? Where is this showing up - the top of the report maybe? Or maybe the bottom of the report? The only thing I can think of to handle this is the Page Setup for a workbook, and looking at the Header and Footer sections of that setup. But I am on Discoverer 10.1.2.2 and I don't see anything I can insert on the header/footer that would show this kind of information. Desktop will let you do Page x of y pages (Plus does not), but that is not what you are seeing. You can maybe look at the page setup and see if there is something there not documented in the Discoverer guides.
    John Dickey

Maybe you are looking for

  • How do I select a data source for my webapp?

    Wel, I'm obviously not looking in the right manual because this ought to be like falling off a log! I have developed a web application in JDeveloper 10.1.3 and I'm deploying it (using a WAR file) to an OC4J container in OAS 10.1.3. I have created a J

  • Page headers missing

    All my document headers have disappeared after updating to Numbers 3. A message appears informing me the Spotlight information has been removed. How can I get my headers and footers back? Where is Page View?

  • HT1766 Are my backed up files accessible (Texts, photos, videos, etc) ? and can I delete them?

    Thanks!

  • I can't install any extension in Safari 5.1.9.

    Hello, I am trying to install an extension to Safari (5.1.9.) however I get an error message after which the install button disappears and it says: Install Failed. Please try again later. - I have tried deleting the user/library/caches/com.apple.Safa

  • "Expired" messages

    I've gotten a couple of strange texts in the last 24 hours that says .."Message to {phone number} expired".  What makes it especially strange is that it is referring to a number of a person that never answered the last few texts last week....because