JTable Examples #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

# 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 COLUMNS = 4;
  private final int ROWS = 15;
  private JTable sampleJTable;

  public JTableSimpleExample() {
    super("Creating a Simple JTable");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();

    String[]   columnNames = buildColumnNames(COLUMNS);
    String[][] tableCells = buildTableCells(ROWS, COLUMNS);

    sampleJTable = new JTable(tableCells, columnNames);
    JScrollPane tablePane = new JScrollPane(sampleJTable);
    content.add(tablePane, BorderLayout.CENTER);
    setSize(450,150);
    setVisible(true);
  }

  private String[] buildColumnNames(int columns) {
    String[] header = new String[columns];
    for(int i=0; i<columns ; i++) {
      header[i] = "Column " + i;
    }
    return(header);
  }

  private String[][] buildTableCells(int rows, int columns) {
    String[][] cells = new String[rows][columns];
    for(int i=0; i<rows ; i++) {
      for(int j=0; j<columns; j++ ) {
        cells[i][j] = "Row " + i + ", Col " + j;
      }
    }
    return(cells);
  }
}
*/

# DefaultTableExample.java A dynamic table (rows can be added or deleted) using a DefaultTableModel.

import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;

/** JTable that uses the DefaultTableModel, which permits
 *  adding rows and columns programmatically.
 *
  */

public class DefaultTableExample extends JTable {
  
  private String[] columnNames = 
    { "Flag", "City", "Country", "Comment", "Visited" };

  public DefaultTableExample() {
    this(new DefaultTableModel());
  }
    
  public DefaultTableExample(DefaultTableModel model) {
    super(model);
    
    JavaLocationCollection collection =
      new JavaLocationCollection();
    JavaLocation[] locations = collection.getLocations();

    // Set up the column labels and data for the table model.
    int i;
    for(i=0; i<columnNames.length; i++ ) {
      model.addColumn(columnNames[i]); 
    }
    for(i=0; i<locations.length; i++) {
      model.addRow(getRowData(locations[i]));
    }
  }

  private Vector getRowData(JavaLocation location) {
    Vector vector = new Vector();
    vector.add(new ImageIcon(location.getFlagFile()));
    vector.add("Java");
    vector.add(location.getCountry());
    vector.add(location.getComment());
    vector.add(new Boolean(false));
    return(vector);
  }
  
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();    
    WindowUtilities.openInJFrame(
       new JScrollPane(new DefaultTableExample()), 600, 150, 
                       "Using a DefaultTableModel");
  }
}

# CustomTableExample.java An improved table that uses a CustomTableModel to correctly display cells containing images and boolean values. 
import javax.swing.*;
import javax.swing.table.*;

/** JTable that uses a CustomTableModel to correctly render
 *  the table cells that contain images and boolean values.
 *
*/

public class CustomTableExample extends DefaultTableExample {
  
  public CustomTableExample() {
    super(new CustomTableModel());
    setCellSizes();
  }
    
  private void setCellSizes() {
    setRowHeight(50);
    getColumn("Flag").setMaxWidth(55);
    getColumn("City").setPreferredWidth(60);
    getColumn("Country").setMinWidth(80);
    getColumn("Comment").setMinWidth(150);
    // Call to resize columns in viewport (bug).
    sizeColumnsToFit(JTable.AUTO_RESIZE_OFF);
  }
  
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(
       new JScrollPane(new CustomTableExample()), 525, 255, 
                       "Using a CustomTableModel");
  }
}

    * CustomTableModel.java Returns the class type of a column (for use by the default cell renderers).

import javax.swing.table.*;

/** A custom DefaultTableModel that returns the class
 *  type for the default cell renderers to use. The user is 
 *  restricted to editing only the Comment and Visited columns.
 *
 */

public class CustomTableModel extends DefaultTableModel {
  
  public Class getColumnClass(int column) {
    return(getValueAt(0, column).getClass());
  }

  // Only permit edit of "Comment" and "Visited" columns.
  public boolean isCellEditable(int row, int column) {
    return(column==3 || column==4);
  }
}
**//
    * JavaLocationCollection.java A simple collection of JavaLocation (below) objects.
    * 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 
JTableEvents.java A table that reacts to the user entering data into a cell.
import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

/** A JTable that responds to TableModelEvents and
 *  updates other cells in the table, based on user input.
 *
  */

public class JTableEvents extends JFrame {
  private final int COL_COST     = 1;
  private final int COL_QTY      = 2;
  private final int COL_TOTAL    = 3;
  private final int ROW_LAST     = 5;
  private DecimalFormat df = new DecimalFormat("$####.##");
  private JTable sampleJTable;
  private DefaultTableModel tableModel;

  public static void main(String[] args) {
    new JTableEvents();
  }

  public JTableEvents() {
    super("Using TableEvents");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();

    String[] columnNames = { "Book", "Cost", "Qty", "Total" };

    final Object[][] data = {
      {"Core Web Programming", "$ 0.99", "0", "$0.00"},
      {"Core Servlets and JavaServer Pages",
                               "$34.39", "0", "$0.00"},
      {"Core Swing",           "$39.99", "0", "$0.00"},
      {"Core Java, Volume I",  "$31.49", "0", "$0.00"},
      {"Core Java, Volume II", "$34.39", "0", "$0.00"},
      {null, null,                  "Grand:", "$0.00"} };

    tableModel = new DefaultTableModel(data, columnNames);
    tableModel.addTableModelListener(
      new TableModelListener() {
        int row, col;
        int quantity;
        float cost, subTotal, grandTotal;
        public void tableChanged(TableModelEvent event) {
          row = event.getFirstRow();
          col = event.getColumn();
          // Only update table if a new book quantity entered.
          if (col == COL_QTY) {
            try {
              cost = getFormattedCellValue(row, COL_COST);
              quantity = (int)getFormattedCellValue(row, COL_QTY);
              subTotal = quantity * cost;

              // Update row total.
              tableModel.setValueAt(df.format(subTotal),
                                    row, COL_TOTAL);
              // Update grand total.
              grandTotal =0;
              for(int row=0; row<data.length-1; row++) {
                grandTotal += getFormattedCellValue(row, COL_TOTAL);
              }
              tableModel.setValueAt(df.format(grandTotal),
                                    ROW_LAST,COL_TOTAL);
              tableModel.fireTableDataChanged();
            } catch (NumberFormatException nfe) {
                // Send error message to user.
                JOptionPane.showMessageDialog(
                             JTableEvents.this,
                             "Illegal value entered!");
            }
          }
        }

        private float getFormattedCellValue(int row, int col) {
          String value = (String)tableModel.getValueAt(row, col);
          return(Float.parseFloat(value.replace('$',' ')));
        }
      });

    sampleJTable = new JTable(tableModel);
    setColumnAlignment(sampleJTable.getColumnModel());
    JScrollPane tablePane = new JScrollPane(sampleJTable);

    content.add(tablePane, BorderLayout.CENTER);
    setSize(460,150);
    setVisible(true);
  }

  // Right-align all but the first column.
  private void setColumnAlignment(TableColumnModel tcm) {
    TableColumn column;
    DefaultTableCellRenderer renderer =
      new DefaultTableCellRenderer();
    for(int i=1; i<tcm.getColumnCount(); i++) {
      column = tcm.getColumn(i);
      renderer.setHorizontalAlignment(SwingConstants.RIGHT);
      column.setCellRenderer(renderer);
    }
  }
}
**//

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10301
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada