With theJTableclass you can display tables of data, optionally allowing the user to edit the data.JTabledoes not contain or cache data; it is simply a view of your data. Here is a picture of a typical table displayed within a scroll pane:
The rest of this section shows you how to accomplish some common table-related tasks. Here are the topics this section covers:
Creating a Simple Table
Adding a Table to a Container
Setting and Changing Column 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
Printing
Examples that Use Tables
(download JDK 7 or later). Or, to compile and run the example yourself, consult theexample index.<="" p="">
Click the cell that contains "Snowboarding".
The entire first row is selected, indicating that you have selected Kathy Smith's data. A special highlight indicates that the "Snowboarding" cell is editable. Generally, you begin editing a text cell by double-clicking it.
Position the cursor over "First Name". Now press the mouse button and drag to the right.
As you 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 adjust to fill the remaining space.
Resize the window containing the table so that it's bigger than necessary to display the whole table.
All the table cells become wider, expanding to fill the extra horizontal space.
The table inSimpleTableDemo.javadeclares the column names in a String array:
String[> columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
Its data is initialized and stored in a two-dimensional Object array:
Object[>[] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
Then the Table is constructed using these data and columnNames:
JTable table = new JTable(data, columnNames);
There are twoJTableconstructors that directly accept data (SimpleTableDemouses the first):
JTable(Object[][] rowData, Object[] columnNames)
JTable(Vector rowData, Vector columnNames)
The advantage of these constructors is that they are easy to use. However, these constructors also have disadvantages:
They automatically make every cell editable.
They treat all data types the same (as strings). For example, if a table column hasBooleandata, the table can display the data in a check box. However, if you use either of the twoJTableconstructors listed previously, yourBooleandata is displayed as a string. You can see this difference in theVegetariancolumn of the previous figure.
They require that you put all of the table's data in an array or vector, which may not be appropriate for some data. For example, if you are instantiating a set of objects from a database, you 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 get around these restrictions, you need to implement your own table model, as described inCreating a Table Model.
Scroll Panethat Serves As A Container For A Table:
JScrollPane ScrollPane = New JScrollPane(Table);
Table.SetFillsViewportHeight(True);
The Two Lines In This Snippet Do The Following:
TheJScrollPaneconstructor Is Invoked With An Argument That Refers To The Table Object. This Creates A Scroll Pane As A Container For The Table; The Table Is Automatically Added To The Container.
JTable.SetFillsViewportHeightis Invoked To Set ThefillsViewportHeightproperty. When This Property Istruethe 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 As A Drag-And-Drop Target.
The Scroll Pane Automatically Places The Table Header At The Top Of The Viewport. The Column Names Remain Visible At The Top 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 Example:
Container.SetLayout(New BorderLayout());
Container.Add(Table.GetTableHeader(), BorderLayout.PAGE_START);
Container.Add(Table, BorderLayout.CENTER);
Setting And Changing Column Widths
By Default, All Columns In A Table Start Out With Equal Width, And The Columns Automatically Fill 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 Column By Dragging Its Right Border, Then Either Other Columns Must Change Size, Or The Table's Size Must Change. By Default, The Table's Size Remains The Same, And All Columns To The Right Of The Drag Point Resize To Accommodate Space Added To Or Removed From The Column To The Left Of The Drag Point.
To Customize Initial Column Widths, You Can InvokesetPreferredWidthon Each Of Your Table's Columns. This Sets Both The Preferred Widths Of The Columns And Their Approximate Relative Widths. For Example, Adding The Following Code ToSimpleTableDemomakes Its Third Column Bigger Than The Other Columns:
TableColumn Column = Null;
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 Column In A Table Is Represented By ATableColumnobject.TableColumnsupplies Getter And Setter Methods For The Minimum, Preferred, And Maximum Widths Of A Column, As Well As A Method For Getting The Current Width. For An Example Of Setting Cell Widths Based On An Approximation Of The Space Needed To Draw The Cells' Contents, See TheinitColumnSizesmethod InTableRenderDemo.Java.
When The User Explicitly Resizes Columns, The Columns'preferredwidths Are Set Such That The User-Specified Sizes Become The Columns' Newcurrentwidths. However, When Table Itself Is Resized — Typically Because The Window Has Resized —; The Columns' Preferred Widths Do Not Change. Instead, The Existing Preferred Widths Are Used To Calculate New Column Widths To Fill The Available Space.
You Can Change A Table's Resize Behavior By InvokingsetAutoResizeMode.
Javaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.Launches The TableSelectionDemo Example<="" P="">
This Example Program 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 First Row, Then Control-Clicked In The Third Row. Notice The Outline Around The Last Cell Clicked; This Is How The Metal Look And Feel Highlights The Lead Selection.
Under "Selection Mode" There Are A Set Of Radio Buttons. Click The One Labelled "Single Selection". Now You Can Only Select One Row At A Time. If You Click On The "Single Interval Selection" Radio Button, You Can Select A Set Of Rows That Must Be Contiguous.
All Of The Radio Buttons Under "Selection Mode" InvokeJTable.SetSelectionMode. This Method Takes A Single Argument, Which Must Be One Of The Following Constants Defined Injavax.Swing.ListSelectionModel:MULTIPLE_INTERVAL_SELECTION,SINGLE_INTERVAL_SELECTION, AndSINGLE_SELECTION.
Returning ToTableSelectionDemo, Notice The Three Option Checkboxes Under "Selection Options." Each Of Checkbox Controls The State Of Abooleanbound Variable Defined ByJTable:
"Row Selection" ControlsrowSelectionAllowedwhich Has Setter MethodsetRowSelectionAllowedand Getter MethodgetRowSelectionAllowed. When This Bound Property Istrue(And ThecolumnSelectionAllowedproperty Isfalse), The User Can Select By Row.
"Column Selection" ControlscolumnSelectionAllowedwhich Has Setter MethodsetColumnSelectionAllowedand Getter MethodgetColumnSelectionAllowed. When This Bound Property Istrue(And TherowSelectionAllowedbound Property Isfalse), The User Can Select By Column.
"Cell Selection" ControlscellSelectionEnabled, Which Has Setter MethodsetCellSelectionEnabledand Getter MethodgetCellSelectionEnabled. When This Bound Property Istrue, The User Can Select A Single Cell Or Rectangular Block Of Cells.
NOTE: JTableuses A Very Simple Concept Of Selection, Managed As An Intersection Of Rows And Columns. It Was Not Designed To Handle Fully Independent Cell Selections.
If You Clear All Three Check Boxes (Setting All Three Bound Properties Tofalse), There Is No Selection; Only The Lead Selection Is Shown.
You May Notice That The "Cell Selection" Checkbox Is Disabled In Multiple Interval Selection Mode. This Is Because Cell Selection Is Not Supported In This Mode In The Demo. You Can Specify Selection By Cell In Multiple Interval Selection Mode, But The Result Is A Table That Does Not Produce Useful Selections.
You May Also Notice That Changing Any Of The Three Selection Options Can Affect The Others. This Is Because Allowing Both Row Selection And Column Selection Is Exactly The Same As Enabling Cell Selection.JTableautomatically Updates The Three Bound Variables As Necessary To Keep Them Consistent.
NOTE: SettingcellSelectionEnabledto A Value Has The Side Effect Of Also Setting BothrowSelectionEnabledandcolumnSelectionEnabledto That Value. Setting BothrowSelectionEnabledandcolumnSelectionEnabledto A Value Has The Side Effect Of Also SettingcellSelectionEnabledto That Value. SettingrowSelectionEnabledandcolumnSelectionEnabledto Different Values Has The Side Effect Of Also SettingcellSelectionEnabledtofalse.
To Retrieve The Current Selection, UseJTable.GetSelectedRowswhich Returns An Array Of Row Indexes, AndJTable.GetSelectedColumnswhich Returns An Array Of Column Indexes. To Retrieve The Coordinates Of The Lead Selection, Refer To The Selection Models For The Table Itself And For The Table's Column Model. The Following Code Formats A String Containing The Row And Column Of The Lead Selection:
String.Format("Lead Selection: %D, %D. ",
Table.GetSelectionModel().GetLeadSelectionIndex(),
Table.GetColumnModel().GetSelectionModel().GetLeadSelectionIndex());
User Selections Generate A Number Of Events. For Information On These, Refer ToHow To Write A List Selection Listenerin TheWriting Event Listenerslesson.
NOTE: Selection Data Actually Describes Selected Cells In The "View" (Table Data As It Appears After Any Sorting Or Filtering) Rather Than In The Table Model. This Distinction Does Not Matter Unless Your Viewed Data Has Been Rearranged By Sorting, Filtering, Or User Manipulation Of Columns. In That Case, You Must Convert Selection Coordinates Using The Conversion Methods Described InSorting And Filtering.
TableModelinterface. If The Programmer Does Not Provide A Table Model Object,JTableautomatically Creates An Instance OfDefaultTableModel. This Relationship Is Illustrated Below.<="" p="">
TheJTableconstructor Used BySimpleTableDemocreates Its Table Model With Code 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) { Return RowData[Row>[Col]; } Public Boolean IsCellEditable(Int Row, Int Col) { Return 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 Be Simple. Generally, You Implement Your Table Model In A Subclass Of TheAbstractTableModelclass.
Your Model Might Hold Its Data In An Array, Vector, Or Hash Map, Or It Might Get The Data From An Outside Source Such As A Database. It Might Even Generate The Data At Execution Time.
This Table Is Different From TheSimpleTableDemotable In The Following Ways:
TableDemo's Custom Table Model, Even Though It Is Simple, Can Easily Determine The Data's Type, Helping TheJTabledisplay The Data In The Best Format.SimpleTableDemo's Automatically Created Table Model, On The Other Hand, Does Not Know That The# Of Yearscolumn Contains Numbers (Which Should Generally Be Right Aligned And Have A Particular Format). It Also Does Not Know That TheVegetariancolumn Contains Boolean Values, Which Can Be Represented By Check Boxes.
The Custom Table Model Implemented InTableDemodoes Not Let You Edit The Name Columns; It Does, However, Let You Edit The Other Columns. InSimpleTableDemo, All Cells Are Editable.
See Below The Code Taken FromTableDemo.Javathat Is Different From TheSimpleTableDemo.Java. Bold Font Indicates The Code That Makes This Table's Model Different From The Table Model Defined Automatically ForSimpleTableDemo.
Public TableDemo() {
...
JTable Table = New JTable(New MyTableModel());
...
}
Class MyTableModel Extends AbstractTableModel {
Private String[] ColumnNames = ...//Same As Before...
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) {
Return Data[Row][Col];
}
Public Class GetColumnClass(Int C) {
Return GetValueAt(0, C).GetClass();
}
/*
* Don't Need To Implement This Method Unless Your Table's
* Editable.
*/
Public Boolean IsCellEditable(Int Row, Int Col) {
//Note That The Data/Cell Address Is Constant,
//No Matter Where The Cell Appears Onscreen.
If (Col < 2) {
Return False;
} Else {
Return True;
}
}
/*
* Don't Need To Implement This Method Unless Your Table's
* Data Can Change.
*/
Public Void SetValueAt(Object Value, Int Row, Int Col) {
Data[Row][Col] = Value;
FireTableCellUpdated(Row, Col);
}
...
}
TableModelListener. In The Following Example Code,SimpleTableDemois Extended To Include Such A Listener. New Code Is In Bold.
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 = E.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...
}
...
}
TableModelEventobject. This Can Be A Complex Procedure, But Is Already Implemented InDefaultTableModel. You Can Either AllowJTableto Use Its Default Instance OfDefaultTableModel, Or Create Your Own Custom Subclass OfDefaultTableModel.
IfDefaultTableModelis Not A Suitable Base Class For Your Custom Table Model Class, Consider SubclassingAbstractTableModel. This Class Implements A Simple Framework For ConstructingTableModelEventobjects. Your Custom Class Simply Needs To Invoke One The FollowingAbstractTableModelmethods Each Time Table Data Is Changed By An External Source.
MethodChange
FireTableCellUpdatedUpdate Of Specified Cell.
FireTableRowsUpdatedUpdate Of Specified Rows
FireTableDataChangedUpdate Of Entire Table (Data Only).
FireTableRowsInsertedNew Rows Inserted.
FireTableRowsDeletedExisting Rows Deleted
FireTableStructureChanged Invalidate Entire Table, Both Data And Structure.
NumberFormatinstance (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 Short Style For The Date And Time).
ImageIcon,Icon— Rendered By A Centered Label.
Object— Rendered By A Label That Displays The Object's String Value.
Cell Editors Are Chosen Using A Similar Algorithm.
Remember That If You Let A Table Create Its Own Model, It UsesObjectas The Type Of Every Column. To Specify More Precise Column Types, The Table Model Must Define ThegetColumnClassmethod Appropriately, As Demonstrated ByTableDemo.Java.
Keep In Mind 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 Up The Events That Take Place Inside A Table, The Technique You Use Varies By The Sort Of Event You Are Interested In:
SituationHow To Get Events
To Detect Events From A Cell That Is Being Edited...Use The Cell Editor (Or Register A Listener On The Cell Editor).
To Detect Row/Column/Cell Selections And Deselections...Use A Selection Listener As Described InDetecting User Selections.
To Detect Mouse Events On A Column Header...Register The Appropriate Type Ofmouse Listeneron The Table'sJTableHeaderobject. (SeeTableSorter.Javafor An Example.)
To Detect Other Events...Register The Appropriate Listener On TheJTableobject.
The Next Few Sections Tell You How To Customize Display And Editing By Specifying Renderers And Editors. You Can Specify Cell Renderers And Editors Either By Column Or By Data Type.
Using Custom Renderers
This Section Tells You How To Create And Specify A Cell Renderer. You Can Set A Type-Specific Cell Renderer Using TheJTablemethodsetDefaultRenderer. To Specify That Cells In A Particular Column Should Use A Renderer, You Use TheTableColumnmethodsetCellRenderer. You Can Even Specify A Cell-Specific Renderer By Creating AJTablesubclass.
It Is Easy To Customize The Text Or Image Rendered By The Default Renderer,DefaultTableCellRenderer. You Just Create A Subclass And Implement ThesetValuemethod So That It InvokessetTextorsetIconwith The Appropriate String Or Image. 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 ExtendingDefaultTableCellRendereris Insufficient, You Can Build A Renderer Using Another Superclass. The Easiest Way Is To Create A Subclass Of An Existing Component, Making Your Subclass Implement TheTableCellRendererinterface.TableCellRendererrequires Just One Method:GetTableCellRendererComponent. Your Implementation Of This Method Should Set Up The Rendering Component To Reflect The Passed-In State, And Then Return The Component.
In ThesnapshotofTableDialogEditDemo, The Renderer Used ForFavorite Colorcells Is A Subclass OfJLabelcalledColorRenderer. Here Are Excerpts FromColorRenderer.Javathat 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 Border In The Color
//Table.GetSelectionBackground().
SetBorder(SelectedBorder);
} Else {
...
//UnselectedBorder Is A Solid Border In The Color
//Table.GetBackground().
SetBorder(UnselectedBorder);
}
}
SetToolTipText(...); //Discussed In The Following Section
Return This;
}
}
Here Is The Code FromTableDialogEditDemo.Javathat Registers AColorRendererinstance As The Default Renderer For AllColordata:
Table.SetDefaultRenderer(Color.Class, New ColorRenderer(True));
To Specify A Cell-Specific Renderer, You Need To Define AJTablesubclass That Overrides ThegetCellRenderermethod. For Example, The Following Code Makes The First Cell In The First Column Of The Table Use A Custom Renderer:
TableCellRenderer WeirdRenderer = New WeirdRenderer();
Table = New JTable(...) {
Public TableCellRenderer GetCellRenderer(Int Row, Int Column) {
If ((Row == 0) && (Column == 0)) {
Return WeirdRenderer;
}
// Else...
Return Super.GetCellRenderer(Row, Column);
}
};
Javaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.Launches The TableRenderDemo Example<="" P="">
The Source Code Is InTableRenderDemo.Java. It Adds Tool Tips To The Cells Of TheSportcolumn With The Following Code:
//Set Up 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 Can Also Implement Tool Tips Whose Text Changes Depending On The State Of The Cell Or Program. Here Are A Couple Ways To Do So:
Add A Bit Of Code To The Renderer's Implementation Of ThegetTableCellRendererComponentmethod.
Override TheJTablemethodgetToolTipText(MouseEvent).
An Example Of Adding Code To A Cell Renderer Is InTableDialogEditDemo. Click The Launch Button To Run It UsingJavaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.
<="" p="">
TableDialogEditDemouses A Renderer For Colors, Implemented InColorRenderer.Java, 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 Example Of What The Tool Tip Looks Like:
[Img Src="How%20to%20Use%20Tables%20%28The%20Java%E2%84%A2%20Tutorials%20%29%20Creating%20a%20GUI%20With%20JFC_Swing%20%29%20Using%20Swing%20Components%29_files/TableDialogEditDemo-Tooltip.Png" Alt="TableDialogEditDemo With A Tool Tip Describing The Moused-Over Cell's RGB Value" Height="119" Align="Bottom" Width="526">
You Can Specify Tool Tip Text By OverridingJTable'sgetToolTipText(MouseEvent)Method. The ProgramTableToolTipsDemoshows How. Click The Launch Button To Run It UsingJavaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.
The Cells With Tool Tips Are In TheSportandVegetariancolumns. Here Is A Picture Of Its Tool Tip:
Here Is The Code FromTableToolTipsDemo.Javathat Implements Tool Tips For Cells In TheSportandVegetariancolumns:
JTable Table = New JTable(New MyTableModel()) { //Implement Table Cell Tool Tips. Public String GetToolTipText(MouseEvent E) { String Tip = Null; Java.Awt.Point P = E.GetPoint(); Int RowIndex = RowAtPoint(P); Int ColIndex = ColumnAtPoint(P); Int RealColumnIndex = ConvertColumnIndexToModel(ColIndex); If (RealColumnIndex == 2) { //Sport Column Tip = "This Person's Favorite Sport To " + "Participate In Is: " + GetValueAt(RowIndex, ColIndex); } Else If (RealColumnIndex == 4) { //Veggie Column TableModel Model = GetModel(); String FirstName = (String)Model.GetValueAt(RowIndex,0); String LastName = (String)Model.GetValueAt(RowIndex,1); Boolean Veggie = (Boolean)Model.GetValueAt(RowIndex,4); If (Boolean.TRUE.Equals(Veggie)) { Tip = FirstName + " " + LastName + " Is A Vegetarian"; } Else { Tip = FirstName + " " + LastName + " Is Not A Vegetarian"; } } Else { //Another Column //You Can Omit This Part If You Know You Don't //Have Any Renderers That Supply Their Own Tool //Tips. Tip = Super.GetToolTipText(E); } Return Tip; } ... }
The Code Is Fairly Straightforward, Except Perhaps For The Call ToconvertColumnIndexToModel. That Call Is Necessary Because If The User Moves The Columns Around, The View's Index For The Column Will Not Match The Model's Index For The Column. For Example, The User Might Drag TheVegetariancolumn (Which The Model Considers To Be At Index 4) So It Is Displayed As The First Column — At View Index 0. SinceprepareRendererprovides The View Index, You Need To Translate The View Index To A Model Index So You Can Be Sure The Intended Column Has Been Selected.
TableSorterDemo.Java. Here Is How It Sets The Tool Tip Text:
Table.GetTableHeader().SetToolTipText(
"Click To Sort; Shift-Click To Sort In Reverse Order");
TableToolTipsDemo.Javahas An Example Of Implementing Column Header Tool Tips That Vary By Column. If You RunTableToolTipsDemo(Click The Launch Button) UsingJavaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.
Launches The TableToolTipsDemo Example
You Will See The Tool Tips When You Mouse Over Any Column Header Except For The First Two. No Tool Tips Were Suppled For The Name Columns Since They Seemed Self-Explanatory. Here Is A Picture Of One Of The Column Header Tool Tips:
The Following Code Implements The Tool Tips. Basically, It Creates A Subclass OfJTableHeaderthat Overrides ThegetToolTipText(MouseEvent)Method So That It Returns The Text For The Current Column. To Associate The Revised Table Header With The Table, TheJTablemethodcreateDefaultTableHeaderis Overridden So That It Returns An Instance Of TheJTableHeadersubclass.
Protected String[> ColumnToolTips = { Null, // "First Name" Assumed Obvious Null, // "Last Name" Assumed Obvious "The Person's Favorite Sport To Participate In", "The Number Of Years The Person Has Played The Sport", "If Checked, The Person Eats No Meat"}; ... JTable Table = New JTable(New MyTableModel()) { ... //Implement Table Header Tool Tips. Protected JTableHeader CreateDefaultTableHeader() { Return New JTableHeader(ColumnModel) { Public String GetToolTipText(MouseEvent E) { String Tip = Null; Java.Awt.Point P = E.GetPoint(); Int Index = ColumnModel.GetColumnIndexAtX(P.X); Int RealIndex = ColumnModel.GetColumn(Index).GetModelIndex(); Return ColumnToolTips[RealIndex>; } }; } };
Sorting And Filtering
Table Sorting And Filtering Is Managed By Asorterobject. The Easiest Way To Provide A Sorter Object Is To SetautoCreateRowSorterbound Property Totrue:
JTable Table = New JTable();
Table.SetAutoCreateRowSorter(True);
This Action Defines A Row Sorter That Is An Instance Ofjavax.Swing.Table.TableRowSorter. This Provides A Table That Does A Simple Locale-Specific Sort When The User Clicks On A Column Header. This Is Demonstrated InTableSortDemo.Java, As Seen In This Screen Shot:
TableSortDemo After Clicking Last Name<="" P="">
To Have More Control Over Sorting, You Can Construct An Instance OfTableRowSorterand Specify That It Is The Sorter Object For Your Table.
TableRowSorter Sorter = New TableRowSorter(Table.GetModel()); Table.SetRowSorter(Sorter);
TableRowSorterusesjava.Util.Comparatorobjects To Sort Its Rows. A Class That Implements This Interface Must Provide A Method Calledcomparethat Defines How Any Two Objects Are Compared For The Purpose Of Sorting. For Example, The Following Code Creates AComparatorthat Sorts A Set Of Strings By The Last Word In Each String:
Comparator Comparator = New Comparator() {
Public Int Compare(String S1, String S2) {
String[> Strings1 = S1.Split("\\S");
String[> Strings2 = S2.Split("\\S");
Return Strings1[Strings1.Length - 1]
.CompareTo(Strings2[Strings2.Length - 1]);
}
};
This Example Is Fairly Simplistic; More Typically, AComparatorimplementation Is A Subclass Ofjava.Text.Collator. You Can Define Your Own Subclass, Use The Factory Methods InCollatorto Obtain AComparatorfor A Specific Locale, Or Usejava.Text.RuleBasedCollator.
To Determine WhichComparatorto Use For A Column,TableRowSorterattempts To Apply Each Of The Following Rules In Turn. Rules Are Followed In The Order Listed Below; The First Rule That Provides The Sorter With AComparatoris Used, And The Remainining Rules Ignored.
If A Comparator Has Been Specified By InvokingsetComparator, Use That Comparator.
If The Table Model Reports That The Column Data Consists Of Strings (TableModel.GetColumnClassreturnsString.Classfor That Column), Use A Comparator That Sorts The Strings Based On The Current Locale.
If The Column Class Returned ByTableModel.GetColumnClassimplementsComparable, Use A Comparator That Sorts The Strings Based On The Values Returned ByComparable.CompareTo.
If A String Convertor Has Been Specified For The Table By InvokingsetStringConverter, Use A Comparator That Sorts The Resulting String Representations Based On The Current Locale.
If None Of The Previous Rules Apply, Use A Comparator That InvokestoStringon The Column Data And Sorts The Resulting Strings Based On The Current Locale.
For More Sophisticated Kinds Of Sorting, SubclassTableRowSorteror Its Parent Classjavax.Swing.DefaultRowSorter.
To Specify The Sort Order And Sort Precedence For Columns, InvokesetSortKeys. 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 Key, So They Rows Are Sorted By First Name, Then Last Name.
List SortKeys
= New ArrayList();
SortKeys.Add(New RowSorter.SortKey(1, SortOrder.ASCENDING));
SortKeys.Add(New RowSorter.SortKey(0, SortOrder.ASCENDING));
Sorter.SetSortKeys(SortKeys);
In Addition To Reordering The Results, A Table Sorter Can Also Specify Which Rows Will Be Displayed. This Is Known Asfiltering.TableRowSorterimplements Filtering Usingjavax.Swing.RowFilterobjects.RowFilterimplements Several Factory Methods That Create Common Kinds Of Filters. For Example,RegexFilterreturns ARowFilterthat Filters Based On Aregular Expression.
In The Following Example Code, You Explicitly Create A Sorter Object So You Can Later Use It To Specify A Filter:
MyTableModel Model = New MyTableModel();
Sorter = New TableRowSorter(Model);
Table = New JTable(Model);
Table.SetRowSorter(Sorter);
Then You Filter Based On The Current Value Of A Text Field:
Private Void NewFilter() {
RowFilter Rf = Null;
//If Current Expression Doesn't Parse, Don't Update.
Try {
Rf = RowFilter.RegexFilter(FilterText.GetText(), 0);
} Catch (Java.Util.Regex.PatternSyntaxException E) {
Return;
}
Sorter.SetRowFilter(Rf);
}
In A Subsequent Example,NewFilter()Is Invoked Every Time The Text Field Changes. When The User Enters Complicated Regular Expressions, Thetry...Catchprevents The Syntax Exception From Interfering With Input.
When A Table Uses A Sorter, The Data The Users Sees May Be In A Different Order Than That Specified By The Data Model, And May Not Include All Rows Specified By The Data Model. The Data The User Actually Sees Is Known As Theview, And Has Its Own Set Of Coordinates.JTableprovides Methods That Convert From Model Coordinates To View Coordinates —ConvertColumnIndexToViewandconvertRowIndexToView— And That Convert From View Coordinates To Model Coordinates —ConvertColumnIndexToModelandconvertRowIndexToModel.
NOTE: When Using A Sorter, Always Remember To Translate Cell Coordinates.
The Following Example Brings Together The Ideas Discussed In This Section.TableFilterDemo.Javaadds A Small Number Of Changes ToTableDemo. These Include The Code Snippets Earlier 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 ShowsTableFilterDemobefore Any Sorting Or Filtering Has Been Done. Notice That Row 3 In The Model Is Still The Same As Row 3 In The View:
[Img Src="How%20to%20Use%20Tables%20%28The%20Java%E2%84%A2%20Tutorials%20%29%20Creating%20a%20GUI%20With%20JFC_Swing%20%29%20Using%20Swing%20Components%29_files/FilterSort.Png" Alt="TableFilterDemo Without Sorting" Height="177" Align="Bottom" Width="526">
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 Can Cause View Coordinates To Diverge From Model Coordinates:
Here Is The Code That Updates The Status Field To Reflect The Current Selection:
Table.GetSelectionModel().AddListSelectionListener( New ListSelectionListener() { Public Void ValueChanged(ListSelectionEvent Event) { Int ViewRow = Table.GetSelectedRow(); If (ViewRow < 0) { //Selection Got Filtered Away. StatusText.SetText(""); } Else { Int ModelRow = Table.ConvertRowIndexToModel(ViewRow); StatusText.SetText( String.Format("Selected Row In View: %D. " + "Selected Row In Model: %D.", ViewRow, ModelRow)); } } } );
Combo Boxas An Editor Is Simple, As The Following Example Shows. The Bold 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:
A Combo Box Cell Editor In Use
The Preceding Code Is FromTableRenderDemo.Java. You Can RunTableRenderDemo(Click The Launch Button) UsingJavaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.
TableCellEditor[/A>Interface. TheAbstractCellEditorclass Is A Good Superclass To Use. It ImplementsTableCellEditor's Superinterface,CellEditor, Saving You The Trouble Of Implementing The Event Firing Code Necessary For Cell Editors.
Your Cell Editor Class Needs To Define At Least Two Methods —GetCellEditorValueandgetTableCellEditorComponent. ThegetCellEditorValuemethod, Required ByCellEditor, Returns The Cell's Current Value. ThegetTableCellEditorComponentmethod, Required ByTableCellEditor, Should Configure And Return The Component That You Want To Use As 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 Cell In TheFavorite Colorcolumn, A Button (The True Cell Editor) Appears And Brings Up The Dialog, With Which The User Can Choose A Different Color.
Javaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.
[Img Src="How%20to%20Use%20Tables%20%28The%20Java%E2%84%A2%20Tutorials%20%29%20Creating%20a%20GUI%20With%20JFC_Swing%20%29%20Using%20Swing%20Components%29_files/Jws-Launch-Button.Png" Alt="Launches The TableDialogEditDemo Example" Height="23" Align="Bottom" Width="88">
Here Is The Code, Taken FromColorEditor.Java, That Implements The Cell Editor.
Public Class ColorEditor Extends AbstractCellEditor Implements TableCellEditor, ActionListener { Color CurrentColor; JButton Button; JColorChooser ColorChooser; JDialog Dialog; Protected Static Final String EDIT = "Edit"; Public ColorEditor() { Button = New JButton(); Button.SetActionCommand(EDIT); Button.AddActionListener(This); Button.SetBorderPainted(False); //Set Up 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 Button Handler } Public Void ActionPerformed(ActionEvent E) { 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 Defined By TableCellEditor. Public Component GetTableCellEditorComponent(JTable Table, Object Value, Boolean IsSelected, Int Row, Int Column) { CurrentColor = (Color)Value; Return Button; } }
As You Can See, The Code Is Pretty Simple. The Only Part That Is A Bit Tricky Is The Call TofireEditingStoppedat The End 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 TofireEditingStoppedlets The Table Know That It Can Deactivate The Editor, Letting The Cell Be Handled By The Renderer Again.
Formatted Text Field. The Formatted Text Field Can Check The Value Either Continuously While The User Is Typing Or After The User Has Indicated The End Of Typing (Such As By Pressing Enter).
The Following Code, Taken From A Demo NamedTableFTFEditDemo.Java, Sets Up A Formatted Text Field As An Editor That Limits All Integer Values To Be Between 0 And 100. You Can RunTableFTFEditDemo(Click The Launch Button) UsingJavaâ„¢ Web Start(Download JDK 7 Or Later). Or, To Compile And Run The Example Yourself, Consult Theexample Index.
[Img Src="How%20to%20Use%20Tables%20%28The%20Java%E2%84%A2%20Tutorials%20%29%20Creating%20a%20GUI%20With%20JFC_Swing%20%29%20Using%20Swing%20Components%29_files/Jws-Launch-Button.Png" Alt="Launches The TableFTFEditDemo Example" Height="23" Align="Bottom" Width="88">
The Following Code Makes The Formatted Text Field The Editor For All Columns That Contain Data Of TypeInteger.
Table.SetDefaultEditor(Integer.Class, New IntegerEditor(0, 100));
TheIntegerEditorclass Is Implemented As A Subclass OfDefaultCellEditorthat Uses AJFormattedTextFieldinstead Of TheJTextFieldthatDefaultCellEditorsupports. It Accomplishes This By First Setting Up A Formatted Text Field To Use An Integer Format And Have The Specified Minimum And Maximum Values, Using The API Described InHow To Use Formatted Text Fields. It Then Overrides TheDefaultCellEditorimplementation Of ThegetTableCellEditorComponent,GetCellEditorValue, AndstopCellEditingmethods, Adding The Operations That Are Necessary For Formatted Text Fields.
The Override OfgetTableCellEditorComponentsets The Formatted Text Field'svalueproperty (And Not Just Thetextproperty It Inherits FromJTextField) Before The Editor Is Shown. The Override OfgetCellEditorValuekeeps The Cell Value As AnInteger, Rather Than, Say, TheLongvalue That The Formatted Text Field's Parser Tends To Return. Finally, OverridingstopCellEditinglets You Check Whether The Text Is Valid, Possibly Stopping The Editor From Being Dismissed. If The Text Isn't Valid, Your Implementation OfstopCellEditingputs Up A Dialog That Gives The User The Option Of Continuing To Edit Or Reverting To The Last Good Value. The Source Code Is A Bit Too Long To Include Here, But You Can Find It InIntegerEditor.Java.
JTable.Printwith No Arguments:
Try {
If (! Table.Print()) {
System.Err.Println("User Cancelled Printing");
}
} Catch (Java.Awt.Print.PrinterException E) {
System.Err.Format("Cannot Print %S%N", E.GetMessage());
}
Invokingprinton A Normal Swing Application Brings Up A Standard Printing Dialog Box. (On A Headless Application, The Table Is Simply Printed.) The Return Value Indicates Whether The User Went Ahead With The Print Job Or Cancelled It.JTable.Printcan Throwjava.Awt.Print.PrinterException, Which Is Achecked Exception; That's Why The Above Example Uses Atry ... Catch.
JTableprovides Several Overloads Ofprintwith Various Options. The Following Code FromTablePrintDemo.Javashows How To Define A Page Header:
MessageFormat Header = New MessageFormat("Page {0,Number,Integer}");
Try {
Table.Print(JTable.PrintMode.FIT_WIDTH, Header, Null);
} Catch (Java.Awt.Print.PrinterException E) {
System.Err.Format("Cannot Print %S%N", E.GetMessage());
}
For More Sophisticated Printing Applications, UseJTable.GetPrintableto Obtain APrintableobject For The Table. For More OnPrintable, Refer To ThePrintinglesson In The2D Graphicstrail.
SimpleTableDemoCreating A Simple TableA Basic Table Withnocustom Model. Does Not Include Code Tospecify Column Widthsordetect User Editing.SimpleTable-
SelectionDemoDetecting User SelectionsAdds Single Selection And Selection Detection ToSimpleTableDemo. By Modifying The Program'sALLOW_COLUMN_SELECTIONandALLOW_ROW_SELECTIONconstants, You Can Experiment With Alternatives To The Table Default Of Allowing Only Rows To Be Selected.TableDemoCreating A Table ModelA Basic Table With A Custom Model.TableFTFEditDemoUsing An Editor To Validate User-Entered TextModifiesTableDemoto Use A Custom Editor (A Formatted Text Field Variant) For AllIntegerdata.TableRenderDemoUsing A Combo Box As An EditorModifiesTableDemoto Use A Custom Editor (A Combo Box) For All Data In TheSportcolumn. Also Intelligently Picks Column Sizes. Uses Renderers To Display Tool Tips For The Sport Cells.TableDialogEditDemoUsing Other EditorsModifiesTableDemoto Have A Cell Renderer And Editor That Display A Color And Let You Choose A New One, Using A Color Chooser Dialog.TableToolTipsDemoSpecifying Tool Tips For Cells,Specifying Tool Tips For Column Headers,Demonstrates How To Use Several Techniques To Set Tool Tip Text For Cells And Column Headers.TableSortDemoSorting And FilteringDemonstrates The Default Sorter, Which Allows The User To Sort Columns By Clicking On Their Headers.TableFilterDemoSorting And FilteringDemonstrates Sorting And Filtering, And How This Can Cause The View Coordinates To Diverge From The Model Coordinates.TablePrintDemoPrintingDemonstrates Table Printing.ListSelectionDemoHow To Write A List Selection ListenerShows How To Use All List Selection Modes, Using A List Selection Listener That's Shared Between A Table And List.SharedModelDemoNowhereBuilds OnListSelectionDemomaking The Data Model Be Shared Between The Table And List. If You Edit An Item In The First Column Of The Table, The New Value Is Reflected In The List.
Copyright © 2011 - All Rights Reserved - Softron.in
Template by Softron Technology