{"id":27192,"date":"2021-05-13T23:10:07","date_gmt":"2021-05-14T03:10:07","guid":{"rendered":"http:\/\/bangla.salearningschool.com\/recent-posts\/jtable-examples-programming-code-examples-java-j2ee-j2me-advanced-swing\/"},"modified":"2021-05-13T23:10:07","modified_gmt":"2021-05-14T03:10:07","slug":"jtable-examples-programming-code-examples-java-j2ee-j2me-advanced-swing","status":"publish","type":"post","link":"http:\/\/bangla.sitestree.com\/?p=27192","title":{"rendered":"JTable Examples #Programming Code Examples #Java\/J2EE\/J2ME #Advanced Swing"},"content":{"rendered":"<pre>\n# JTableSimpleExample.java Simple table that takes column names and data from arrays of Strings.\n\nimport java.awt.*;\nimport javax.swing.*;\n\n\/** Simple JTable example that uses a String array for the\n *  table header and table data.\n *\n *\/\n\npublic class JTableSimpleExample extends JFrame {\n  public static void main(String[] args) {\n    new JTableSimpleExample();\n  }\n\n  private final int COLUMNS = 4;\n  private final int ROWS = 15;\n  private JTable sampleJTable;\n\n  public JTableSimpleExample() {\n    super(&quot;Creating a Simple JTable&quot;);\n    WindowUtilities.setNativeLookAndFeel();\n    addWindowListener(new ExitListener());\n    Container content = getContentPane();\n\n    String[]   columnNames = buildColumnNames(COLUMNS);\n    String[][] tableCells = buildTableCells(ROWS, COLUMNS);\n\n    sampleJTable = new JTable(tableCells, columnNames);\n    JScrollPane tablePane = new JScrollPane(sampleJTable);\n    content.add(tablePane, BorderLayout.CENTER);\n    setSize(450,150);\n    setVisible(true);\n  }\n\n  private String[] buildColumnNames(int columns) {\n    String[] header = new String[columns];\n    for(int i=0; i&lt;columns ; i++) {\n      header[i] = &quot;Column &quot; + i;\n    }\n    return(header);\n  }\n\n  private String[][] buildTableCells(int rows, int columns) {\n    String[][] cells = new String[rows][columns];\n    for(int i=0; i&lt;rows ; i++) {\n      for(int j=0; j&lt;columns; j++ ) {\n        cells[i][j] = &quot;Row &quot; + i + &quot;, Col &quot; + j;\n      }\n    }\n    return(cells);\n  }\n}\n*\/\n\n# DefaultTableExample.java A dynamic table (rows can be added or deleted) using a DefaultTableModel.\n\nimport java.util.Vector;\nimport javax.swing.*;\nimport javax.swing.table.*;\n\n\/** JTable that uses the DefaultTableModel, which permits\n *  adding rows and columns programmatically.\n *\n  *\/\n\npublic class DefaultTableExample extends JTable {\n  \n  private String[] columnNames = \n    { &quot;Flag&quot;, &quot;City&quot;, &quot;Country&quot;, &quot;Comment&quot;, &quot;Visited&quot; };\n\n  public DefaultTableExample() {\n    this(new DefaultTableModel());\n  }\n    \n  public DefaultTableExample(DefaultTableModel model) {\n    super(model);\n    \n    JavaLocationCollection collection =\n      new JavaLocationCollection();\n    JavaLocation[] locations = collection.getLocations();\n\n    \/\/ Set up the column labels and data for the table model.\n    int i;\n    for(i=0; i&lt;columnNames.length; i++ ) {\n      model.addColumn(columnNames[i]); \n    }\n    for(i=0; i&lt;locations.length; i++) {\n      model.addRow(getRowData(locations[i]));\n    }\n  }\n\n  private Vector getRowData(JavaLocation location) {\n    Vector vector = new Vector();\n    vector.add(new ImageIcon(location.getFlagFile()));\n    vector.add(&quot;Java&quot;);\n    vector.add(location.getCountry());\n    vector.add(location.getComment());\n    vector.add(new Boolean(false));\n    return(vector);\n  }\n  \n  public static void main(String[] args) {\n    WindowUtilities.setNativeLookAndFeel();    \n    WindowUtilities.openInJFrame(\n       new JScrollPane(new DefaultTableExample()), 600, 150, \n                       &quot;Using a DefaultTableModel&quot;);\n  }\n}\n\n# CustomTableExample.java An improved table that uses a CustomTableModel to correctly display cells containing images and boolean values. \nimport javax.swing.*;\nimport javax.swing.table.*;\n\n\/** JTable that uses a CustomTableModel to correctly render\n *  the table cells that contain images and boolean values.\n *\n*\/\n\npublic class CustomTableExample extends DefaultTableExample {\n  \n  public CustomTableExample() {\n    super(new CustomTableModel());\n    setCellSizes();\n  }\n    \n  private void setCellSizes() {\n    setRowHeight(50);\n    getColumn(&quot;Flag&quot;).setMaxWidth(55);\n    getColumn(&quot;City&quot;).setPreferredWidth(60);\n    getColumn(&quot;Country&quot;).setMinWidth(80);\n    getColumn(&quot;Comment&quot;).setMinWidth(150);\n    \/\/ Call to resize columns in viewport (bug).\n    sizeColumnsToFit(JTable.AUTO_RESIZE_OFF);\n  }\n  \n  public static void main(String[] args) {\n    WindowUtilities.setNativeLookAndFeel();\n    WindowUtilities.openInJFrame(\n       new JScrollPane(new CustomTableExample()), 525, 255, \n                       &quot;Using a CustomTableModel&quot;);\n  }\n}\n\n    * CustomTableModel.java Returns the class type of a column (for use by the default cell renderers).\n\nimport javax.swing.table.*;\n\n\/** A custom DefaultTableModel that returns the class\n *  type for the default cell renderers to use. The user is \n *  restricted to editing only the Comment and Visited columns.\n *\n *\/\n\npublic class CustomTableModel extends DefaultTableModel {\n  \n  public Class getColumnClass(int column) {\n    return(getValueAt(0, column).getClass());\n  }\n\n  \/\/ Only permit edit of &quot;Comment&quot; and &quot;Visited&quot; columns.\n  public boolean isCellEditable(int row, int column) {\n    return(column==3 || column==4);\n  }\n}\n**\/\/\n    * JavaLocationCollection.java A simple collection of JavaLocation (below) objects.\n    * JavaLocation.java An object representing a city named Java. Defines the country where the Java city is located, along with a comment and country flag \nJTableEvents.java A table that reacts to the user entering data into a cell.\nimport java.awt.*;\nimport java.text.DecimalFormat;\nimport javax.swing.*;\nimport javax.swing.event.*;\nimport javax.swing.table.*;\n\n\/** A JTable that responds to TableModelEvents and\n *  updates other cells in the table, based on user input.\n *\n  *\/\n\npublic class JTableEvents extends JFrame {\n  private final int COL_COST     = 1;\n  private final int COL_QTY      = 2;\n  private final int COL_TOTAL    = 3;\n  private final int ROW_LAST     = 5;\n  private DecimalFormat df = new DecimalFormat(&quot;$####.##&quot;);\n  private JTable sampleJTable;\n  private DefaultTableModel tableModel;\n\n  public static void main(String[] args) {\n    new JTableEvents();\n  }\n\n  public JTableEvents() {\n    super(&quot;Using TableEvents&quot;);\n    WindowUtilities.setNativeLookAndFeel();\n    addWindowListener(new ExitListener());\n    Container content = getContentPane();\n\n    String[] columnNames = { &quot;Book&quot;, &quot;Cost&quot;, &quot;Qty&quot;, &quot;Total&quot; };\n\n    final Object[][] data = {\n      {&quot;Core Web Programming&quot;, &quot;$ 0.99&quot;, &quot;0&quot;, &quot;$0.00&quot;},\n      {&quot;Core Servlets and JavaServer Pages&quot;,\n                               &quot;$34.39&quot;, &quot;0&quot;, &quot;$0.00&quot;},\n      {&quot;Core Swing&quot;,           &quot;$39.99&quot;, &quot;0&quot;, &quot;$0.00&quot;},\n      {&quot;Core Java, Volume I&quot;,  &quot;$31.49&quot;, &quot;0&quot;, &quot;$0.00&quot;},\n      {&quot;Core Java, Volume II&quot;, &quot;$34.39&quot;, &quot;0&quot;, &quot;$0.00&quot;},\n      {null, null,                  &quot;Grand:&quot;, &quot;$0.00&quot;} };\n\n    tableModel = new DefaultTableModel(data, columnNames);\n    tableModel.addTableModelListener(\n      new TableModelListener() {\n        int row, col;\n        int quantity;\n        float cost, subTotal, grandTotal;\n        public void tableChanged(TableModelEvent event) {\n          row = event.getFirstRow();\n          col = event.getColumn();\n          \/\/ Only update table if a new book quantity entered.\n          if (col == COL_QTY) {\n            try {\n              cost = getFormattedCellValue(row, COL_COST);\n              quantity = (int)getFormattedCellValue(row, COL_QTY);\n              subTotal = quantity * cost;\n\n              \/\/ Update row total.\n              tableModel.setValueAt(df.format(subTotal),\n                                    row, COL_TOTAL);\n              \/\/ Update grand total.\n              grandTotal =0;\n              for(int row=0; row&lt;data.length-1; row++) {\n                grandTotal += getFormattedCellValue(row, COL_TOTAL);\n              }\n              tableModel.setValueAt(df.format(grandTotal),\n                                    ROW_LAST,COL_TOTAL);\n              tableModel.fireTableDataChanged();\n            } catch (NumberFormatException nfe) {\n                \/\/ Send error message to user.\n                JOptionPane.showMessageDialog(\n                             JTableEvents.this,\n                             &quot;Illegal value entered!&quot;);\n            }\n          }\n        }\n\n        private float getFormattedCellValue(int row, int col) {\n          String value = (String)tableModel.getValueAt(row, col);\n          return(Float.parseFloat(value.replace(&#039;$&#039;,&#039; &#039;)));\n        }\n      });\n\n    sampleJTable = new JTable(tableModel);\n    setColumnAlignment(sampleJTable.getColumnModel());\n    JScrollPane tablePane = new JScrollPane(sampleJTable);\n\n    content.add(tablePane, BorderLayout.CENTER);\n    setSize(460,150);\n    setVisible(true);\n  }\n\n  \/\/ Right-align all but the first column.\n  private void setColumnAlignment(TableColumnModel tcm) {\n    TableColumn column;\n    DefaultTableCellRenderer renderer =\n      new DefaultTableCellRenderer();\n    for(int i=1; i&lt;tcm.getColumnCount(); i++) {\n      column = tcm.getColumn(i);\n      renderer.setHorizontalAlignment(SwingConstants.RIGHT);\n      column.setCellRenderer(renderer);\n    }\n  }\n}\n**\/\/\n<\/pre>\n<p>Note: Brought from our old site: http:\/\/www.salearningschool.com\/example_codes\/ on Jan 2nd, 2017 From: http:\/\/sitestree.com\/?p=10301<br \/> Categories:Programming Code Examples, Java\/J2EE\/J2ME, Advanced Swing<br \/>Tags:Java\/J2EE\/J2MEAdvanced Swing<br \/> Post Data:2017-01-02 16:04:31<\/p>\n<p>\t\tShop Online: <a href='https:\/\/www.ShopForSoul.com\/' target='new' rel=\"noopener\">https:\/\/www.ShopForSoul.com\/<\/a><br \/>\n\t\t(Big Data, Cloud, Security, Machine Learning): Courses: <a href='http:\/\/Training.SitesTree.com' target='new' rel=\"noopener\"> http:\/\/Training.SitesTree.com<\/a><br \/>\n\t\tIn Bengali: <a href='http:\/\/Bangla.SaLearningSchool.com' target='new' rel=\"noopener\">http:\/\/Bangla.SaLearningSchool.com<\/a><br \/>\n\t\t<a href='http:\/\/SitesTree.com' target='new' rel=\"noopener\">http:\/\/SitesTree.com<\/a><br \/>\n\t\t8112223 Canada Inc.\/JustEtc: <a href='http:\/\/JustEtc.net' target='new' rel=\"noopener\">http:\/\/JustEtc.net (Software\/Web\/Mobile\/Big-Data\/Machine Learning) <\/a><br \/>\n\t\tShop Online: <a href='https:\/\/www.ShopForSoul.com'> https:\/\/www.ShopForSoul.com\/<\/a><br \/>\n\t\tMedium: <a href='https:\/\/medium.com\/@SayedAhmedCanada' target='new' rel=\"noopener\"> https:\/\/medium.com\/@SayedAhmedCanada <\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p># JTableSimpleExample.java Simple table that takes column names and data from arrays of Strings. import java.awt.*; import javax.swing.*; \/** Simple JTable example that uses a String array for the * table header and table data. * *\/ public class JTableSimpleExample extends JFrame { public static void main(String[] args) { new JTableSimpleExample(); } private final int &hellip; <\/p>\n<p><a class=\"more-link btn\" href=\"http:\/\/bangla.sitestree.com\/?p=27192\">Continue reading<\/a><\/p>\n","protected":false},"author":8,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[1917],"tags":[],"class_list":["post-27192","post","type-post","status-publish","format-standard","hentry","category-fromsitestree-com","item-wrap"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":10269,"url":"http:\/\/bangla.sitestree.com\/?p=10269","url_meta":{"origin":27192,"position":0},"title":"JTable Examples","author":"","date":"August 26, 2015","format":false,"excerpt":"# JTableSimpleExample.java Simple table that takes column names and data from arrays of Strings. import java.awt.*; import javax.swing.*; \/** Simple JTable example that uses a String array for the \u00a0*\u00a0 table header and table data. \u00a0* \u00a0*\/ public class JTableSimpleExample extends JFrame { \u00a0 public static void main(String[] args) {\u2026","rel":"","context":"In &quot;Code . Programming Samples . \u09aa\u09cd\u09b0\u09cb\u0997\u09cd\u09b0\u09be\u09ae \u0989\u09a6\u09be\u09b9\u09b0\u09a8&quot;","block_context":{"text":"Code . Programming Samples . \u09aa\u09cd\u09b0\u09cb\u0997\u09cd\u09b0\u09be\u09ae \u0989\u09a6\u09be\u09b9\u09b0\u09a8","link":"http:\/\/bangla.sitestree.com\/?cat=1417"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":26850,"url":"http:\/\/bangla.sitestree.com\/?p=26850","url_meta":{"origin":27192,"position":1},"title":"QueryViewer.java: An interactive database query viewer #Programming Code Examples #Java\/J2EE\/J2ME #JDBC","author":"Author-Check- Article-or-Video","date":"May 3, 2021","format":false,"excerpt":"# QueryViewer.java An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file: * DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used to\u2026","rel":"","context":"In &quot;FromSitesTree.com&quot;","block_context":{"text":"FromSitesTree.com","link":"http:\/\/bangla.sitestree.com\/?cat=1917"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":10128,"url":"http:\/\/bangla.sitestree.com\/?p=10128","url_meta":{"origin":27192,"position":2},"title":"extract relevant data from a DBResults","author":"","date":"August 6, 2015","format":false,"excerpt":"# QueryViewer.java\u00a0 An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file: \u00a0\u00a0\u00a0 * DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used\u2026","rel":"","context":"In &quot;Code . Programming Samples . \u09aa\u09cd\u09b0\u09cb\u0997\u09cd\u09b0\u09be\u09ae \u0989\u09a6\u09be\u09b9\u09b0\u09a8&quot;","block_context":{"text":"Code . Programming Samples . \u09aa\u09cd\u09b0\u09cb\u0997\u09cd\u09b0\u09be\u09ae \u0989\u09a6\u09be\u09b9\u09b0\u09a8","link":"http:\/\/bangla.sitestree.com\/?cat=1417"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":10126,"url":"http:\/\/bangla.sitestree.com\/?p=10126","url_meta":{"origin":27192,"position":3},"title":"QueryViewer.java: An interactive database query viewer","author":"","date":"August 8, 2015","format":false,"excerpt":"# QueryViewer.java\u00a0 An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file: \u00a0\u00a0\u00a0 * DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used\u2026","rel":"","context":"In &quot;Code . Programming Samples . \u09aa\u09cd\u09b0\u09cb\u0997\u09cd\u09b0\u09be\u09ae \u0989\u09a6\u09be\u09b9\u09b0\u09a8&quot;","block_context":{"text":"Code . Programming Samples . \u09aa\u09cd\u09b0\u09cb\u0997\u09cd\u09b0\u09be\u09ae \u0989\u09a6\u09be\u09b9\u09b0\u09a8","link":"http:\/\/bangla.sitestree.com\/?cat=1417"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":26852,"url":"http:\/\/bangla.sitestree.com\/?p=26852","url_meta":{"origin":27192,"position":4},"title":"extract relevant data from a DBResults #Programming Code Examples #Java\/J2EE\/J2ME #JDBC","author":"Author-Check- Article-or-Video","date":"May 3, 2021","format":false,"excerpt":"package cwp; import javax.swing.table.*; \/** Simple class that tells a JTable how to extract * relevant data from a DBResults object (which is * used to store the results from a database query). *\/ public class DBResultsTableModel extends AbstractTableModel { private DBResults results; public DBResultsTableModel(DBResults results) { this.results = results;\u2026","rel":"","context":"In &quot;FromSitesTree.com&quot;","block_context":{"text":"FromSitesTree.com","link":"http:\/\/bangla.sitestree.com\/?cat=1917"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":26830,"url":"http:\/\/bangla.sitestree.com\/?p=26830","url_meta":{"origin":27192,"position":5},"title":"DBResults.java: Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways #Programming Code Examples #Java\/J2EE\/J2ME #JDBC","author":"Author-Check- Article-or-Video","date":"May 2, 2021","format":false,"excerpt":"# DBResults.java Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways: * ResultSet doesn?t necessarily have all the data; reconnection to database occurs as you ask for later rows. * This class stores results as strings, in arrays. * This class includes DatabaseMetaData\u2026","rel":"","context":"In &quot;FromSitesTree.com&quot;","block_context":{"text":"FromSitesTree.com","link":"http:\/\/bangla.sitestree.com\/?cat=1917"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=\/wp\/v2\/posts\/27192","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=27192"}],"version-history":[{"count":0,"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=\/wp\/v2\/posts\/27192\/revisions"}],"wp:attachment":[{"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=27192"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=27192"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/bangla.sitestree.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=27192"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}