Read Second Column of Integer and Save to the Array Java
With the JTable class you can display tables of data, optionally allowing the user to edit the data. JTable does non comprise or enshroud data; it is just a view of your data. Here is a film of a typical table displayed within a scroll pane:
The rest of this department shows you how to attain some mutual table-related tasks. Here are the topics this section covers:
- Creating a Uncomplicated Tabular array
- Calculation a Table to a Container
- Setting and Changing Cavalcade Widths
- User Selections
- Creating a Tabular array 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 Use Tables
Creating a Simple Table
Try this:
-
Click the Launch push to run
SimpleTableDemousing Coffee™ Spider web Commencement (download JDK seven or later on). Or, to compile and run the example yourself, consult the instance index.
-
Click the cell that contains "Snowboarding".
The entire get-go row is selected, indicating that you have selected Kathy Smith'south data. A special highlight indicates that the "Snowboarding" cell is editable. Generally, y'all begin editing a text prison cell by double-clicking it. -
Position the cursor over "Showtime Name". Now press the mouse push and elevate to the right.
As yous can see, users can rearrange columns in tables. -
Position the cursor just to the right of a column header. Now press the mouse button and drag to the right or left.
The column changes size, and the other columns arrange to fill the remaining space. - Resize the window containing the tabular array and so that it'due 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.coffee declares the column names in a String array:
String[] columnNames = {"Get-go Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; Its data is initialized and stored in a 2-dimensional Object array:
Object[][] data = { {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(imitation)}, {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)}, {"Sue", "Black", "Knitting", new Integer(ii), new Boolean(faux)}, {"Jane", "White", "Speed reading", new Integer(twenty), new Boolean(truthful)}, {"Joe", "Dark-brown", "Puddle", new Integer(10), new Boolean(simulated)} }; Then the Table is constructed using these data and columnNames:
JTable table = new JTable(data, columnNames);
There are two JTable constructors that straight accept information (SimpleTableDemo uses the first):
-
JTable(Object[][] rowData, Object[] columnNames) -
JTable(Vector rowData, Vector columnNames)
The advantage of these constructors is that they are easy to use. Notwithstanding, these constructors also accept disadvantages:
- They automatically make every jail cell editable.
- They treat all information types the aforementioned (every bit strings). For example, if a tabular array column has
Booleandata, the table tin can display the data in a check box. However, if you utilise either of the twoJTableconstructors listed previously, yourBooleandata is displayed as a cord. You can see this departure in theVegetariancavalcade of the previous effigy. - They require that yous put all of the table's data in an array or vector, which may not exist appropriate for some data. For instance, if you are instantiating a set of objects from a database, yous might want to query the objects directly for their values, rather than copying all their values into an array or vector.
If you want to become around these restrictions, you lot need to implement your own table model, as described in Creating a Table Model.
Adding a Table to a Container
Hither is typical code for creating a curl pane that serves equally a container for a table:
JScrollPane scrollPane = new JScrollPane(table); tabular array.setFillsViewportHeight(true);
The ii lines in this snippet do the post-obit:
- The
JScrollPaneconstructor is invoked with an argument that refers to the table object. This creates a scroll pane as a container for the tabular array; the tabular array is automatically added to the container. -
JTable.setFillsViewportHeightis invoked to fix thefillsViewportHeightproperty. When this property istruthfulthe table uses the entire height of the container, even if the table doesn't accept enough rows to utilize the whole vertical space. This makes it easier to apply the table as a drag-and-drib target.
The scroll pane automatically places the table header at the height of the viewport. The cavalcade names remain visible at the meridian of the viewing area when the table data is scrolled.
If you are using a table without a scroll pane, then you must get the table header component and place it yourself. For case:
container.setLayout(new BorderLayout()); container.add(table.getTableHeader(), BorderLayout.PAGE_START); container.add(table, BorderLayout.CENTER);
Setting and Irresolute Column Widths
By default, all columns in a table outset out with equal width, and the columns automatically fill the entire width of the table. When the tabular array becomes wider or narrower (which might happen when the user resizes the window containing the table), all the column widths alter appropriately.
When the user resizes a column by dragging its right border, then either other columns must change size, or the table'south size must alter. By default, the table'due south size remains the same, and all columns to the correct of the drag point resize to accommodate space added to or removed from the cavalcade to the left of the elevate point.
To customize initial column widths, y'all tin can invoke setPreferredWidth on each of your tabular array'south columns. This sets both the preferred widths of the columns and their guess relative widths. For example, adding the following code to SimpleTableDemo makes its third cavalcade bigger than the other columns:
TableColumn column = zero; for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 2) { column.setPreferredWidth(100); //tertiary column is bigger } else { column.setPreferredWidth(50); } } Every bit the preceding code shows, each column in a table is represented by a TableColumn object. TableColumn supplies getter and setter methods for the minimum, preferred, and maximum widths of a column, too as a method for getting the current width. For an example of setting cell widths based on an approximation of the infinite needed to describe the cells' contents, see the initColumnSizes method in TableRenderDemo.java.
When the user explicitly resizes columns, the columns' preferred widths are set such that the user-specified sizes become the columns' new electric current widths. Nevertheless, when table itself is resized — typically because the window has resized —; the columns' preferred widths do not modify. Instead, the existing preferred widths are used to summate new column widths to make full the available space.
Y'all can change a table's resize beliefs by invoking setAutoResizeMode.
User Selections
In its default configuration, a table supports a selection that consists of 1 or more rows. The user tin select a contiguous range of rows or an arbitrary set of rows. The last cell that the user indicated gets a special indication; in the Metal await and feel, the cell is outlined. This prison cell is known as the lead selection; information technology is sometimes called "the jail cell with the focus" or "the current prison cell".
The user uses the mouse and/or keyboard to make selections, as described in the following table:
| Operation | Mouse Action | Keyboard Action |
|---|---|---|
| Select unmarried row. | Click. | Up Arrow or Downwardly Pointer. |
| Extend contiguous option. | Shift-Click or Drag over rows. | Shift-Up Arrow or Shift-Down Arrow. |
| Add together row to choice/toggle row option. | Control-Click | Move lead option with Control-Up Pointer or Control-Downwards Pointer, then use Space Bar to add to selection or Control-Space Bar to toggle row selection. |
To run into how selections work, click the Launch button to run TableSelectionDemo using Coffee™ Web Outset (download JDK 7 or later). Or, to compile and run the example yourself, consult the case index.
This instance plan presents the familiar tabular array, and allows the user to manipulate certain JTable options. In that location is also a text pane that logs pick events.
In the screenshot below, a user has run the plan, clicked in the first row, then control-clicked in the third row. Notice the outline around the terminal prison cell clicked; this is how the Metal look and feel highlights the atomic number 82 choice.
Nether "Option Fashion" in that location are a set of radio buttons. Click the 1 labelled "Unmarried Selection". At present you can but select one row at a time. If you click on the "Single Interval Option" radio button, you tin can select a set of rows that must be contiguous.
All of the radio buttons nether "Selection Mode" invoke JTable.setSelectionMode. This method takes a single argument, which must be ane of the following constants defined in javax.swing.ListSelectionModel: MULTIPLE_INTERVAL_SELECTION, SINGLE_INTERVAL_SELECTION, and SINGLE_SELECTION.
Returning to TableSelectionDemo, observe the three pick check boxes under "Pick Options." Each of check box controls the land of a boolean leap variable divers by JTable:
- "Row Pick" controls
rowSelectionAllowedwhich has setter methodsetRowSelectionAllowedand getter methodgetRowSelectionAllowed. When this leap belongings istrue(and thecolumnSelectionAllowedholding isimitation), the user can select past row. - "Column Option" controls
columnSelectionAllowedwhich has setter methodsetColumnSelectionAllowedand getter methodgetColumnSelectionAllowed. When this jump property istrue(and therowSelectionAllowedbound belongings isfalse), the user can select by column. - "Jail cell Selection" controls
cellSelectionEnabled, which has setter methodsetCellSelectionEnabledand getter methodgetCellSelectionEnabled. When this bound property istrue, the user can select a single prison cell or rectangular cake of cells.
Note:JTable uses a very simple concept of pick, managed as an intersection of rows and columns. It was not designed to handle fully independent cell selections.
If you articulate all three check boxes (setting all iii bound properties to false), there is no selection; only the lead pick is shown.
You lot may detect that the "Cell Selection" bank check box is disabled in multiple interval selection mode. This is because cell selection is not supported in this way in the demo. You can specify choice by cell in multiple interval option way, but the consequence is a table that does not produce useful selections.
Yous may also find that changing any of the 3 choice options can affect the others. This is because assuasive both row option and column selection is exactly the same as enabling prison cell selection. JTable automatically updates the three bound variables as necessary to proceed them consistent.
NOTE: 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 issue of as well setting cellSelectionEnabled to simulated.
To retrieve the current selection, use JTable.getSelectedRows which returns an array of row indexes, and JTable.getSelectedColumns which returns an array of column indexes. To recall the coordinates of the atomic number 82 choice, refer to the selection models for the table itself and for the table's column model. The following lawmaking formats a string containing the row and column of the lead option:
String.format("Lead Pick: %d, %d. ", tabular array.getSelectionModel().getLeadSelectionIndex(), table.getColumnModel().getSelectionModel().getLeadSelectionIndex()); User selections generate a number of events. For data on these, refer to How to Write a Listing Selection Listener in the Writing Event Listeners lesson.
NOTE: Choice data actually describes selected cells in the "view" (tabular array data as it appears after whatever sorting or filtering) rather than in the table model. This distinction does not matter unless your viewed data has been rearranged past sorting, filtering, or user manipulation of columns. In that case, you 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 bodily table information. A table model object must implement the TableModel interface. If the programmer does not 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 lawmaking like this:
new AbstractTableModel() { public String getColumnName(int col) { return columnNames[col].toString(); } public int getRowCount() { return rowData.length; } public int getColumnCount() { return columnNames.length; } public Object getValueAt(int row, int col) { render rowData[row][col]; } public boolean isCellEditable(int row, int col) { render true; } 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 exist simple. Mostly, you implement your table model in a subclass of the AbstractTableModel course.
Your model might hold its information in an array, vector, or hash map, or it might go the data from an outside source such as a database. It might even generate the data at execution time.
This table is different from the SimpleTableDemo tabular array in the following ways:
-
TableDemo'south custom tabular array model, fifty-fifty though information technology is simple, can easily determine the data's blazon, helping theJTablebrandish the data in the best format.SimpleTableDemo's automatically created table model, on the other mitt, does not know that the # of Years column contains numbers (which should generally be correct aligned and have a particular format). It also does not know that theVegetariancolumn contains boolean values, which can exist represented by check boxes. - The custom tabular array model implemented in
TableDemodoes non let you edit the name columns; it does, still, permit you lot edit the other columns. InSimpleTableDemo, all cells are editable.
See below the code taken from TableDemo.coffee that is different from the SimpleTableDemo.coffee. Bold font indicates the lawmaking that makes this table's model different from the table model defined automatically for SimpleTableDemo.
public TableDemo() { ... JTable tabular array = new JTable(new MyTableModel()); ... } grade MyTableModel extends AbstractTableModel { private String[] columnNames = ...//same equally earlier... private Object[][] information = ...//aforementioned as earlier... public int getColumnCount() { render columnNames.length; } public int getRowCount() { return data.length; } public Cord getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return information[row][col]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } /* * Don't demand 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 < ii) { return imitation; } else { render true; } } /* * Don't need to implement this method unless your table'southward * data can modify. */ public void setValueAt(Object value, int row, int col) { data[row][col] = value; fireTableCellUpdated(row, col); } ... } Listening for Data Changes
A tabular array model tin can have a set of listeners that are notified whenever the table data changes. Listeners are instances of TableModelListener. In the following case lawmaking, SimpleTableDemo is extended to include such a listener. New code is in assuming.
import javax.swing.event.*; import javax.swing.table.TableModel; public class SimpleTableDemo ... implements TableModelListener { ... public SimpleTableDemo() { ... table.getModel().addTableModelListener(this); ... } public void tableChanged(TableModelEvent e) { int row = eastward.getFirstRow(); int column = e.getColumn(); TableModel model = (TableModel)e.getSource(); String columnName = model.getColumnName(column); Object data = model.getValueAt(row, column); ...// Do something with the data... } ... } Firing Information Change Events
In order to burn data change events the tabular array model must know how to construct a TableModelEvent object. This can exist a complex process, but is already implemented in DefaultTableModel. You can either allow JTable to use its default instance of DefaultTableModel, or create your own custom subclass of DefaultTableModel.
If DefaultTableModel is not a suitable base of operations course for your custom table model course, consider subclassing AbstractTableModel. This class implements a simple framework for constructing TableModelEvent objects. Your custom class simply needs to invoke one the following AbstractTableModel methods each time table data is changed by an external source.
| Method | Alter |
|---|---|
fireTableCellUpdated | Update of specified cell. |
fireTableRowsUpdated | Update of specified rows |
fireTableDataChanged | Update of entire table (data only). |
fireTableRowsInserted | New rows inserted. |
fireTableRowsDeleted | Existing rows Deleted |
fireTableStructureChanged | Invalidate entire table, both data and construction. |
Concepts: Editors and Renderers
Before y'all go on to the next few tasks, you need to understand how tables describe their cells. You lot might await each cell in a table to be a component. However, for performance reasons, Swing tables are implemented differently.
Instead, a single cell renderer is more often than not used to describe all of the cells that contain the same type of data. Yous can recall of the renderer as a configurable ink stamp that the tabular array uses to stamp appropriately formatted data onto each cell. When the user starts to edit a cell'southward information, a cell editor takes over the prison cell, controlling the jail cell'south editing behavior.
For example, each jail 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 advisable numbers, correct-aligned, on the cavalcade's cells. If the user begins editing 1 of the cells, the default jail cell editor uses a right-aligned JTextField to command the cell editing.
To choose the renderer that displays the cells in a column, a table first determines whether you specified a renderer for that particular column. If you lot did not, so the table invokes the table model's getColumnClass method, which gets the data type of the column'due south cells. Adjacent, the table compares the cavalcade'south information type with a list of information types for which cell renderers are registered. This list is initialized by the table, just you tin can add together to it or change it. Currently, tables put the following types of data in the listing:
-
Boolean— rendered with a check box. -
Number— rendered by a right-aligned label. -
Double,Float— same asNumber, but the object-to-text translation is performed past aNumberFormatinstance (using the default number format for the current locale). -
Date— rendered by a label, with the object-to-text translation performed by aDateFormatinstance (using a brusk mode for the date and time). -
ImageIcon,Icon— rendered by a centered characterization. -
Object— rendered by a label that displays the object'southward string value.
Jail cell editors are chosen using a similar algorithm.
Call back that if you let a table create its own model, it uses Object as the blazon of every cavalcade. To specify more precise column types, the table model must define the getColumnClass method appropriately, as demonstrated past TableDemo.coffee.
Keep in heed that although renderers determine how each cell or column header looks and tin can specify its tool tip text, a renderer does not handle events. If you need to pick up the events that take place within a tabular array, the technique you lot use varies by the sort of issue you lot are interested in:
| Situation | How to Get Events |
|---|---|
| To observe events from a jail cell that is beingness edited... | Use the cell editor (or register a listener on the prison cell editor). |
| To find row/column/cell selections and deselections... | Use a option listener as described in Detecting User Selections. |
| To detect mouse events on a column header... | Register the appropriate type of mouse listener on the table's JTableHeader object. (Come across TableSorter.java for an example.) |
| To detect other events... | Register the appropriate listener on the JTable object. |
The next few sections tell you how to customize display and editing by specifying renderers and editors. You tin specify cell renderers and editors either by cavalcade or past information blazon.
Using Custom Renderers
This section tells you how to create and specify a cell renderer. You can set a type-specific cell renderer using the JTable method setDefaultRenderer. To specify that cells in a particular column should use a renderer, y'all utilise the TableColumn method setCellRenderer. You tin can even specify a cell-specific renderer by creating a JTable bracket.
It is piece of cake to customize the text or image rendered by the default renderer, DefaultTableCellRenderer. You just create a bracket and implement the setValue method and then that it invokes setText or setIcon with the appropriate string or paradigm. For example, here is how the default date 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 == null) ? "" : formatter.format(value)); } } If extending DefaultTableCellRenderer is insufficient, y'all can build a renderer using another superclass. The easiest mode is to create a subclass of an existing component, making your subclass implement the TableCellRenderer interface. TableCellRenderer requires merely one method: getTableCellRendererComponent. Your implementation of this method should fix the rendering component to reflect the passed-in country, and and so return the component.
In the snapshot of TableDialogEditDemo, the renderer used for Favorite Colour cells is a subclass of JLabel chosen ColorRenderer. Here are excerpts from ColorRenderer.coffee that evidence how it is implemented.
public form ColorRenderer extends JLabel implements TableCellRenderer { ... public ColorRenderer(boolean isBordered) { this.isBordered = isBordered; setOpaque(true); //MUST do this for groundwork to show upwards. } public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { Color newColor = (Colour)color; setBackground(newColor); if (isBordered) { if (isSelected) { ... //selectedBorder is a solid border in the color //table.getSelectionBackground(). setBorder(selectedBorder); } else { ... //unselectedBorder is a solid border in the colour //tabular array.getBackground(). setBorder(unselectedBorder); } } setToolTipText(...); //Discussed in the following section render this; } } Here is the code from TableDialogEditDemo.coffee that registers a ColorRenderer example as the default renderer for all Color information:
table.setDefaultRenderer(Colour.grade, new ColorRenderer(true));
To specify a cell-specific renderer, yous need to define a JTable subclass that overrides the getCellRenderer method. For instance, the following lawmaking makes the first cell in the first column of the tabular array use 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
Past default, the tool tip text displayed for a table jail cell is determined by the jail cell's renderer. However, sometimes it can be simpler to specify tool tip text by overriding JTable's implementation of the getToolTipText(MouseEvent) method. This section shows you how to apply both techniques.
To add a tool tip to a cell using its renderer, you first need to get or create the cell renderer. And then, afterwards making sure the rendering component is a JComponent, invoke the setToolTipText method on it.
An case of setting tool tips for cells is in TableRenderDemo. Click the Launch push button to run it using Java™ Web Start (download JDK 7 or later). Or, to compile and run the example yourself, consult the example index.
The source code is in TableRenderDemo.java. It adds tool tips to the cells of the Sport column with the following code:
//Prepare 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 instance is static, you can too implement tool tips whose text changes depending on the state of the jail cell or program. Here are a couple ways to practice so:
- Add together a bit of code to the renderer's implementation of the
getTableCellRendererComponentmethod. - Override the
JTablemethodgetToolTipText(MouseEvent).
An instance of adding lawmaking to a cell renderer is in TableDialogEditDemo. Click the Launch push button to run information technology using Coffee™ Web First (download JDK 7 or later). Or, to compile and run the instance yourself, consult the case index.
TableDialogEditDemo uses a renderer for colors, implemented in ColorRenderer.java, that sets the tool tip text using the boldface code in the post-obit snippet:
public class ColorRenderer extends JLabel implements TableCellRenderer { ... public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { Colour newColor = (Color)colour; ... setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue()); render this; } } Here is an example of what the tool tip looks like:
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 it using Java™ Spider web Outset (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. Here is a flick of its tool tip:
Here is the code from TableToolTipsDemo.coffee that implements tool tips for cells in the Sport and Vegetarian columns:
JTable table = new JTable(new MyTableModel()) { //Implement table cell tool tips. public String getToolTipText(MouseEvent due east) { Cord tip = naught; java.awt.Point p = east.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); Cord lastName = (String)model.getValueAt(rowIndex,1); Boolean veggie = (Boolean)model.getValueAt(rowIndex,four); if (Boolean.Truthful.equals(veggie)) { tip = firstName + " " + lastName + " is a vegetarian"; } else { tip = firstName + " " + lastName + " is not a vegetarian"; } } else { //another column //You can omit this part if you know you lot don't //accept any renderers that supply their own tool //tips. tip = super.getToolTipText(due east); } render tip; } ... } The code is adequately straightforward, except peradventure for the call to convertColumnIndexToModel. That phone call is necessary because if the user moves the columns effectually, the view'southward index for the column volition not friction match the model's alphabetize for the cavalcade. For instance, the user might drag the Vegetarian column (which the model considers to exist at index 4) so it is displayed as the commencement cavalcade — at view alphabetize 0. Since prepareRenderer provides the view index, you demand to translate the view alphabetize to a model index so you lot tin be sure the intended column has been selected.
Specifying Tool Tips for Column Headers
Y'all can add together a tool tip to a column header by setting the tool tip text for the table's JTableHeader. Often, different column headers crave different tool tip text. You lot can change the text by overriding the table header'due south getToolTipText method. Alternately, y'all tin invoke TableColumn.setHeaderRenderer to provide a custom renderer for the header.
An instance of using the aforementioned tool tip text for all column headers is in TableSorterDemo.java. Here is how it sets the tool tip text:
table.getTableHeader().setToolTipText( "Click to sort; Shift-Click to sort in reverse lodge");
TableToolTipsDemo.java has an example of implementing column header tool tips that vary past cavalcade. If you run TableToolTipsDemo (click the Launch button) using Java™ Web First (download JDK vii or later). Or, to compile and run the instance yourself, consult the example index.
You will run into the tool tips when you mouse over any cavalcade header except for the first two. No tool tips were supplied for the name columns since they seemed self-explanatory. Hither is a picture of ane of the column header tool tips:
The following code implements the tool tips. Basically, it creates a bracket of JTableHeader that overrides the getToolTipText(MouseEvent) method so that it returns the text for the electric current column. To associate the revised table header with the table, the JTable method createDefaultTableHeader is overridden and so that it returns an case of the JTableHeader bracket.
protected Cord[] columnToolTips = { nil, // "Outset Name" assumed obvious goose egg, // "Concluding Proper name" assumed obvious "The person'south favorite sport to participate in", "The number of years the person has played the sport", "If checked, the person eats no meat"}; ... JTable table = new JTable(new MyTableModel()) { ... //Implement table header tool tips. protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { public String getToolTipText(MouseEvent eastward) { String tip = null; coffee.awt.Bespeak p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.ten); int realIndex = columnModel.getColumn(index).getModelIndex(); render columnToolTips[realIndex]; } }; } }; Sorting and Filtering
Table sorting and filtering is managed by a sorter object. The easiest way to provide a sorter object is to prepare autoCreateRowSorter bound belongings to true:
JTable tabular array = new JTable(); table.setAutoCreateRowSorter(truthful);
This action defines a row sorter that is an instance of javax.swing.table.TableRowSorter. This provides a tabular array that does a simple locale-specific sort when the user clicks on a column header. This is demonstrated in , as seen in this screen shot:TableSortDemo.coffee
To have more control over sorting, you can construct an instance of TableRowSorter and specify that it is the sorter object for your table.
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.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 fix of strings past the last word in each string:
Comparator<String> comparator = new Comparator<String>() { public int compare(String s1, String s2) { String[] strings1 = s1.split up("\\s"); String[] strings2 = s2.carve up("\\s"); return strings1[strings1.length - 1] .compareTo(strings2[strings2.length - 1]); } }; This instance is fairly simplistic; more typically, a Comparator implementation is a subclass of java.text.Collator. Y'all can define your own bracket, apply 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 utilize each of the following rules in turn. Rules are followed in the order listed below; the first rule that provides the sorter with a Comparator is used, and the remaining rules ignored.
- If a comparator has been specified by invoking
setComparator, utilise that comparator. - If the table model reports that the cavalcade data consists of strings (
TableModel.getColumnClassreturnsString.classfor that column), employ a comparator that sorts the strings based on the current locale. - If the cavalcade class returned by
TableModel.getColumnClassimplementsComparable, use a comparator that sorts the strings based on the values returned byComparable.compareTo. - If a string convertor has been specified for the tabular array by invoking
setStringConverter, apply a comparator that sorts the resulting string representations based on the current locale. - If none of the previous rules apply, employ a comparator that invokes
toStringon the cavalcade data and sorts the resulting strings based on the current locale.
For more sophisticated kinds of sorting, subclass TableRowSorter or its parent class javax.swing.DefaultRowSorter.
To specify the sort social club and sort precedence for columns, invoke setSortKeys. Hither 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 gild of the sort keys in the sort central list. In this case, the second column has the showtime sort key, so they rows are sorted by first name, so last name.
List <RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>(); sortKeys.add(new RowSorter.SortKey(one, SortOrder.ASCENDING)); sortKeys.add together(new RowSorter.SortKey(0, SortOrder.ASCENDING)); sorter.setSortKeys(sortKeys);
In addition to reordering the results, a tabular array sorter tin can also specify which rows will be displayed. This is known as filtering. TableRowSorter implements filtering using javax.swing.RowFilter objects. RowFilter implements several factory methods that create common kinds of filters. For example, regexFilter returns a RowFilter that filters based on a regular expression.
In the following example code, you explicitly create a sorter object so you can subsequently use it to specify a filter:
MyTableModel model = new MyTableModel(); sorter = new TableRowSorter<MyTableModel>(model); tabular array = new JTable(model); table.setRowSorter(sorter);
So 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. effort { rf = RowFilter.regexFilter(filterText.getText(), 0); } catch (java.util.regex.PatternSyntaxException e) { render; } sorter.setRowFilter(rf); } In a subsequent example, newFilter() is invoked every time the text field changes. When the user enters complicated regular expressions, the try...catch prevents the syntax exception from interfering with input.
When a tabular array uses a sorter, the information the users sees may be in a different gild than that specified past the data model, and may non include all rows specified by the data model. The information the user actually sees is known equally the view, and has its own ready 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.
NOTE: When using a sorter, always remember to translate cell coordinates.
The post-obit case brings together the ideas discussed in this department. adds a small number of changes to TableFilterDemo.coffee TableDemo. These include the lawmaking snippets before in this section, which provide a sorter for the main table, and use a text field to supply the filtering regular expression. The following screen shot shows TableFilterDemo before whatsoever sorting or filtering has been washed. Notice that row 3 in the model is yet the same equally row three in the view:
If the user clicks twice on the 2d column, the fourth row becomes the first row — just simply in the view:
Every bit 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 can cause view coordinates to diverge from model coordinates:
Hither is the code that updates the status field to reflect the current selection:
tabular array.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { int viewRow = tabular array.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 as an Editor
Setting upwardly a combo box as an editor is uncomplicated, as the following example shows. The bold line of code sets up the combo box as the editor for a specific column.
TableColumn sportColumn = tabular array.getColumnModel().getColumn(2); ... JComboBox comboBox = new JComboBox(); comboBox.addItem("Snowboarding"); comboBox.addItem("Rowing"); comboBox.addItem("Chasing toddlers"); comboBox.addItem("Speed reading"); comboBox.addItem("Educational activity loftier 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. Y'all tin run TableRenderDemo (click the Launch button) using Java™ Spider web Start (download JDK 7 or subsequently). Or, to compile and run the example yourself, consult the example index.
Using Other Editors
Whether y'all are setting the editor for a single cavalcade of cells (using the TableColumn setCellEditor method) or for a specific blazon of data (using the JTable setDefaultEditor method), you specify the editor using an argument that adheres to the TableCellEditor interface. Fortunately, the DefaultCellEditor class implements this interface and provides constructors to let you specify an editing component that is a JTextField, JCheckBox, or JComboBox. Usually you practise not accept to explicitly specify a check box every bit an editor, since columns with Boolean data automatically use a check box renderer and editor.
What if yous want to specify an editor other than a text field, cheque box, or philharmonic box? As DefaultCellEditor does not back up other types of components, you must practice a petty more work. Yous need to create a class that implements the TableCellEditor interface. The AbstractCellEditor grade is a adept superclass to use. It implements TableCellEditor's superinterface, CellEditor, saving you the trouble of implementing the outcome firing code necessary for prison cell editors.
Your cell editor class needs to ascertain at least 2 methods — getCellEditorValue and getTableCellEditorComponent. The getCellEditorValue method, required by CellEditor, returns the cell's current value. The getTableCellEditorComponent method, required past TableCellEditor, should configure and render the component that you want to use every bit the editor.
Here is a picture of a table with a dialog that serves, indirectly, as a cell editor. When the user begins editing a jail cell in the Favorite Color column, a button (the true cell editor) appears and brings up the dialog, with which the user tin cull a different color.
You can run TableDialogEditDemo (click the Launch push button) using Coffee™ Web Commencement (download JDK 7 or subsequently). Or, to compile and run the example yourself, consult the example index.
Here is the code, taken from ColorEditor.coffee, that implements the cell editor.
public form ColorEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { Color currentColor; JButton push button; JColorChooser colorChooser; JDialog dialog; protected static concluding String EDIT = "edit"; public ColorEditor() { button = new JButton(); button.setActionCommand(EDIT); button.addActionListener(this); push button.setBorderPainted(simulated); //Gear up the dialog that the push brings upward. colorChooser = new JColorChooser(); dialog = JColorChooser.createDialog(push, "Option a Colour", true, //modal colorChooser, this, //OK push handler null); //no CANCEL button handler } public void actionPerformed(ActionEvent east) { if (EDIT.equals(e.getActionCommand())) { //The user has clicked the cell, so //bring up the dialog. button.setBackground(currentColor); colorChooser.setColor(currentColor); dialog.setVisible(true); fireEditingStopped(); //Make the renderer reappear. } else { //User pressed dialog's "OK" button. currentColor = colorChooser.getColor(); } } //Implement the one CellEditor method that AbstractCellEditor doesn't. public Object getCellEditorValue() { return currentColor; } //Implement the one method divers by TableCellEditor. public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { currentColor = (Color)value; return button; } } Every bit you lot can see, the lawmaking is pretty uncomplicated. The only part that is a bit tricky is the call to fireEditingStopped at the finish of the editor button'southward action handler. Without this phone call, the editor would remain active, even though the modal dialog is no longer visible. The telephone call to fireEditingStopped lets the tabular array know that it tin deactivate the editor, letting the cell be handled by the renderer again.
Using an Editor to Validate User-Entered Text
If a cell's default editor allows text entry, you get some error checking for free if the cell's blazon is specified as something other than Cord or Object. The error 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 instance of the form associated with the prison cell's column. The default editor creates this example using a constructor that takes a String as an argument. For example, in a column whose cells take blazon 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 jail cell'southward outline turns red and refuses to let focus move out of the cell. If you implement a class used as a column data type, you lot tin use the default editor if your form supplies a constructor that takes a unmarried argument of type String.
If you similar having a text field as the editor for a cell, just want to customize information technology — perhaps to check user-entered text more strictly or to react differently when the text is invalid — you can alter the cell editor to apply a formatted text field. The formatted text field tin can check the value either continuously while the user is typing or after the user has indicated the end of typing (such every bit by pressing Enter).
The following code, taken from a demo named TableFTFEditDemo.coffee, sets up a formatted text field as an editor that limits all integer values to be between 0 and 100. You tin can run TableFTFEditDemo (click the Launch button) using Coffee™ Web Kickoff (download JDK 7 or later on). 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 class is implemented as a bracket of DefaultCellEditor that uses a JFormattedTextField instead of the JTextField that DefaultCellEditor supports. It accomplishes this by commencement setting up a formatted text field to use 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, adding the operations that are necessary for formatted text fields.
The override of getTableCellEditorComponent sets the formatted text field'due south value property (and non just the text property information technology inherits from JTextField) before the editor is shown. The override of getCellEditorValue keeps the cell value equally an Integer, rather than, say, the Long value that the formatted text field'due south parser tends to render. Finally, overriding stopCellEditing lets you check whether the text is valid, maybe stopping the editor from existence dismissed. If the text isn't valid, your implementation of stopCellEditing puts up a dialog that gives the user the option of standing to edit or reverting to the last good value. The source lawmaking is a bit too long to include here, simply you can find information technology in IntegerEditor.coffee.
Printing
JTable provides a simple API for printing tables. The easiest way to print out a table is to invoke JTable.print with no arguments:
endeavour { if (! tabular array.impress()) { Organization.err.println("User cancelled printing"); } } catch (java.awt.print.PrinterException e) { System.err.format("Cannot print %s%northward", e.getMessage()); } Invoking print on a normal Swing application brings up a standard printing dialog box. (On a headless application, the tabular array is simply printed.) The return value indicates whether the user went ahead with the print job or cancelled it. JTable.print tin can throw java.awt.impress.PrinterException, which is a checked exception; that's why the in a higher place case uses a try ... catch.
JTable provides several overloads of impress with various options. The post-obit lawmaking from shows how to define a page header:TablePrintDemo.coffee
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 print %due south%n", e.getMessage()); } For more sophisticated printing applications, use JTable.getPrintable to obtain a Printable object for the table. For more on Printable, refer to the Printing lesson in the 2D Graphics trail.
Examples that Employ Tables
This table lists examples that use JTable and where those examples are described.
| Example | Where Described | Notes |
|---|---|---|
SimpleTableDemo | Creating a Simple Tabular array | A basic table with no custom model. Does not include code to specify column widths or discover user editing. |
SimpleTable- | Detecting User Selections | Adds single choice and choice detection to SimpleTableDemo. By modifying the program's ALLOW_COLUMN_SELECTION and ALLOW_ROW_SELECTION constants, you can experiment with alternatives to the table default of allowing just rows to be selected. |
TableDemo | Creating a Table Model | A bones tabular array 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 data. |
TableRenderDemo | Using a Combo Box as an Editor | Modifies TableDemo to use a custom editor (a combo box) for all information in the Sport column. Also intelligently picks cavalcade 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 brandish a color and allow you cull 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 set tool tip text for cells and cavalcade 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 tin cause the view coordinates to diverge from the model coordinates. |
TablePrintDemo | Printing | Demonstrates table printing. |
ListSelectionDemo | How to Write a List Selection Listener | Shows how to employ all list selection modes, using a list selection listener that'southward shared betwixt a table and list. |
SharedModelDemo | Nowhere | Builds on ListSelectionDemo making the data model be shared between the tabular array and list. If you edit an item in the first column of the table, the new value is reflected in the list. |
Source: https://docs.oracle.com/javase/tutorial/uiswing/components/table.html
0 Response to "Read Second Column of Integer and Save to the Array Java"
Post a Comment