How to Read in Data Two Rows Down in Java Txt File
With the JTable
class you tin can brandish tables of data, optionally allowing the user to edit the information. JTable
does not contain or enshroud data; it is simply a view of your data. Here is a picture of a typical tabular array displayed within a gyre pane:
The rest of this department shows you how to achieve some common table-related tasks. Here are the topics this department covers:
- Creating a Simple Table
- Adding a Table to a Container
- Setting and Changing Cavalcade Widths
- User Selections
- Creating a Table Model
- Listening for Data Changes
- Firing Data Change Events
- Concepts: Editors and Renderers
- Using Custom Renderers
- Specifying Tool Tips for Cells
- Specifying Tool Tips for Column Headers
- Sorting and Filtering
- Using a Combo Box as an Editor
- Using Other Editors
- Using an Editor to Validate User-Entered Text
- Press
- Examples that Apply Tables
Creating a Simple Tabular array
Attempt this:
-
Click the Launch button to run
SimpleTableDemo
using Java™ Web Start (download JDK vii or later on). Or, to compile and run the example yourself, consult the example index.
-
Click the jail cell that contains "Snowboarding".
The entire get-go row is selected, indicating that you take selected Kathy Smith's data. A special highlight indicates that the "Snowboarding" cell is editable. Generally, yous begin editing a text cell by double-clicking it. -
Position the cursor over "First Name". At present press the mouse button and drag to the correct.
Equally you lot can see, users can rearrange columns in tables. -
Position the cursor merely to the correct of a cavalcade header. Now press the mouse button and drag to the right or left.
The column changes size, and the other columns adjust to fill the remaining space. - Resize the window containing the table and then that it'south bigger than necessary to brandish the whole table.
All the table cells become wider, expanding to fill the extra horizontal infinite.
The table in SimpleTableDemo.java
declares the column names in a Cord assortment:
String[] columnNames = {"First Name", "Last Proper name", "Sport", "# of Years", "Vegetarian"};
Its data is initialized and stored in a two-dimensional Object assortment:
Object[][] data = { {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(fake)}, {"John", "Doe", "Rowing", new Integer(3), new Boolean(truthful)}, {"Sue", "Black", "Knitting", new Integer(ii), new Boolean(fake)}, {"Jane", "White", "Speed reading", new Integer(twenty), new Boolean(true)}, {"Joe", "Chocolate-brown", "Pool", new Integer(10), new Boolean(false)} };
And so the Table is constructed using these data and columnNames:
JTable table = new JTable(data, columnNames);
There are two JTable
constructors that directly accept data (SimpleTableDemo
uses the first):
-
JTable(Object[][] rowData, Object[] columnNames)
-
JTable(Vector rowData, Vector columnNames)
The advantage of these constructors is that they are like shooting fish in a barrel to use. However, these constructors likewise take disadvantages:
- They automatically make every cell editable.
- They treat all information types the aforementioned (as strings). For example, if a table column has
Boolean
data, the tabular array tin can display the data in a check box. Notwithstanding, if yous utilize either of the twoJTable
constructors listed previously, yourBoolean
data is displayed as a string. You can run across this difference in theVegetarian
cavalcade of the previous figure. - They require that you put all of the tabular array's data in an assortment or vector, which may not be advisable for some data. For example, if you are instantiating a set of objects from a database, yous might desire to query the objects directly for their values, rather than copying all their values into an array or vector.
If you desire to get around these restrictions, you need to implement your own tabular array model, as described in Creating a Tabular array Model.
Adding a Table to a Container
Here is typical code for creating a curl pane that serves as a container for a tabular array:
JScrollPane scrollPane = new JScrollPane(table); table.setFillsViewportHeight(truthful);
The two lines in this snippet practice the following:
- The
JScrollPane
constructor is invoked with an argument that refers to the table object. This creates a scroll pane as a container for the tabular array; the table is automatically added to the container. -
JTable.setFillsViewportHeight
is invoked to set thefillsViewportHeight
property. When this property istrue
the table uses the entire height of the container, even if the table doesn't have enough rows to use the whole vertical space. This makes it easier to use the table every bit a drag-and-drop target.
The scroll pane automatically places the tabular array header at the meridian of the viewport. The cavalcade names remain visible at the elevation of the viewing expanse when the tabular array data is scrolled.
If you are using a table without a coil pane, then you lot must go the table header component and identify information technology yourself. For case:
container.setLayout(new BorderLayout()); container.add(tabular array.getTableHeader(), BorderLayout.PAGE_START); container.add(table, BorderLayout.CENTER);
Setting and Changing Column Widths
Past default, all columns in a table outset out with equal width, and the columns automatically fill up the entire width of the table. When the table becomes wider or narrower (which might happen when the user resizes the window containing the table), all the column widths change appropriately.
When the user resizes a cavalcade by dragging its right border, so either other columns must change size, or the table'south size must modify. By default, the tabular array's size remains the same, and all columns to the right of the elevate indicate resize to accommodate space added to or removed from the column to the left of the drag bespeak.
To customize initial column widths, you lot can invoke setPreferredWidth
on each of your table'due south columns. This sets both the preferred widths of the columns and their gauge relative widths. For instance, adding the post-obit code to SimpleTableDemo
makes its third cavalcade bigger than the other columns:
TableColumn column = zilch; for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 2) { column.setPreferredWidth(100); //third column is bigger } else { column.setPreferredWidth(50); } }
As the preceding code shows, each cavalcade in a table is represented by a TableColumn
object. TableColumn
supplies getter and setter methods for the minimum, preferred, and maximum widths of a cavalcade, as well equally a method for getting the current width. For an case of setting cell widths based on an approximation of the space needed to depict the cells' contents, meet the initColumnSizes
method in TableRenderDemo.java
.
When the user explicitly resizes columns, the columns' preferred widths are gear up such that the user-specified sizes go the columns' new current widths. However, when table itself is resized — typically because the window has resized —; the columns' preferred widths do non change. Instead, the existing preferred widths are used to calculate new column widths to fill the bachelor infinite.
Y'all can change a tabular array'south resize behavior by invoking setAutoResizeMode
.
User Selections
In its default configuration, a table supports a selection that consists of one or more than rows. The user can select a contiguous range of rows or an arbitrary set of rows. The last prison cell that the user indicated gets a special indication; in the Metal look and feel, the cell is outlined. This cell is known equally the atomic number 82 choice; it is sometimes chosen "the jail cell with the focus" or "the electric current jail cell".
The user uses the mouse and/or keyboard to make selections, equally described in the following table:
Functioning | Mouse Action | Keyboard Action |
---|---|---|
Select single row. | Click. | Up Arrow or Downwards Pointer. |
Extend contiguous choice. | Shift-Click or Drag over rows. | Shift-Up Arrow or Shift-Down Arrow. |
Add row to selection/toggle row option. | Command-Click | Move atomic number 82 selection with Command-Up Arrow or Control-Downwardly Arrow, so use Space Bar to add to pick or Control-Space Bar to toggle row selection. |
To run into how selections work, click the Launch push to run TableSelectionDemo
using Java™ Web Get-go (download JDK 7 or later). Or, to compile and run the example yourself, consult the example alphabetize.
This example programme presents the familiar table, and allows the user to manipulate certain JTable options. There is also a text pane that logs selection events.
In the screenshot below, a user has run the program, clicked in the get-go row, then control-clicked in the tertiary row. Notice the outline around the last cell clicked; this is how the Metal look and feel highlights the lead option.
Nether "Choice Mode" there are a set of radio buttons. Click the 1 labelled "Single Selection". At present yous can but select one row at a time. If you lot click on the "Single Interval Selection" radio button, yous tin can select a ready of rows that must be contiguous.
All of the radio buttons under "Selection Mode" invoke JTable.setSelectionMode
. This method takes a single argument, which must exist i of the following constants defined in javax.swing.ListSelectionModel
: MULTIPLE_INTERVAL_SELECTION
, SINGLE_INTERVAL_SELECTION
, and SINGLE_SELECTION
.
Returning to TableSelectionDemo
, find the three option cheque boxes under "Selection Options." Each of check box controls the state of a boolean
bound variable defined by JTable
:
- "Row Choice" controls
rowSelectionAllowed
which has setter methodsetRowSelectionAllowed
and getter methodgetRowSelectionAllowed
. When this spring property istrue
(and thecolumnSelectionAllowed
property isfalse
), the user can select by row. - "Column Selection" controls
columnSelectionAllowed
which has setter methodsetColumnSelectionAllowed
and getter methodgetColumnSelectionAllowed
. When this bound belongings istruthful
(and therowSelectionAllowed
bound property isfalse
), the user can select past column. - "Cell Choice" controls
cellSelectionEnabled
, which has setter methodsetCellSelectionEnabled
and getter methodgetCellSelectionEnabled
. When this jump property istrue
, the user can select a unmarried cell or rectangular block of cells.
NOTE:JTable
uses a very elementary concept of pick, managed equally an intersection of rows and columns. It was not designed to handle fully contained prison cell selections.
If you clear all three cheque boxes (setting all three bound properties to false
), there is no option; only the lead choice is shown.
Yous may detect that the "Cell Selection" bank check box is disabled in multiple interval selection style. This is considering prison cell selection is not supported in this mode in the demo. You lot can specify pick past cell in multiple interval selection fashion, but the result is a tabular array that does non produce useful selections.
You may also notice that changing whatsoever of the iii selection options can affect the others. This is because allowing both row selection and column selection is exactly the same equally enabling cell choice. JTable
automatically updates the three bound variables as necessary to proceed them consequent.
Notation: Setting cellSelectionEnabled
to a value has the side effect of also setting both rowSelectionEnabled
and columnSelectionEnabled
to that value. Setting both rowSelectionEnabled
and columnSelectionEnabled
to a value has the side outcome of also setting cellSelectionEnabled
to that value. Setting rowSelectionEnabled
and columnSelectionEnabled
to different values has the side outcome of also setting cellSelectionEnabled
to false
.
To recall the current choice, use JTable.getSelectedRows
which returns an array of row indexes, and JTable.getSelectedColumns
which returns an array of column indexes. To call back the coordinates of the atomic number 82 selection, refer to the choice models for the table itself and for the tabular array'due south cavalcade model. The following lawmaking formats a string containing the row and column of the lead choice:
String.format("Atomic number 82 Selection: %d, %d. ", table.getSelectionModel().getLeadSelectionIndex(), table.getColumnModel().getSelectionModel().getLeadSelectionIndex());
User selections generate a number of events. For data on these, refer to How to Write a List Pick Listener in the Writing Event Listeners lesson.
Notation: Option data really describes selected cells in the "view" (table information as information technology appears afterward whatever sorting or filtering) rather than in the table model. This stardom does not thing unless your viewed information has been rearranged by sorting, filtering, or user manipulation of columns. In that case, you lot must convert selection coordinates using the conversion methods described in Sorting and Filtering.
Creating a Table Model
Every table object uses a table model object to manage the actual table data. A table model object must implement the TableModel
interface. If the developer does non provide a table model object, JTable
automatically creates an instance of DefaultTableModel
. This human relationship is illustrated below.
The JTable
constructor used past SimpleTableDemo
creates its table model with code similar this:
new AbstractTableModel() { public String getColumnName(int col) { render columnNames[col].toString(); } public int getRowCount() { return rowData.length; } public int getColumnCount() { render columnNames.length; } public Object getValueAt(int row, int col) { return rowData[row][col]; } public boolean isCellEditable(int row, int col) { render truthful; } public void setValueAt(Object value, int row, int col) { rowData[row][col] = value; fireTableCellUpdated(row, col); } }
As the preceding code shows, implementing a table model can be simple. Mostly, you implement your table model in a bracket of the AbstractTableModel
form.
Your model might hold its data in an array, vector, or hash map, or it might get the information from an outside source such equally a database. Information technology might even generate the data at execution fourth dimension.
This table is dissimilar from the SimpleTableDemo
table in the following means:
-
TableDemo
's custom table model, even though it is simple, can hands determine the information'south type, helping theJTable
display the data in the best format.SimpleTableDemo
'south automatically created table model, on the other hand, does non know that the # of Years cavalcade contains numbers (which should generally be right aligned and have a particular format). Information technology also does not know that theVegetarian
cavalcade contains boolean values, which tin can be represented past check boxes. - The custom tabular array model implemented in
TableDemo
does not let yous edit the name columns; it does, however, let y'all edit the other columns. InSimpleTableDemo
, all cells are editable.
See below the code taken from TableDemo.java
that is different from the SimpleTableDemo.java
. Bold font indicates the code that makes this table's model different from the table model divers automatically for SimpleTableDemo
.
public TableDemo() { ... JTable table = new JTable(new MyTableModel()); ... } grade MyTableModel extends AbstractTableModel { individual String[] columnNames = ...//same every bit earlier... private Object[][] data = ...//same as before... 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) { render data[row][col]; } public Class getColumnClass(int c) { render getValueAt(0, c).getClass(); } /* * Don't demand to implement this method unless your tabular array's * editable. */ public boolean isCellEditable(int row, int col) { //Notation that the data/cell address is constant, //no matter where the jail cell appears onscreen. if (col < 2) { render false; } else { return true; } } /* * Don't need to implement this method unless your table'due south * data tin can change. */ public void setValueAt(Object value, int row, int col) { information[row][col] = value; fireTableCellUpdated(row, col); } ... }
Listening for Information Changes
A table model tin take a fix of listeners that are notified whenever the table data changes. Listeners are instances of TableModelListener
. In the following example code, SimpleTableDemo
is extended to include such a listener. New code is in assuming.
import javax.swing.outcome.*; import javax.swing.table.TableModel; public form SimpleTableDemo ... implements TableModelListener { ... public SimpleTableDemo() { ... tabular array.getModel().addTableModelListener(this); ... } public void tableChanged(TableModelEvent e) { int row = e.getFirstRow(); int cavalcade = east.getColumn(); TableModel model = (TableModel)e.getSource(); Cord columnName = model.getColumnName(column); Object data = model.getValueAt(row, column); ...// Do something with the information... } ... }
Firing Data Change Events
In social club to fire information change events the table model must know how to construct a TableModelEvent
object. This can exist a complex process, just is already implemented in DefaultTableModel
. Y'all can either allow JTable
to use its default instance of DefaultTableModel
, or create your ain custom subclass of DefaultTableModel
.
If DefaultTableModel
is non a suitable base class for your custom table model course, consider subclassing AbstractTableModel
. This grade implements a simple framework for constructing TableModelEvent
objects. Your custom class simply needs to invoke ane the following AbstractTableModel
methods each fourth dimension table data is changed by an external source.
Method | Change |
---|---|
fireTableCellUpdated | Update of specified prison cell. |
fireTableRowsUpdated | Update of specified rows |
fireTableDataChanged | Update of unabridged table (data but). |
fireTableRowsInserted | New rows inserted. |
fireTableRowsDeleted | Existing rows Deleted |
fireTableStructureChanged | Invalidate unabridged table, both data and structure. |
Concepts: Editors and Renderers
Before you go on to the next few tasks, you need to empathize how tables draw their cells. You might wait each cell in a table to be a component. However, for performance reasons, Swing tables are implemented differently.
Instead, a single cell renderer is generally used to depict all of the cells that contain the same type of data. Yous can remember of the renderer equally a configurable ink stamp that the table uses to stamp accordingly formatted data onto each prison cell. When the user starts to edit a jail cell's information, a cell editor takes over the cell, controlling the cell's editing behavior.
For instance, each cell in the # of Years column in TableDemo
contains Number
data — specifically, an Integer
object. By default, the cell renderer for a Number
-containing column uses a unmarried JLabel
instance to describe the appropriate numbers, right-aligned, on the cavalcade's cells. If the user begins editing one of the cells, the default cell editor uses a right-aligned JTextField
to control the cell editing.
To choose the renderer that displays the cells in a column, a tabular array first determines whether yous specified a renderer for that detail column. If you lot did not, then the table invokes the table model's getColumnClass
method, which gets the information blazon of the cavalcade's cells. Adjacent, the table compares the cavalcade'due south data type with a list of data types for which cell renderers are registered. This listing is initialized by the table, but you can add together to it or alter information technology. Currently, tables put the post-obit types of data in the list:
-
Boolean
— rendered with a check box. -
Number
— rendered by a correct-aligned label. -
Double
,Float
— aforementioned asNumber
, but the object-to-text translation is performed by aNumberFormat
instance (using the default number format for the electric current locale). -
Date
— rendered by a label, with the object-to-text translation performed by aDateFormat
instance (using a curt style for the date and fourth dimension). -
ImageIcon
,Icon
— rendered past a centered label. -
Object
— rendered by a label that displays the object'due south string value.
Cell editors are chosen using a like algorithm.
Remember that if you allow a table create its ain model, it uses Object
every bit the blazon of every column. To specify more than precise cavalcade types, the table model must define the getColumnClass
method appropriately, as demonstrated past TableDemo.coffee
.
Proceed in listen that although renderers determine how each cell or column header looks and can specify its tool tip text, a renderer does not handle events. If you need to pick upwards the events that accept place inside a table, the technique you lot employ varies by the sort of event you are interested in:
Situation | How to Get Events |
---|---|
To detect events from a prison cell that is being edited... | Employ the cell editor (or register a listener on the jail cell editor). |
To detect row/column/cell selections and deselections... | Use a pick listener as described in Detecting User Selections. |
To discover mouse events on a cavalcade header... | Register the appropriate type of mouse listener on the table's JTableHeader object. (Come across TableSorter.coffee for an example.) |
To notice other events... | Register the appropriate listener on the JTable object. |
The adjacent few sections tell yous how to customize brandish and editing by specifying renderers and editors. You can specify cell renderers and editors either by column or by data blazon.
Using Custom Renderers
This section tells you how to create and specify a cell renderer. Y'all can prepare a type-specific cell renderer using the JTable
method setDefaultRenderer
. To specify that cells in a item column should use a renderer, you use the TableColumn
method setCellRenderer
. You tin can fifty-fifty specify a cell-specific renderer by creating a JTable
subclass.
Information technology is easy to customize the text or prototype rendered past the default renderer, DefaultTableCellRenderer
. You just create a subclass and implement the setValue
method so that it invokes setText
or setIcon
with the appropriate string or prototype. For example, here is how the default engagement renderer is implemented:
static class DateRenderer extends DefaultTableCellRenderer { DateFormat formatter; public DateRenderer() { super(); } public void setValue(Object value) { if (formatter==null) { formatter = DateFormat.getDateInstance(); } setText((value == nil) ? "" : formatter.format(value)); } }
If extending DefaultTableCellRenderer
is bereft, you can build a renderer using some other superclass. The easiest way is to create a subclass of an existing component, making your subclass implement the TableCellRenderer
interface. TableCellRenderer
requires just one method: getTableCellRendererComponent
. Your implementation of this method should set the rendering component to reverberate the passed-in country, and then return the component.
In the snapshot of TableDialogEditDemo
, the renderer used for Favorite Colour cells is a bracket of JLabel
called ColorRenderer
. Here are excerpts from ColorRenderer.java
that show how it is implemented.
public class ColorRenderer extends JLabel implements TableCellRenderer { ... public ColorRenderer(boolean isBordered) { this.isBordered = isBordered; setOpaque(true); //MUST do this for background to show up. } public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { Color newColor = (Color)color; setBackground(newColor); if (isBordered) { if (isSelected) { ... //selectedBorder is a solid edge in the color //table.getSelectionBackground(). setBorder(selectedBorder); } else { ... //unselectedBorder is a solid edge in the color //table.getBackground(). setBorder(unselectedBorder); } } setToolTipText(...); //Discussed in the following section return this; } }
Here is the code from TableDialogEditDemo.coffee
that registers a ColorRenderer
instance as the default renderer for all Color
data:
table.setDefaultRenderer(Color.grade, new ColorRenderer(true));
To specify a cell-specific renderer, you lot need to define a JTable
bracket that overrides the getCellRenderer
method. For case, the post-obit lawmaking makes the first cell in the first cavalcade of the table utilize a custom renderer:
TableCellRenderer weirdRenderer = new WeirdRenderer(); tabular array = new JTable(...) { public TableCellRenderer getCellRenderer(int row, int column) { if ((row == 0) && (column == 0)) { return weirdRenderer; } // else... return super.getCellRenderer(row, column); } };
Specifying Tool Tips for Cells
By default, the tool tip text displayed for a table cell is determined by the prison cell'southward renderer. Yet, sometimes it can be simpler to specify tool tip text by overriding JTable
's implementation of the getToolTipText(MouseEvent)
method. This section shows yous how to utilise both techniques.
To add a tool tip to a cell using its renderer, you first need to get or create the cell renderer. Then, later on making sure the rendering component is a JComponent
, invoke the setToolTipText
method on it.
An example of setting tool tips for cells is in TableRenderDemo
. Click the Launch button to run it using Coffee™ Web Start (download JDK seven or later). Or, to compile and run the case yourself, consult the example index.
The source lawmaking is in TableRenderDemo.java
. Information technology adds tool tips to the cells of the Sport column with the following lawmaking:
//Prepare upward tool tips for the sport cells. DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setToolTipText("Click for combo box"); sportColumn.setCellRenderer(renderer);
Although the tool tip text in the previous example is static, you tin can besides implement tool tips whose text changes depending on the land of the jail cell or plan. Here are a couple ways to do so:
- Add a bit of code to the renderer's implementation of the
getTableCellRendererComponent
method. - Override the
JTable
methodgetToolTipText(MouseEvent)
.
An case of adding code to a prison cell renderer is in TableDialogEditDemo
. Click the Launch button to run information technology using Coffee™ Web First (download JDK 7 or later). Or, to compile and run the case yourself, consult the example index.
TableDialogEditDemo
uses a renderer for colors, implemented in ColorRenderer.coffee
, that sets the tool tip text using the boldface code in the following snippet:
public class ColorRenderer extends JLabel implements TableCellRenderer { ... public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { Color newColor = (Color)color; ... setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue()); return this; } }
Here is an case of what the tool tip looks similar:
You can specify tool tip text by overriding JTable
's getToolTipText(MouseEvent)
method. The program TableToolTipsDemo
shows how. Click the Launch push button to run information technology using Coffee™ Spider web Start (download JDK 7 or afterwards). Or, to compile and run the example yourself, consult the example index.
The cells with tool tips are in the Sport and Vegetarian columns. Hither is a picture of its tool tip:
Here is the lawmaking from TableToolTipsDemo.java
that implements tool tips for cells in the Sport and Vegetarian columns:
JTable tabular array = new JTable(new MyTableModel()) { //Implement tabular array prison cell tool tips. public String getToolTipText(MouseEvent e) { Cord 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 = (Cord)model.getValueAt(rowIndex,0); Cord lastName = (String)model.getValueAt(rowIndex,ane); Boolean veggie = (Boolean)model.getValueAt(rowIndex,4); if (Boolean.True.equals(veggie)) { tip = firstName + " " + lastName + " is a vegetarian"; } else { tip = firstName + " " + lastName + " is non a vegetarian"; } } else { //some other column //You tin can omit this part if you know yous don't //accept any renderers that supply their own tool //tips. tip = super.getToolTipText(e); } return tip; } ... }
The lawmaking is fairly straightforward, except perhaps for the call to convertColumnIndexToModel
. That phone call is necessary considering if the user moves the columns around, the view's alphabetize for the cavalcade will not match the model's alphabetize for the column. For example, the user might drag the Vegetarian column (which the model considers to be at index 4) and so it is displayed as the first column — at view index 0. Since prepareRenderer
provides the view alphabetize, you demand to translate the view index to a model alphabetize so y'all tin can be sure the intended column has been selected.
Specifying Tool Tips for Column Headers
You tin add a tool tip to a column header by setting the tool tip text for the table's JTableHeader
. Oftentimes, unlike column headers require unlike tool tip text. You can modify the text by overriding the tabular array header's getToolTipText
method. Alternately, yous can invoke TableColumn.setHeaderRenderer
to provide a custom renderer for the header.
An instance of using the same tool tip text for all column headers is in TableSorterDemo.java
. Here is how information technology sets the tool tip text:
table.getTableHeader().setToolTipText( "Click to sort; Shift-Click to sort in opposite social club");
TableToolTipsDemo.coffee
has an case of implementing cavalcade header tool tips that vary past column. If you run TableToolTipsDemo
(click the Launch push button) using Java™ Web Start (download JDK vii or afterwards). Or, to compile and run the instance yourself, consult the example alphabetize.
You will see the tool tips when y'all mouse over any column header except for the first 2. No tool tips were supplied for the name columns since they seemed self-explanatory. Hither is a motion picture of one of the cavalcade header tool tips:
The following code implements the tool tips. Basically, it creates a subclass of JTableHeader
that overrides the getToolTipText(MouseEvent)
method so that it returns the text for the current column. To acquaintance the revised tabular array header with the table, the JTable
method createDefaultTableHeader
is overridden so that it returns an example of the JTableHeader
subclass.
protected String[] columnToolTips = { zilch, // "First Name" assumed obvious nix, // "Last Name" assumed obvious "The person'due south favorite sport to participate in", "The number of years the person has played the sport", "If checked, the person eats no meat"}; ... JTable tabular array = new JTable(new MyTableModel()) { ... //Implement tabular array header tool tips. protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { public String getToolTipText(MouseEvent e) { String tip = naught; java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); return columnToolTips[realIndex]; } }; } };
Sorting and Filtering
Table sorting and filtering is managed past a sorter object. The easiest way to provide a sorter object is to set up autoCreateRowSorter
bound holding to true
:
JTable table = new JTable(); table.setAutoCreateRowSorter(true);
This activeness defines a row sorter that is an instance of javax.swing.table.TableRowSorter
. This provides a table that does a elementary locale-specific sort when the user clicks on a cavalcade header. This is demonstrated in
, as seen in this screen shot:TableSortDemo.java
To have more than control over sorting, you can construct an instance of TableRowSorter
and specify that information technology is the sorter object for your table.
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tabular array.getModel()); table.setRowSorter(sorter);
TableRowSorter
uses java.util.Comparator
objects to sort its rows. A class that implements this interface must provide a method called compare
that defines how any two objects are compared for the purpose of sorting. For example, the following code creates a Comparator
that sorts a set up of strings by the last discussion in each cord:
Comparator<Cord> comparator = new Comparator<String>() { public int compare(Cord s1, String s2) { Cord[] strings1 = s1.split("\\s"); Cord[] strings2 = s2.split("\\s"); return strings1[strings1.length - 1] .compareTo(strings2[strings2.length - 1]); } };
This example is adequately simplistic; more than typically, a Comparator
implementation is a bracket of coffee.text.Collator
. You lot tin define your ain subclass, use the factory methods in Collator
to obtain a Comparator
for a specific locale, or use java.text.RuleBasedCollator
.
To determine which Comparator
to use for a cavalcade, TableRowSorter
attempts to apply each of the post-obit rules in plough. Rules are followed in the order listed below; the beginning rule that provides the sorter with a Comparator
is used, and the remaining rules ignored.
- If a comparator has been specified past invoking
setComparator
, use that comparator. - If the table model reports that the column data consists of strings (
TableModel.getColumnClass
returnsCord.class
for that cavalcade), use a comparator that sorts the strings based on the current locale. - If the column class returned by
TableModel.getColumnClass
implementsComparable
, use a comparator that sorts the strings based on the values returned byComparable.compareTo
. - If a cord convertor has been specified for the table by invoking
setStringConverter
, use a comparator that sorts the resulting cord representations based on the current locale. - If none of the previous rules apply, apply a comparator that invokes
toString
on the cavalcade data and sorts the resulting strings based on the current locale.
For more than sophisticated kinds of sorting, bracket TableRowSorter
or its parent class javax.swing.DefaultRowSorter
.
To specify the sort lodge and sort precedence for columns, invoke setSortKeys
. Here is an example that sorts the table used in the examples by the first two columns. The precedence of the columns in the sort is indicated by the order of the sort keys in the sort key list. In this case, the second column has the first sort primal, so they rows are sorted by offset name, so last name.
List <RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>(); sortKeys.add(new RowSorter.SortKey(1, SortOrder.ASCENDING)); sortKeys.add together(new RowSorter.SortKey(0, SortOrder.ASCENDING)); sorter.setSortKeys(sortKeys);
In addition to reordering the results, a tabular array sorter can also specify which rows will be displayed. This is known every bit filtering. TableRowSorter
implements filtering using javax.swing.RowFilter
objects. RowFilter
implements several mill methods that create common kinds of filters. For case, regexFilter
returns a RowFilter
that filters based on a regular expression.
In the following instance code, you explicitly create a sorter object so you can afterward use information technology to specify a filter:
MyTableModel model = new MyTableModel(); sorter = new TableRowSorter<MyTableModel>(model); table = new JTable(model); table.setRowSorter(sorter);
Then you filter based on the current value of a text field:
private void newFilter() { RowFilter<MyTableModel, Object> rf = null; //If current expression doesn't parse, don't update. endeavour { rf = RowFilter.regexFilter(filterText.getText(), 0); } catch (java.util.regex.PatternSyntaxException e) { return; } sorter.setRowFilter(rf); }
In a subsequent example, newFilter()
is invoked every fourth dimension the text field changes. When the user enters complicated regular expressions, the endeavour...catch
prevents the syntax exception from interfering with input.
When a tabular array uses a sorter, the data the users sees may exist in a dissimilar order than that specified by the data model, and may not include all rows specified by the data model. The information the user actually sees is known as the view, and has its ain set of coordinates. JTable
provides methods that convert from model coordinates to view coordinates — convertColumnIndexToView
and convertRowIndexToView
— and that convert from view coordinates to model coordinates — convertColumnIndexToModel
and convertRowIndexToModel
.
Notation: When using a sorter, always remember to interpret cell coordinates.
The following case brings together the ideas discussed in this section.
adds a pocket-size number of changes to TableFilterDemo.java
TableDemo
. These include the lawmaking snippets earlier in this department, which provide a sorter for the principal tabular array, and utilize a text field to supply the filtering regular expression. The following screen shot shows TableFilterDemo
before any sorting or filtering has been washed. Notice that row 3 in the model is notwithstanding the same as row three in the view:
If the user clicks twice on the second column, the fourth row becomes the first row — but only in the view:
As previously noted, the text the user enters in the "Filter Text" text field defines a filter that determines which rows are shown. As with sorting, filtering tin cause view coordinates to diverge from model coordinates:
Here is the code that updates the status field to reflect the electric current selection:
table.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent effect) { int viewRow = table.getSelectedRow(); if (viewRow < 0) { //Selection got filtered abroad. statusText.setText(""); } else { int modelRow = table.convertRowIndexToModel(viewRow); statusText.setText( String.format("Selected Row in view: %d. " + "Selected Row in model: %d.", viewRow, modelRow)); } } } );
Using a Combo Box equally an Editor
Setting up a combo box as an editor is unproblematic, as the following example shows. The assuming line of code sets up the combo box as the editor for a specific column.
TableColumn sportColumn = table.getColumnModel().getColumn(2); ... JComboBox comboBox = new JComboBox(); comboBox.addItem("Snowboarding"); comboBox.addItem("Rowing"); comboBox.addItem("Chasing toddlers"); comboBox.addItem("Speed reading"); comboBox.addItem("Teaching high school"); comboBox.addItem("None"); sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
Here is a picture of the combo box editor in use:
The preceding code is from TableRenderDemo.java
. You can run TableRenderDemo
(click the Launch button) using Java™ Web Kickoff (download JDK vii or afterwards). Or, to compile and run the example yourself, consult the example index.
Using Other Editors
Whether you are setting the editor for a single column of cells (using the TableColumn
setCellEditor
method) or for a specific type of information (using the JTable
setDefaultEditor
method), you specify the editor using an statement that adheres to the TableCellEditor
interface. Fortunately, the DefaultCellEditor
form implements this interface and provides constructors to let you specify an editing component that is a JTextField
, JCheckBox
, or JComboBox
. Usually y'all exercise not have to explicitly specify a check box as an editor, since columns with Boolean
data automatically utilize a check box renderer and editor.
What if you desire to specify an editor other than a text field, check box, or philharmonic box? As DefaultCellEditor
does not support other types of components, you must practice a little more work. You need to create a form that implements the TableCellEditor
interface. The AbstractCellEditor
grade is a good superclass to employ. It implements TableCellEditor
'southward superinterface, CellEditor
, saving you the trouble of implementing the event firing lawmaking necessary for jail cell editors.
Your jail cell editor course needs to define at least two methods — getCellEditorValue
and getTableCellEditorComponent
. The getCellEditorValue
method, required past CellEditor
, returns the jail cell's electric current value. The getTableCellEditorComponent
method, required by TableCellEditor
, should configure and return the component that you desire to use as the editor.
Here is a picture of a table with a dialog that serves, indirectly, every bit a cell editor. When the user begins editing a jail cell in the Favorite Colour column, a push button (the truthful cell editor) appears and brings up the dialog, with which the user can cull a different color.
You can run TableDialogEditDemo
(click the Launch button) using Java™ Spider web Start (download JDK 7 or afterward). Or, to compile and run the example yourself, consult the example index.
Here is the code, taken from ColorEditor.java
, that implements the cell editor.
public grade ColorEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { Colour currentColor; JButton push button; JColorChooser colorChooser; JDialog dialog; protected static terminal String EDIT = "edit"; public ColorEditor() { push = new JButton(); push button.setActionCommand(EDIT); button.addActionListener(this); button.setBorderPainted(simulated); //Ready the dialog that the button brings up. colorChooser = new JColorChooser(); dialog = JColorChooser.createDialog(button, "Pick a Color", true, //modal colorChooser, this, //OK button handler null); //no Cancel push handler } public void actionPerformed(ActionEvent e) { if (EDIT.equals(east.getActionCommand())) { //The user has clicked the cell, and so //bring up the dialog. push.setBackground(currentColor); colorChooser.setColor(currentColor); dialog.setVisible(true); fireEditingStopped(); //Brand the renderer reappear. } else { //User pressed dialog's "OK" button. currentColor = colorChooser.getColor(); } } //Implement the i CellEditor method that AbstractCellEditor doesn't. public Object getCellEditorValue() { return currentColor; } //Implement the one method defined by TableCellEditor. public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int cavalcade) { currentColor = (Color)value; return push; } }
As you lot can encounter, the code is pretty simple. The only part that is a flake tricky is the telephone call to fireEditingStopped
at the stop of the editor button's action handler. Without this call, the editor would remain active, even though the modal dialog is no longer visible. The call to fireEditingStopped
lets the table know that it tin can conciliate the editor, letting the jail cell be handled by the renderer once more.
Using an Editor to Validate User-Entered Text
If a jail cell'south default editor allows text entry, you get some error checking for free if the cell's type is specified as something other than String
or Object
. The mistake checking is a side effect of converting the entered text into an object of the proper type.
The automatic checking of user-entered strings occurs when the default editor attempts to create a new example of the class associated with the prison cell's cavalcade. The default editor creates this instance using a constructor that takes a String
as an argument. For instance, in a column whose cells have type Integer
, when the user types in "123" the default editor creates the corresponding Integer
using code equivalent to new Integer("123")
. If the constructor throws an exception, the prison cell's outline turns red and refuses to let focus move out of the cell. If you lot implement a class used as a column data type, you tin can use the default editor if your class supplies a constructor that takes a single argument of type String
.
If y'all like having a text field as the editor for a cell, but desire to customize it — possibly to bank check user-entered text more strictly or to react differently when the text is invalid — you can change the jail cell editor to use a formatted text field. The formatted text field tin can check the value either continuously while the user is typing or later the user has indicated the terminate of typing (such every bit by pressing Enter).
The following code, taken from a demo named TableFTFEditDemo.coffee
, sets upward a formatted text field every bit an editor that limits all integer values to exist between 0 and 100. You tin can run TableFTFEditDemo
(click the Launch button) using Coffee™ Web Start (download JDK 7 or later). Or, to compile and run the example yourself, consult the case index.
The following code makes the formatted text field the editor for all columns that contain data of type Integer
.
tabular array.setDefaultEditor(Integer.class, new IntegerEditor(0, 100));
The IntegerEditor
grade is implemented equally a subclass of DefaultCellEditor
that uses a JFormattedTextField
instead of the JTextField
that DefaultCellEditor
supports. It accomplishes this past first setting up a formatted text field to apply an integer format and take the specified minimum and maximum values, using the API described in How to Use Formatted Text Fields. It then overrides the DefaultCellEditor
implementation of the getTableCellEditorComponent
, getCellEditorValue
, and stopCellEditing
methods, calculation the operations that are necessary for formatted text fields.
The override of getTableCellEditorComponent
sets the formatted text field's value holding (and not just the text belongings it inherits from JTextField
) before the editor is shown. The override of getCellEditorValue
keeps the cell value as an Integer
, rather than, say, the Long
value that the formatted text field's parser tends to return. Finally, overriding stopCellEditing
lets you check whether the text is valid, possibly stopping the editor from beingness dismissed. If the text isn't valid, your implementation of stopCellEditing
puts upwardly a dialog that gives the user the option of continuing to edit or reverting to the terminal skillful value. The source code is a scrap too long to include here, simply y'all tin find it in IntegerEditor.java
.
Printing
JTable
provides a unproblematic API for printing tables. The easiest way to impress out a table is to invoke JTable.print
with no arguments:
endeavour { if (! table.print()) { Organization.err.println("User cancelled press"); } } catch (java.awt.print.PrinterException east) { Organisation.err.format("Cannot impress %southward%north", eastward.getMessage()); }
Invoking print
on a normal Swing application brings up a standard printing dialog box. (On a headless application, the table is only printed.) The return value indicates whether the user went alee with the impress job or cancelled it. JTable.print
tin throw coffee.awt.print.PrinterException
, which is a checked exception; that'south why the above case uses a endeavor ... catch
.
JTable
provides several overloads of print
with diverse options. The post-obit code from
shows how to define a page header:TablePrintDemo.java
MessageFormat header = new MessageFormat("Page {0,number,integer}"); endeavor { table.print(JTable.PrintMode.FIT_WIDTH, header, null); } catch (java.awt.impress.PrinterException e) { System.err.format("Cannot impress %s%n", e.getMessage()); }
For more sophisticated printing applications, apply JTable.getPrintable
to obtain a Printable
object for the table. For more on Printable
, refer to the Printing lesson in the second Graphics trail.
Examples that Use Tables
This table lists examples that use JTable
and where those examples are described.
Case | Where Described | Notes |
---|---|---|
SimpleTableDemo | Creating a Elementary Tabular array | A basic table with no custom model. Does not include code to specify column widths or detect user editing. |
SimpleTable- | Detecting User Selections | Adds single selection and selection detection to SimpleTableDemo . By modifying the plan'south ALLOW_COLUMN_SELECTION and ALLOW_ROW_SELECTION constants, you tin experiment with alternatives to the table default of assuasive just rows to be selected. |
TableDemo | Creating a Tabular array Model | A basic table with a custom model. |
TableFTFEditDemo | Using an Editor to Validate User-Entered Text | Modifies TableDemo to use a custom editor (a formatted text field variant) for all Integer information. |
TableRenderDemo | Using a Philharmonic Box as an Editor | Modifies TableDemo to employ a custom editor (a philharmonic box) for all data in the Sport column. Also intelligently picks column sizes. Uses renderers to display tool tips for the sport cells. |
TableDialogEditDemo | Using Other Editors | Modifies TableDemo to have a cell renderer and editor that display a color and permit you choose a new one, using a color chooser dialog. |
TableToolTipsDemo | Specifying Tool Tips for Cells, Specifying Tool Tips for Cavalcade Headers, | Demonstrates how to use several techniques to ready tool tip text for cells and column headers. |
TableSortDemo | Sorting and Filtering | Demonstrates the default sorter, which allows the user to sort columns past clicking on their headers. |
TableFilterDemo | Sorting and Filtering | Demonstrates sorting and filtering, and how this can cause the view coordinates to diverge from the model coordinates. |
TablePrintDemo | Printing | Demonstrates table printing. |
ListSelectionDemo | How to Write a List Option Listener | Shows how to apply all list selection modes, using a list option listener that'south shared between a table and listing. |
SharedModelDemo | Nowhere | Builds on ListSelectionDemo making the data model exist shared between the table and listing. If you edit an item in the offset cavalcade of the table, the new value is reflected in the list. |
How to Read in Data Two Rows Down in Java Txt File
Source: https://docs.oracle.com/javase/tutorial/uiswing/components/table.html