Java Tutorial/Swing/JTable — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:34, 31 мая 2010
Содержание
- 1 Add 5 spaces to the left and right sides of a cell.
- 2 Allowing the User to Resize a Column in a JTable Component
- 3 Build a table from list data and column names
- 4 Control the selection of rows or columns or individual cells
- 5 Creating a JTable
- 6 Creating a JTable with rows of variable height
- 7 Creating a Scrollable JTable Component
- 8 Creating image out of a JTable
- 9 Deselect all cells
- 10 Deselect a range of columns - columns 0 to 1
- 11 Deselect a range of rows - rows 0 to 1
- 12 Determining If a Cell Is Visible in a JTable Component
- 13 Disable auto resizing to make the table horizontal scrollable
- 14 Disabling User Edits in a JTable
- 15 Don"t show any grid lines
- 16 Enable cell selection in a JTable
- 17 Enable column selection in a JTable
- 18 Enable row selection (default) in a JTable
- 19 Getting the Gap Size Between Cells in a JTable Component
- 20 Getting the Number of Rows and Columns in a JTable Component
- 21 Increase the row height
- 22 JTable Look and Feel
- 23 JTable with Tooltip
- 24 Listening for Changes to the Rows and Columns of a JTable Component
- 25 Listening for Column-Related Changes in a JTable Component
- 26 Listening for Selection Events in a JTable Component
- 27 Listening to JTable Events with a TableModelListener
- 28 Making a Cell Visible in a JTable Component
- 29 Manually Positioning the JTable View
- 30 No user interaction to print
- 31 Print a JTable out
- 32 Printing Tables Sample
- 33 Programmatically Starting Cell Editing in a JTable Component
- 34 public JTable(Vector rowData, Vector columnNames)
- 35 Retrieve the value in cell (rom the model
- 36 Retrieve the value in the visible cell (n a JTable
- 37 Scrolling a Cell to the Center of a JTable Component
- 38 Select a cell: cell (2,1)
- 39 Select a column - column 0 in a JTable
- 40 Select all cells
- 41 Select an additional range of columns - columns 1 to 2
- 42 Select an additional range of rows - rows 1 to 2
- 43 Select a row - row 0
- 44 Selection Modes
- 45 Set the grid color
- 46 Setting Tool Tips on Cells in a JTable Component
- 47 Show both horizontal and vertical grid lines (the default)
- 48 Show only horizontal grid lines
- 49 Show only vertical grid lines
- 50 Specify a page header or footer during printing
- 51 Specify the print mode: public boolean print(JTable.PrintMode printMode)
- 52 Table Selection Events and Listeners
- 53 Table selection mode
- 54 To change cell contents in code: setValueAt(Object value, int row, int column) method of JTable.
- 55 Use a regexFilter to filter table content
- 56 When the width of a column is changed, all columns to the right are resized
- 57 When the width of a column is changed, only the columns to the left and right of the margin change
- 58 When the width of a column is changed, the width of the right-most column is changed
- 59 When the width of a column is changed, the widths of all columns are changed
Add 5 spaces to the left and right sides of a cell.
import java.awt.Dimension;
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
int gapWidth = 10;
int gapHeight = 4;
table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
}
}
Allowing the User to Resize a Column in a JTable Component
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 3;
int cols = 3;
JTable table = new JTable(rows, cols);
table.getTableHeader().setResizingAllowed(false);
}
}
Build a table from list data and column names
import java.util.Arrays;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) {
Vector rowData = new Vector();
for (int i = 0; i < 1; i++) {
Vector colData = new Vector(Arrays.asList("qq"));
rowData.add(colData);
}
String[] columnNames = {"a"};
Vector columnNamesV = new Vector(Arrays.asList(columnNames));
JTable table = new JTable(rowData, columnNamesV);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Control the selection of rows or columns or individual cells
public void setRowSelectionAllowed(boolean flag)
public void setColumnSelectionAllowed(boolean flag)
public void setCellSelectionEnabled(boolean flag)
Creating a JTable
public JTable()
JTable table = new JTable();
public JTable(int rows, int columns)
JTable table = new JTable(2, 3);
public JTable(Object rowData[][], Object columnNames[])
Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3"},
{ "Row2-Column1", "Row2-Column2", "Row2-Column3"} };
Object columnNames[] = { "Column One", "Column Two", "Column Three"};
JTable table = new JTable(rowData, columnNames);
public JTable(TableModel model)
TableModel model = new DefaultTableModel(rowData, columnNames);
JTable table = new JTable(model);
public JTable(TableModel model, TableColumnModel columnModel)
TableColumnModel columnModel = new DefaultTableColumnModel();
TableColumn firstColumn = new TableColumn(1);
firstColumn.setHeaderValue(headers[1]);columnModel.addColumn(firstColumn);
TableColumn secondColumn = new TableColumn(0);
secondColumn.setHeaderValue(headers[0]);
columnModel.addColumn(secondColumn);
JTable table = new JTable(model, columnModel);
public JTable(TableModel model, TableColumnModel columnModel, ListSelectionModel selectionModel)
ListSelectionModel selectionModel = new DefaultListSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JTable table = new JTable(model, columnModel, selectionModel);
Creating a JTable with rows of variable height
import java.awt.Color;
import java.awt.ruponent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class Main {
public static void main(String[] argv) {
JFrame demoFrame = new JFrame("Variable Row Height Table Demo");
StringTableModel imageTableModel = new StringTableModel();
JTable imageTable = new JTable(imageTableModel);
imageTable.getColumnModel().getColumn(0).setCellRenderer(new VariableRowHeightRenderer());
demoFrame.getContentPane().add(new JScrollPane(imageTable));
demoFrame.pack();
demoFrame.setVisible(true);
}
}
class VariableRowHeightRenderer extends JLabel implements TableCellRenderer {
public VariableRowHeightRenderer() {
super();
setOpaque(true);
setHorizontalAlignment(JLabel.CENTER);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (isSelected) {
setBackground(UIManager.getColor("Table.selectionBackground"));
}
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
if (table.isCellEditable(row, column)) {
super.setForeground(UIManager.getColor("Table.focusCellForeground"));
super.setBackground(UIManager.getColor("Table.focusCellBackground"));
}
} else {
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
}
setText((String) (value));
table.setRowHeight(row, getPreferredSize().height + row * 10);
return this;
}
}
class StringTableModel extends AbstractTableModel {
public static final int IMG_COL = 0;
public String[] m_colNames = { "Variable Dimension" };
public Class[] m_colTypes = { String.class };
public StringTableModel() {
super();
}
public int getColumnCount() {
return m_colNames.length;
}
public int getRowCount() {
return 3;
}
public String getColumnName(int col) {
return "" + col;
}
public Object getValueAt(int row, int col) {
return "aa";
}
}
Creating a Scrollable JTable Component
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) {
// Create a table with 10 rows and 5 columns
JTable table = new JTable(10, 5);
// Make the table vertically scrollable
JScrollPane scrollPane = new JScrollPane(table);
}
}
Creating image out of a JTable
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
public class Main {
public static BufferedImage createImage(JTable table) {
JTableHeader tableHeaderComp = table.getTableHeader();
int totalWidth = tableHeaderComp.getWidth() + table.getWidth();
int totalHeight = tableHeaderComp.getHeight() + table.getHeight();
BufferedImage tableImage = new BufferedImage(totalWidth, totalHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2D = (Graphics2D) tableImage.getGraphics();
tableHeaderComp.paint(g2D);
g2D.translate(0, tableHeaderComp.getHeight());
table.paint(g2D);
return tableImage;
}
}
Deselect all cells
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.clearSelection();
}
}
Deselect a range of columns - columns 0 to 1
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.removeColumnSelectionInterval(0, 1);
}
}
Deselect a range of rows - rows 0 to 1
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
table.removeRowSelectionInterval(0, 1);
}
}
Determining If a Cell Is Visible in a JTable Component
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JTable;
import javax.swing.JViewport;
public class Main {
public static void main(String[] argv) {
JTable table = new JTable(10, 5);
int rowIndex = 1;
int vColIndex = 2;
isCellVisible(table, rowIndex, vColIndex);
}
public static boolean isCellVisible(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return false;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Point pt = viewport.getViewPosition();
rect.setLocation(rect.x - pt.x, rect.y - pt.y);
return new Rectangle(viewport.getExtentSize()).contains(rect);
}
}
Disable auto resizing to make the table horizontal scrollable
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) {
// Create a table with 10 rows and 5 columns
JTable table = new JTable(10, 5);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
}
Disabling User Edits in a JTable
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table1 = new JTable() {
public boolean isCellEditable(int rowIndex, int vColIndex) {
return false;
}
};
}
}
Don"t show any grid lines
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setShowGrid(false);
}
}
Enable cell selection in a JTable
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
}
}
Enable column selection in a JTable
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
}
}
Enable row selection (default) in a JTable
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
// Enable row selection (default)
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
}
}
Getting the Gap Size Between Cells in a JTable Component
import java.awt.Dimension;
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
Dimension d = table.getIntercellSpacing();
// d.width == 1, d.height == 1
}
}
Getting the Number of Rows and Columns in a JTable Component
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
Object[][] cellData = { { "1-1", "1-2" }, { "2-1", "2-2" } };
String[] columnNames = { "col1", "col2" };
JTable table = new JTable(cellData, columnNames);
int rows = table.getRowCount();
int cols = table.getColumnCount();
System.out.println(rows);
System.out.println(cols);
}
}
Increase the row height
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setRowHeight(table.getRowHeight() + 3);
}
}
JTable Look and Feel
Property StringObject TypeTable.actionMapActionMapTable.ancestorInputMapInputMapTable.ancestorInputMap.RightToLeftInputMapTable.backgroundColorTable.darkShadowColorTable.focusCellBackgroundColorTable.focusCellForegroundColorTable.focusCellHighlightBorderBorderTable.fontFontTable.foregroundColorTable.gridColorColorTable.highlightColorTable.lightColorTable.rendererUseTableColorsBooleanTable.rendererUseUIBorderBooleanTable.rowHeightIntegerTable.scrollPaneBorderBorderTable.selectionBackgroundColorTable.selectionForegroundColorTable.shadowColorTableUIString
JTable with Tooltip
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* TableToolTipsDemo.java requires no other files.
*/
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
/**
* TableToolTipsDemo is just like TableDemo except that it
* sets up tool tips for both cells and column headers.
*/
public class TableToolTipsDemo extends JPanel {
private boolean DEBUG = false;
protected String[] columnToolTips = {null,
null,
"The person"s favorite sport to participate in",
"The number of years the person has played the sport",
"If checked, the person eats no meat"};
public TableToolTipsDemo() {
super(new GridLayout(1,0));
JTable table = new JTable(new MyTableModel()) {
//Implement table cell tool tips.
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
int realColumnIndex = convertColumnIndexToModel(colIndex);
if (realColumnIndex == 2) { //Sport column
tip = "This person"s favorite sport to "
+ "participate in is: "
+ getValueAt(rowIndex, colIndex);
} else if (realColumnIndex == 4) { //Veggie column
TableModel model = getModel();
String firstName = (String)model.getValueAt(rowIndex,0);
String lastName = (String)model.getValueAt(rowIndex,1);
Boolean veggie = (Boolean)model.getValueAt(rowIndex,4);
if (Boolean.TRUE.equals(veggie)) {
tip = firstName + " " + lastName
+ " is a vegetarian";
} else {
tip = firstName + " " + lastName
+ " is not a vegetarian";
}
} else {
//You can omit this part if you know you don"t
//have any renderers that supply their own tool
//tips.
tip = super.getToolTipText(e);
}
return tip;
}
//Implement table header tool tips.
protected JTableHeader createDefaultTableHeader() {
return new JTableHeader(columnModel) {
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int index = columnModel.getColumnIndexAtX(p.x);
int realIndex = columnModel.getColumn(index).getModelIndex();
return columnToolTips[realIndex];
}
};
}
};
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)}
};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn"t implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don"t need to implement this method unless your table"s
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don"t need to implement this method unless your table"s
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* 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("TableToolTipsDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new TableToolTipsDemo();
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();
}
});
}
}
Listening for Changes to the Rows and Columns of a JTable Component
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.getModel().addTableModelListener(new MyTableModelListener(table));
}
}
class MyTableModelListener implements TableModelListener {
JTable table;
MyTableModelListener(JTable table) {
this.table = table;
}
public void tableChanged(TableModelEvent e) {
int firstRow = e.getFirstRow();
int lastRow = e.getLastRow();
int index = e.getColumn();
switch (e.getType()) {
case TableModelEvent.INSERT:
for (int i = firstRow; i <= lastRow; i++) {
System.out.println(i);
}
break;
case TableModelEvent.UPDATE:
if (firstRow == TableModelEvent.HEADER_ROW) {
if (index == TableModelEvent.ALL_COLUMNS) {
System.out.println("A column was added");
} else {
System.out.println(index + "in header changed");
}
} else {
for (int i = firstRow; i <= lastRow; i++) {
if (index == TableModelEvent.ALL_COLUMNS) {
System.out.println("All columns have changed");
} else {
System.out.println(index);
}
}
}
break;
case TableModelEvent.DELETE:
for (int i = firstRow; i <= lastRow; i++) {
System.out.println(i);
}
break;
}
}
}
Listening for Column-Related Changes in a JTable Component
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.getColumnModel().addColumnModelListener(new MyTableColumnModelListener(table));
}
}
class MyTableColumnModelListener implements TableColumnModelListener {
JTable table;
public MyTableColumnModelListener(JTable table) {
this.table = table;
}
public void columnAdded(TableColumnModelEvent e) {
int fromIndex = e.getFromIndex();
int toIndex = e.getToIndex();
System.out.println(fromIndex);
System.out.println(toIndex);
}
public void columnRemoved(TableColumnModelEvent e) {
int fromIndex = e.getFromIndex();
int toIndex = e.getToIndex();
System.out.println(fromIndex);
System.out.println(toIndex);
}
public void columnMoved(TableColumnModelEvent e) {
int fromIndex = e.getFromIndex();
int toIndex = e.getToIndex();
System.out.println(fromIndex);
System.out.println(toIndex);
}
public void columnMarginChanged(ChangeEvent e) {
System.out.println(e);
}
public void columnSelectionChanged(ListSelectionEvent e) {
System.out.println(e);
}
}
Listening for Selection Events in a JTable Component
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
SelectionListener listener = new SelectionListener(table);
table.getSelectionModel().addListSelectionListener(listener);
table.getColumnModel().getSelectionModel().addListSelectionListener(listener);
}
}
class SelectionListener implements ListSelectionListener {
JTable table;
SelectionListener(JTable table) {
this.table = table;
}
public void valueChanged(ListSelectionEvent e) {
if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) {
int first = e.getFirstIndex();
int last = e.getLastIndex();
} else if (e.getSource() == table.getColumnModel().getSelectionModel()
&& table.getColumnSelectionAllowed()) {
int first = e.getFirstIndex();
int last = e.getLastIndex();
}
if (e.getValueIsAdjusting()) {
System.out.println("The mouse button has not yet been released");
}
}
}
Listening to JTable Events with a TableModelListener
If you want to dynamically update your table data, you can work with a TableModelListener to find out when the data changes. The interface consists of one method that tells you when the table data changes.
public interface TableModelListener extends EventListener {
public void tableChanged(TableModelEvent e);
}
Making a Cell Visible in a JTable Component
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JTable;
import javax.swing.JViewport;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable(10, 5);
int rowIndex = 1;
int vColIndex = 2;
scrollToVisible(table, rowIndex, vColIndex);
}
public static void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Point pt = viewport.getViewPosition();
rect.setLocation(rect.x - pt.x, rect.y - pt.y);
viewport.scrollRectToVisible(rect);
}
}
Manually Positioning the JTable View
To return the position to the origin, you can set the viewport position back to point (0, 0).
scrollPane.getViewport().setViewPosition(new Point(0,0));
No user interaction to print
Show the printer dialog box and configure what the default print request attribute set entails, such as how many copies to print.
public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat,MessageFormat footerFormat, boolean showPrintDialog,PrintRequestAttributeSet attr, boolean interactive)
Print a JTable out
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.print.PrinterException;
public class PrintTable {
public static void main(String[] args) throws Exception {
String[] columns = { "Name", "Age" };
Object[][] content = { { "R", new Integer(24) }, { "A", new Integer(25) },
{ "J", new Integer(30) }, { "A", new Integer(32) }, { "S", new Integer(27) } };
JTable table = new JTable(content, columns);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel(new GridLayout(2, 0));
jPanel.setOpaque(true);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
jPanel.add(new JScrollPane(table));
/* Add the panel to the JFrame */
frame.add(jPanel);
/* Display the JFrame window */
frame.pack();
frame.setVisible(true);
table.print();
}
}
Printing Tables Sample
The print() method returns a boolean, so you can discover if the user canceled the operation.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
public class TablePrint {
public static void main(String args[]) {
final Object rows[][] = {
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
};
final Object headers[] = {"English", "#"};
JFrame frame = new JFrame("Table Printing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table = new JTable(rows, headers);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Print");
ActionListener printAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
table.print();
} catch (PrinterException pe) {
System.err.println("Error printing: " + pe.getMessage());
}
}
};
button.addActionListener(printAction);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Programmatically Starting Cell Editing in a JTable Component
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
int row = 1;
int col = 3;
boolean success = table.editCellAt(row, col);
if (success) {
boolean toggle = false;
boolean extend = false;
table.changeSelection(row, col, toggle, extend);
}
}
}
public JTable(Vector rowData, Vector columnNames)
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class JTableCreatingByVector {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> rowOne = new Vector<String>();
rowOne.addElement("Row1-Column1");
rowOne.addElement("Row1-Column2");
rowOne.addElement("Row1-Column3");
Vector<String> rowTwo = new Vector<String>();
rowTwo.addElement("Row2-Column1");
rowTwo.addElement("Row2-Column2");
rowTwo.addElement("Row2-Column3");
Vector<Vector> rowData = new Vector<Vector>();
rowData.addElement(rowOne);
rowData.addElement(rowTwo);
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Column One");
columnNames.addElement("Column Two");
columnNames.addElement("Column Three");
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Retrieve the value in cell (rom the model
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 3;
int cols = 3;
JTable table = new JTable(rows, cols);
Object o = table.getModel().getValueAt(1, 1);
}
}
Retrieve the value in the visible cell (n a JTable
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 3;
int cols = 3;
JTable table = new JTable(rows, cols);
int rowIndex = 1;
int vColIndex = 2;
Object o = table.getValueAt(rowIndex, vColIndex);
}
}
Scrolling a Cell to the Center of a JTable Component
import java.awt.Rectangle;
import javax.swing.JTable;
import javax.swing.JViewport;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable(5, 5);
int rowIndex = 1;
int vColIndex = 2;
scrollToCenter(table, rowIndex, vColIndex);
}
public static void scrollToCenter(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
rect.setLocation(rect.x - viewRect.x, rect.y - viewRect.y);
int centerX = (viewRect.width - rect.width) / 2;
int centerY = (viewRect.height - rect.height) / 2;
if (rect.x < centerX) {
centerX = -centerX;
}
if (rect.y < centerY) {
centerY = -centerY;
}
rect.translate(centerX, centerY);
viewport.scrollRectToVisible(rect);
}
}
Select a cell: cell (2,1)
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
int row = 2;
int col = 1;
boolean toggle = false;
boolean extend = false;
table.changeSelection(row, col, toggle, extend);
}
}
Select a column - column 0 in a JTable
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
// Select a column - column 0
table.setColumnSelectionInterval(0, 0);
}
}
Select all cells
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
//
table.selectAll();
}
}
Select an additional range of columns - columns 1 to 2
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
// Select an additional range of columns - columns 1 to 2
table.addColumnSelectionInterval(1, 2);
}
}
Select an additional range of rows - rows 1 to 2
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
table.addRowSelectionInterval(1, 2);
}
}
Select a row - row 0
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
table.setRowSelectionInterval(0, 0);
}
}
Selection Modes
- The ListSelectionModel class provides constants for the different selection modes.
- The ListSelectionModel interface and DefaultListSelectionModel are used to describe the current set of rows and columns within the JTable component.
They have three settings:
- MULTIPLE_INTERVAL_SELECTION (the default)
- SINGLE_INTERVAL_SELECTION
- SINGLE_SELECTION
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class SelectionModelTable {
public static void main(String args[]) {
final Object rowData[][] = { { "1", "one", "I" }, { "2", "two", "II" }, { "3", "three", "III" } };
final String columnNames[] = { "#", "English", "Roman" };
final JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Resizing Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Set the grid color
import java.awt.Color;
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setGridColor(Color.red);
}
}
Setting Tool Tips on Cells in a JTable Component
import java.awt.ruponent;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable() {
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) {
Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
if (c instanceof JComponent) {
JComponent jc = (JComponent) c;
jc.setToolTipText((String) getValueAt(rowIndex, vColIndex));
}
return c;
}
};
}
}
Show both horizontal and vertical grid lines (the default)
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setShowGrid(true);
}
}
Show only horizontal grid lines
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setShowGrid(false);
table.setShowHorizontalLines(true);
}
}
Show only vertical grid lines
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
table.setShowGrid(false);
table.setShowVerticalLines(true);
}
}
- MessageFormat comes from the java.text package.
- To display the page number, include {0} in your formatting string.
- Both will appear centered on the page, with the header in a larger font.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class TablePrintMessageFormat {
public static void main(String args[]) {
final Object rows[][] = {
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
};
final Object headers[] = {"English", "#"};
JFrame frame = new JFrame("Table Printing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table = new JTable(rows, headers);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Print");
ActionListener printAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
MessageFormat headerFormat = new MessageFormat("Page {0}");
MessageFormat footerFormat = new MessageFormat("- {0} -");
table.print(JTable.PrintMode.FIT_WIDTH, headerFormat, footerFormat);
} catch (PrinterException pe) {
System.err.println("Error printing: " + pe.getMessage());
}
}
};
button.addActionListener(printAction);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Specify the print mode: public boolean print(JTable.PrintMode printMode)
The JTable.PrintMode argument is an enumeration of FIT_WIDTH(default) and NORMAL.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class TablePrintPrintMode {
public static void main(String args[]) {
final Object rows[][] = {
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
};
final Object headers[] = {"English", "#"};
JFrame frame = new JFrame("Table Printing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table = new JTable(rows, headers);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Print");
ActionListener printAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
table.print(JTable.PrintMode.NORMAL);
} catch (PrinterException pe) {
System.err.println("Error printing: " + pe.getMessage());
}
}
};
button.addActionListener(printAction);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Table Selection Events and Listeners
Whenever a selection is made, the ListSelectionEvent are fired. The method valueChanged() in the interface ListSelectionListener is called whenever a new selection has been made.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JTableListSelectionListener {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table;
String[] columnTitles = { "A", "B", "C", "D" };
Object[][] rowData = { { "11", "12", "13", "14" }, { "21", "22", "23", "24" },
{ "31", "32", "33", "34" }, { "41", "42", "44", "44" } };
table = new JTable(rowData, columnTitles);
table.setCellSelectionEnabled(true);
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedRow.length; i++) {
for (int j = 0; j < selectedColumns.length; j++) {
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});
frame.add(new JScrollPane(table));
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Table selection mode
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* SimpleTableSelectionDemo.java requires no other files.
*/
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/**
* SimpleTableSelectionDemo is just like SimpleTableDemo, except that it detects
* selections, printing information about the current selection to standard
* output.
*/
public class SimpleTableSelectionDemo extends JPanel {
private boolean DEBUG = false;
private boolean ALLOW_COLUMN_SELECTION = false;
private boolean ALLOW_ROW_SELECTION = true;
public SimpleTableSelectionDemo() {
super(new GridLayout(1, 0));
final String[] columnNames = { "First Name", "Last Name", "Sport",
"# of Years", "Vegetarian" };
final Object[][] data = {
{ "Mary", "Campione", "Snowboarding", new Integer(5),
new Boolean(false) },
{ "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
{ "Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false) },
{ "Sharon", "Zakhour", "Speed reading", new Integer(20),
new Boolean(true) },
{ "Philip", "Milne", "Pool", new Integer(10), new Boolean(false) } };
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (ALLOW_ROW_SELECTION) { // true by default
ListSelectionModel rowSM = table.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// Ignore extra messages.
if (e.getValueIsAdjusting())
return;
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
if (lsm.isSelectionEmpty()) {
System.out.println("No rows are selected.");
} else {
int selectedRow = lsm.getMinSelectionIndex();
System.out.println("Row " + selectedRow + " is now selected.");
}
}
});
} else {
table.setRowSelectionAllowed(false);
}
if (ALLOW_COLUMN_SELECTION) { // false by default
if (ALLOW_ROW_SELECTION) {
// We allow both row and column selection, which
// implies that we *really* want to allow individual
// cell selection.
table.setCellSelectionEnabled(true);
}
table.setColumnSelectionAllowed(true);
ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
colSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// Ignore extra messages.
if (e.getValueIsAdjusting())
return;
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
if (lsm.isSelectionEmpty()) {
System.out.println("No columns are selected.");
} else {
int selectedCol = lsm.getMinSelectionIndex();
System.out.println("Column " + selectedCol + " is now selected.");
}
}
});
}
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);
}
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("--------------------------");
}
/**
* 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("SimpleTableSelectionDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
SimpleTableSelectionDemo newContentPane = new SimpleTableSelectionDemo();
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();
}
});
}
}
To change cell contents in code: setValueAt(Object value, int row, int column) method of JTable.
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class SetEditableTableCell {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> rowOne = new Vector<String>();
rowOne.addElement("Row1-Column1");
rowOne.addElement("Row1-Column2");
rowOne.addElement("Row1-Column3");
Vector<String> rowTwo = new Vector<String>();
rowTwo.addElement("Row2-Column1");
rowTwo.addElement("Row2-Column2");
rowTwo.addElement("Row2-Column3");
Vector<Vector> rowData = new Vector<Vector>();
rowData.addElement(rowOne);
rowData.addElement(rowTwo);
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Column One");
columnNames.addElement("Column Two");
columnNames.addElement("Column Three");
JTable table = new JTable(rowData, columnNames);
table.setValueAt("aa", 0, 0);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Use a regexFilter to filter table content
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.PatternSyntaxException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame("Sorting JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyTableModel model = new MyTableModel();
JTable table = new JTable(model);
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane pane = new JScrollPane(table);
frame.add(pane, BorderLayout.CENTER);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
final JTextField filterText = new JTextField("Y");
panel.add(filterText, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
JButton button = new JButton("Filter");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
try {
sorter.setRowFilter(RowFilter.regexFilter(text));
} catch (PatternSyntaxException pse) {
System.err.println("Bad regex pattern");
}
}
});
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 250);
frame.setVisible(true);
}
}
class MyTableModel extends DefaultTableModel {
Object rows[][] = { { "A", "A", 1 }, { "E", "E", 4 }, { "Y", "Y", 3 } };
String columns[] = { "Symbol", "Name", "Price" };
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
}
When the width of a column is changed, all columns to the right are resized
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
Object[][] cellData = { { "1-1", "1-2" }, { "2-1", "2-2" } };
String[] columnNames = { "col1", "col2" };
JTable table = new JTable(cellData, columnNames);
table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
}
}
When the width of a column is changed, only the columns to the left and right of the margin change
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
Object[][] cellData = { { "1-1", "1-2" }, { "2-1", "2-2" } };
String[] columnNames = { "col1", "col2" };
JTable table = new JTable(cellData, columnNames);
table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
}
}
When the width of a column is changed, the width of the right-most column is changed
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
Object[][] cellData = { { "1-1", "1-2" }, { "2-1", "2-2" } };
String[] columnNames = { "col1", "col2" };
JTable table = new JTable(cellData, columnNames);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
}
}
When the width of a column is changed, the widths of all columns are changed
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
Object[][] cellData = { { "1-1", "1-2" }, { "2-1", "2-2" } };
String[] columnNames = { "col1", "col2" };
JTable table = new JTable(cellData, columnNames);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
}
}