+ All Categories
Home > Documents > How to Use Tables

How to Use Tables

Date post: 03-Jan-2016
Category:
Upload: dane-hodges
View: 38 times
Download: 5 times
Share this document with a friend
Description:
How to Use Tables. The practice of JTable in swing. The JTable component. In many applications a Table is a natural representation to use: Displays a grid of data consisting of rows and columns similar to a spreadsheet. - PowerPoint PPT Presentation
23
How to Use Tables How to Use Tables The practice of JTable in The practice of JTable in swing swing
Transcript
Page 1: How to Use Tables

How to Use Tables How to Use Tables

The practice of JTable in swingThe practice of JTable in swing

Page 2: How to Use Tables

The JTable componentThe JTable component

In many applications a Table is a natural In many applications a Table is a natural representation to use: representation to use: • Displays a grid of data consisting of rows and Displays a grid of data consisting of rows and

columns similar to a spreadsheet. columns similar to a spreadsheet. • The JTableclass is The JTableclass is NOTNOT a spreadsheet, but it supports a spreadsheet, but it supports

many features that make it superior to a simple many features that make it superior to a simple spreadsheet component. spreadsheet component.

The JTable component that provides the power The JTable component that provides the power to present large amounts of data in a simple to present large amounts of data in a simple 2D display2D display• it supports custom data modeling and display it supports custom data modeling and display

rendering rendering

Page 3: How to Use Tables

A Simple Table ExampleA Simple Table Example

Page 4: How to Use Tables

A Simple table ExampleA Simple table Example Clicking the left mouse button on an individual cell will highlight Clicking the left mouse button on an individual cell will highlight

the entire row and select the individual cell the entire row and select the individual cell • Initially the select rectangle is surrounding the 89.2 value. Initially the select rectangle is surrounding the 89.2 value. • If you reduce the height of the window, the vertical scroll bar If you reduce the height of the window, the vertical scroll bar

appears by default. appears by default. • Resizing the frame in the horizontal direction automatically adds the Resizing the frame in the horizontal direction automatically adds the

horizontal scroll bar. horizontal scroll bar. The application also inherits is the ability to reorganize and The application also inherits is the ability to reorganize and

resize the columns: resize the columns: • Placing the mouse over a column name and dragging it (with the left Placing the mouse over a column name and dragging it (with the left

mouse button pressed) allows the entire column to be moved to a mouse button pressed) allows the entire column to be moved to a new position. new position.

• When the mouse button is released, the selected column is dropped When the mouse button is released, the selected column is dropped into its new location and the entire table is repainted to into its new location and the entire table is repainted to accommodate the adjustment. accommodate the adjustment.

• Placing the mouse on the vertical separator between two column Placing the mouse on the vertical separator between two column headers causes the pointer to change to a resize indicator. Holding headers causes the pointer to change to a resize indicator. Holding down the left mouse button while dragging resizes the columns. down the left mouse button while dragging resizes the columns.

Page 5: How to Use Tables

// Constructor of main framepublic SimpleTableExample(){

// Set the frame characteristicssetTitle( "Simple Table Application" );setSize( 300, 200 );setBackground( Color.gray );

 // Create a panel to hold all other componentstopPanel = new JPanel();topPanel.setLayout( new BorderLayout() );getContentPane().add( topPanel );

 // Create columns namesString columnNames[] = { "Column 1", "Column 2", "Column 3" };

 // Create some dataString dataValues[][] ={

{ "12", "234", "67" },{ "-123", "43", "853" },{ "93", "89.2", "109" },{ "279", "9033", "3092" }

}; 

// Create a new table instancetable = new JTable( dataValues, columnNames );

 // Add the table to a scrolling panescrollPane = new JScrollPane( table );topPanel.add( scrollPane, BorderLayout.CENTER );

Page 6: How to Use Tables

A More Complex ExampleA More Complex Example

Page 7: How to Use Tables

More complex exampleMore complex example Uses loader methods to load an array of eight Uses loader methods to load an array of eight

columns by one hundred rows. columns by one hundred rows. Additionally, the table is configured to show only Additionally, the table is configured to show only

the vertical grid lines and to allow simultaneous the vertical grid lines and to allow simultaneous row and column selection. row and column selection.

Notice that with this example, when an individual Notice that with this example, when an individual cell is selected, a cross-hair selection pattern is cell is selected, a cross-hair selection pattern is formed, centered around the selected cell. formed, centered around the selected cell.

Also the foreground and background colours for Also the foreground and background colours for the selection region have been altered for effect the selection region have been altered for effect (since JTable supports colour changes for the (since JTable supports colour changes for the selection area). selection area).

Page 8: How to Use Tables

public AdvancedTableExample(){ // Set the frame characteristics

setTitle( "Advanced Table Application" );setSize( 300, 200 );setBackground( Color.gray );

 // Create a panel to hold all other componentstopPanel = new JPanel();topPanel.setLayout( new BorderLayout() );getContentPane().add( topPanel );

 // Create columnsCreateColumns();CreateData();

 // Create a new table instancetable = new JTable( dataValues, columnNames );

 // Configure some of JTable's paramterstable.setShowHorizontalLines( false );table.setRowSelectionAllowed( true );table.setColumnSelectionAllowed( true );

 // Change the selection colourtable.setSelectionForeground( Color.white );table.setSelectionBackground( Color.red );

 // Add the table to a scrolling panescrollPane = table.createScrollPaneForTable( table );topPanel.add( scrollPane, BorderLayout.CENTER );

}

Page 9: How to Use Tables

Adding a Custom Data ModelAdding a Custom Data Model The JTable supports the replacement of its data model in The JTable supports the replacement of its data model in

order to improve performance or to help reduce the size of order to improve performance or to help reduce the size of the code required for a given application. the code required for a given application.

The custom data model feature used in JTable is actually The custom data model feature used in JTable is actually simpler than the one used for (for example) the JTree class: simpler than the one used for (for example) the JTree class: • JTable only has to manage a simple 2D matrix of data JTable only has to manage a simple 2D matrix of data

Re-engineer the code from the previous example. This Re-engineer the code from the previous example. This example, example, • build a new application that uses a custom data model but build a new application that uses a custom data model but • produces exactly the same results the previous example. produces exactly the same results the previous example. • Though Though the output looks the same as the one shown the output looks the same as the one shown

previously, it offers much better performance, particularly as previously, it offers much better performance, particularly as the size of the data set grows. the size of the data set grows.

Page 10: How to Use Tables

CustomDataTableExampleCustomDataTableExample Contains the code for the main frame class, which is a Contains the code for the main frame class, which is a

modified version of the previous example: modified version of the previous example: • the CreateData() method has been removed -- it is no longer the CreateData() method has been removed -- it is no longer

required because the custom data model generates the data required because the custom data model generates the data set. set.

• the CreateColumns() method has been changed -- the code no the CreateColumns() method has been changed -- the code no longer uses an instance of the DefaultDataModel class longer uses an instance of the DefaultDataModel class (instantiated automatically by JTable in the previous example). (instantiated automatically by JTable in the previous example).

• the application is now required to create its own columns -- the the application is now required to create its own columns -- the CreateColumns() method reverts to first principles by creating CreateColumns() method reverts to first principles by creating an instance of a TableColumn object and populating it with the an instance of a TableColumn object and populating it with the appropriate text before adding it to the table. appropriate text before adding it to the table.

• the example now generates its own column data therefore it the example now generates its own column data therefore it notifies the table not to attempt to determine this information notifies the table not to attempt to determine this information from the data. It does this by calling JTable's from the data. It does this by calling JTable's setAutoCreateColumnsFromModel() method. setAutoCreateColumnsFromModel() method.

Page 11: How to Use Tables

CustomDataModelCustomDataModel Thee custom data model, which extends the Thee custom data model, which extends the

AbstractTableModel class and provides four methods called AbstractTableModel class and provides four methods called by the JTable code when data is accessed. by the JTable code when data is accessed. • Since the data model is now synthesized, the getValueAt() Since the data model is now synthesized, the getValueAt()

method simply determines the row and column being accessed method simply determines the row and column being accessed and generates a string representing the cell data. and generates a string representing the cell data.

• The getColumnCount() method returns a value of zero, which The getColumnCount() method returns a value of zero, which may not be what you expected. Remember, though, that this may not be what you expected. Remember, though, that this method returns the number of columns managed by the table method returns the number of columns managed by the table code. In the CreateColumns() method in the main code. In the CreateColumns() method in the main CustomDataTableExample class, we informed the table that it CustomDataTableExample class, we informed the table that it should not attempt to generate any of its own columns. As a should not attempt to generate any of its own columns. As a result, the value of getColumnCount() is zero. result, the value of getColumnCount() is zero.

Explore the full listings via the course web siteExplore the full listings via the course web site

Page 12: How to Use Tables

Custom Table RenderingCustom Table Rendering

As in other components can alter the display by As in other components can alter the display by developing custom rendering classes.developing custom rendering classes.

Modify the initial example to implement a custom Modify the initial example to implement a custom rendered JTable: rendered JTable: • implements the custom rendering on top of the modified implements the custom rendering on top of the modified

code from the first examplecode from the first example• Instead of displaying numerical (X, Y) data, the code Instead of displaying numerical (X, Y) data, the code

displays a card deck in tabular form displays a card deck in tabular form • Each column represents a suit in the deck, with each cell Each column represents a suit in the deck, with each cell

drawn as a graphical suit and a card number.drawn as a graphical suit and a card number.

Page 13: How to Use Tables

CustomRenderTableExampleCustomRenderTableExample• contains the code for the main frame of the application. The only contains the code for the main frame of the application. The only

significant notable in this file is the call the JTable's significant notable in this file is the call the JTable's setCellRenderer() method, which informs the table object that all setCellRenderer() method, which informs the table object that all of its drawing will be handled by an external rendering class. of its drawing will be handled by an external rendering class.

CustomCellRendererCustomCellRenderer• contains the code for the custom table cell renderer, contains the code for the custom table cell renderer,

implementing a method named implementing a method named getTableCellRendererComponent() to handle the drawing of getTableCellRendererComponent() to handle the drawing of individual cells. This method determines if the item it is drawing individual cells. This method determines if the item it is drawing is selected or has the focus, and uses this information to control is selected or has the focus, and uses this information to control the foreground colour. Because of the restrictions with regards to the foreground colour. Because of the restrictions with regards to painting the background colour, this class also provides a paint() painting the background colour, this class also provides a paint() method, which uses the selection and focus flags as well. method, which uses the selection and focus flags as well.

CustomDataModelCustomDataModel• includes a custom data model, which is similar to previous includes a custom data model, which is similar to previous

examples. The only difference is in the number of rows in the examples. The only difference is in the number of rows in the modelmodel

Page 14: How to Use Tables
Page 15: How to Use Tables

Listening for Table ActionsListening for Table Actions

Many situations demand that the Many situations demand that the application immediately detect changes application immediately detect changes initiated by the user. initiated by the user.

These events can be sorted into two basic These events can be sorted into two basic categories: categories: • cell selections made by the user, and cell selections made by the user, and • user-invoked changes to the table itself. user-invoked changes to the table itself.

Page 16: How to Use Tables

Detecting Table SelectionsDetecting Table Selections

The type of action usually involves a mouse click The type of action usually involves a mouse click to select a single cell or a drag operation to select to select a single cell or a drag operation to select a range of values from the table. a range of values from the table.

JTable implements selection listeners in exactly JTable implements selection listeners in exactly the same way as the JList -- the same way as the JList -- ListSelectionListenerListSelectionListener . .

To enable selection events, the code adds a To enable selection events, the code adds a ListSelectionListener to the table's selection ListSelectionListener to the table's selection model. model.

valueChanged()valueChanged() method is required in order to method is required in order to implement ListSelectionListener. implement ListSelectionListener.

Page 17: How to Use Tables

public void valueChanged( ListSelectionEvent event ) { // See if this is a valid table selection

if( event.getSource() == table.getSelectionModel()&& event.getFirstIndex() >= 0 )

{// Get the data model for this tableTableModel model = (TableModel)table.getModel();

 // Determine the selected itemString string = (String)model.getValueAt(

table.getSelectedRow(), table.getSelectedColumn() );

 // Display the selected itemSystem.out.println( "Value selected = " + string );

} }

this method first determines if the event originates from our JTable this method first determines if the event originates from our JTable instance's selection model, and then it ensures that the event instance's selection model, and then it ensures that the event references a valid selection. To access the selected cell, the code references a valid selection. To access the selected cell, the code references the table's data model and simply extracts the data references the table's data model and simply extracts the data based on the selected row and column. based on the selected row and column.

Page 18: How to Use Tables

Detecting Column Property ChangesDetecting Column Property Changes

Second significant series of events produced by table Second significant series of events produced by table activity relate to manipulations of the column presentation: activity relate to manipulations of the column presentation:

Any time the user moves a column from one place to Any time the user moves a column from one place to another, or adds a new column, the table generates an another, or adds a new column, the table generates an event -- a column model change event. event -- a column model change event.

To intercept these events, a listener must be associated To intercept these events, a listener must be associated with the table's column model. This is done using the with the table's column model. This is done using the following code: following code: • // Handle the listener // Handle the listener

DefaultTableColumnModel columnModel = DefaultTableColumnModel columnModel = (DefaultTableColumnModel)table.getColumnModel(); (DefaultTableColumnModel)table.getColumnModel(); columnModel.addColumnModelListener( this ); columnModel.addColumnModelListener( this );

Page 19: How to Use Tables

TableColumnModelListener Interface TableColumnModelListener Interface Methods called Methods called whenever the column model changes whenever the column model changes

public void columnAdded( TableColumnModelEvent event ) public void columnAdded( TableColumnModelEvent event ) public void columnRemoved( TableColumnModelEvent event ) public void columnRemoved( TableColumnModelEvent event ) public void columnMoved( TableColumnModelEvent event ) public void columnMoved( TableColumnModelEvent event ) public void columnMarginChanged( ChangeEvent event ) public void columnMarginChanged( ChangeEvent event ) public void columnSelectionChanged( ListSelectionEvent event )public void columnSelectionChanged( ListSelectionEvent event )

constants used as flags to control the resize state of columns in constants used as flags to control the resize state of columns in the table. These constants are used as parameters to the the table. These constants are used as parameters to the setAutoResizeModesetAutoResizeMode() method. () method.

public static final int AUTO_RESIZE_LAST_COLUMN public static final int AUTO_RESIZE_LAST_COLUMN public static final int AUTO_RESIZE_OFF public static final int AUTO_RESIZE_OFF public static final int AUTO_RESIZE_ALL_COLUMNSpublic static final int AUTO_RESIZE_ALL_COLUMNS

Page 20: How to Use Tables

Key VariablesKey Variables The following variables hold instances of the various models The following variables hold instances of the various models

associated with a JTable object: associated with a JTable object: • protected TableModel dataModel protected TableModel dataModel

protected TableColumnModel columnModel protected TableColumnModel columnModel protected ListSelectionModel selectionModelprotected ListSelectionModel selectionModel

The The protected JTableHeader tableHeaderprotected JTableHeader tableHeader variable holds the variable holds the instance of the table headers for this JTable object. The instance of the table headers for this JTable object. The header holds particulars, such as, the column object. header holds particulars, such as, the column object.

The following variables contain information to manage the The following variables contain information to manage the attributes of a table row: attributes of a table row: • protected int rowHeight protected int rowHeight

protected int rowMargin protected int rowMargin The colour of the grid lines drawn in the table is stored in The colour of the grid lines drawn in the table is stored in

the the protected Color gridColorprotected Color gridColor variable. variable.

Page 21: How to Use Tables

More key variablesMore key variables The following boolean flags contain information about the The following boolean flags contain information about the

states of particular modes within the JTable object: states of particular modes within the JTable object: • protected boolean showHorizontalLines protected boolean showHorizontalLines

protected boolean showVerticalLines protected boolean showVerticalLines protected boolean autoCreateColumnsFromModel protected boolean autoCreateColumnsFromModel protected boolean rowSelectionAllowed protected boolean rowSelectionAllowed

The value of the protected The value of the protected int autoResizeModeint autoResizeMode variable variable determines if the table object automatically resizes the width determines if the table object automatically resizes the width the columns to occupy the entire width of the table. It is also the columns to occupy the entire width of the table. It is also used to decide how the resizing is done. used to decide how the resizing is done.

The The protected Dimension preferredViewportSizeprotected Dimension preferredViewportSize variable is variable is used by the scrolling pane instance associated with the table used by the scrolling pane instance associated with the table object. It determines the initial visible area for the table. object. It determines the initial visible area for the table.

When the table is performing a cell editing operation, the When the table is performing a cell editing operation, the protected transient Component editorCompprotected transient Component editorComp variable holds an variable holds an instance of the component used to handle the editing instance of the component used to handle the editing operation. operation.

Page 22: How to Use Tables

JTable variablesJTable variables The protected transient TableCellEditor cellEditor variable The protected transient TableCellEditor cellEditor variable

holds an instance of the cell editor used by this table holds an instance of the cell editor used by this table object. object.

When editing table cells, the following variables contain the When editing table cells, the following variables contain the row and column address of the cell being edited. row and column address of the cell being edited. • protected transient int editingRow protected transient int editingRow

protected transient int editingColumn protected transient int editingColumn The following variables are used to keep track of the default The following variables are used to keep track of the default

cell editors and renderers known to this table object: cell editors and renderers known to this table object: • protected Hashtable defaultRenderersByColumnClass protected Hashtable defaultRenderersByColumnClass

protected Hashtable defaultEditorsByColumnClass protected Hashtable defaultEditorsByColumnClass These variables contain the colours of the foreground and These variables contain the colours of the foreground and

background used to draw selected text. These values are background used to draw selected text. These values are overridden by any custom cell render code: overridden by any custom cell render code: • protected Color selectionForeground protected Color selectionForeground

protected Color selectionBackgroundprotected Color selectionBackground

Page 23: How to Use Tables

SummarySummary

Presented an Overview of JTree Presented an Overview of JTree Should read these notes alongside the example Should read these notes alongside the example

code available on the web sitecode available on the web site• Down run compile and run the code Down run compile and run the code

Supplement by looking at the Sun tutorials on Supplement by looking at the Sun tutorials on Jtree (be award of the1.6 dependency)Jtree (be award of the1.6 dependency)

NextNext• Consider how the different components can best be put Consider how the different components can best be put

together by looking at the graphical design and interface together by looking at the graphical design and interface principlesprinciples


Recommended