0% acharam este documento útil (0 voto)
43 visualizações

Class DefaultTableModel

Este documento fornece uma visão geral da classe DefaultTableModel em Java, que implementa o TableModel usando um vetor de vetores para armazenar os dados da tabela. Ele descreve os campos protegidos dataVector e columnIdentifiers, vários construtores para inicializar o modelo de dados, e métodos para adicionar, remover e editar linhas e colunas.

Enviado por

Xavier Joaquim
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
43 visualizações

Class DefaultTableModel

Este documento fornece uma visão geral da classe DefaultTableModel em Java, que implementa o TableModel usando um vetor de vetores para armazenar os dados da tabela. Ele descreve os campos protegidos dataVector e columnIdentifiers, vários construtores para inicializar o modelo de dados, e métodos para adicionar, remover e editar linhas e colunas.

Enviado por

Xavier Joaquim
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
Você está na página 1/ 12

Visão geral 

Pacote   Aula  Usar  Árvore  Descontinuada  Índice  Ajuda  Plataforma Java 1.2
Beta 4
 AULA ANTERIOR AULA    PRÓXIMA QUADROS   SEM QUADROS

RESUMO: INTERIOR | CAMPO  | CONSTR  | MÉTODO DETALHE:   CAMPO  | CONSTR  | MÉTODO

Classe com.sun.java.swing.table.DefaultTableModel
java.lang.Object
|
+-- com.sun.java.swing.table.AbstractTableModel
|
+-- com.sun.java.swing.table.DefaultTableModel

classe pública DefaultTableModel


estende AbstractTableModel
implementa serializável

Esta é uma implementação do TableModel que usa um Vector de Vetores para armazenar os
objetos de valor da célula.

Nota:
A API do DefaultTableModel contém os métodos addColumn(), removeColumn(), mas não
métodos para inserir uma coluna em um índice nem métodos para mover as colunas. Isso
ocorre porque o JTable não exibe as colunas com base na ordem das colunas neste modelo.
Portanto, reorganizá-los aqui não ajuda muito. Consulte os métodos de ordenação de
colunas em TableColumnModel.

Aviso: os objetos serializados desta classe não serão compatíveis com versões futuras do
swing. O suporte de serialização atual é apropriado para armazenamento de curto prazo ou
RMI entre aplicativos Swing1.0. Não será possível carregar objetos Swing1.0 serializados
com versões futuras do Swing. A versão JDK1.2 do Swing será a linha de base de
compatibilidade para a forma serializada dos objetos Swing.

Veja também:
TableModel, getDataVector(), Formulário serializado

Resumo do campo
vetor
columnIdentifiers
protegido
          O vetor de identificadores de coluna
 

vetor
dataVector
protegido
          O vetor de valores de vetor de objeto
 
 
Campos herdados da classe com.sun.java.swing.table. AbstractTableModel
lista de ouvintes
 
Resumo do Construtor
DefaultTableModel ()
          Constrói um DefaultTableModel padrão que é uma tabela de zero colunas e zero
linhas.
DefaultTableModel (int numRows, int numColumns)
          Constrói um DefaultTableModel com numRows e numColumns de valores nulos de
objeto.
DefaultTableModel ( Object [] columnNames, int numRows)
          Constrói um DefaultTableModel com tantas colunas quantas forem os elementos em
columnNames e numRows de valores nulos de objeto.
DefaultTableModel ( Object [][] data, Object [] columnNames)
          Constrói um DefaultTableModel e inicializa a tabela passando dados e columnNames
para o método setDataVector().
DefaultTableModel ( Vector  columnNames, int numRows)
          Constrói um DefaultTableModel com tantas colunas quantas forem os elementos em
columnNames e numRows de valores de objeto nulos .
DefaultTableModel ( Vector  data, Vector  columnNames)
          Constrói um DefaultTableModel e inicializa a tabela passando dados e columnNames
para o método setDataVector().
 
Resumo do método
 vazio addColumn ( Object  columnName, Object [] columnData)
          Adiciona uma coluna ao modelo com o nome columnName .
 vazio addColumn ( Object  columnName, Vector  columnData)
          Adiciona uma coluna ao modelo.
 vazio addColumn ( Object  columnName)
          Adiciona uma coluna ao modelo.
 vazio addRow ( Object [] rowData)
          Adiciona uma linha ao final do modelo.
 vazio addRow ( Vector  rowData)
          Adiciona uma linha ao final do modelo.
vetor
convertToVector ( Object [] anArray)
estático
protegido 
          Retorna um Vector que contém os mesmos objetos que o array

vetor
convertToVector ( Object [][] anArray)
estático
protegido 
          Retorna um Vector de Vetores que contém os mesmos objetos que o array

 int getColumnCount ()
           
 Fragmento getColumnName (coluna int)
           
 Vetor getDataVector ()
          Retorna o Vetor de Vetores que contém os valores dos dados da tabela.
 int getRowCount ()
           
 Objeto getValueAt (int row, int column)
          Retorna um valor de atributo para a célula na linha e na coluna .
 vazio insertRow (int row, Object [] rowData)
          Insere uma linha na linha do modelo.
 vazio insertRow (int row, Vector  rowData)
          Insere uma linha na linha no modelo.
 boleano isCellEditable (int row, int column)
          Retorna verdadeiro se a célula na linha e na coluna for editável.
 vazio moveRow (int startIndex, int endIndex, int toIndex)
          Move uma ou mais linhas começando em startIndex para endIndex no
modelo para o toIndex .
 vazio newDataAvailable ( evento TableModelEvent  )
          Equivalente a fireTableChanged.
 vazio newRowsAdded ( evento TableModelEvent  )
          Este método garantirá que as novas linhas tenham o número correto de
colunas.
 vazio removeRow (int row)
          Remove a linha na linha do modelo.
 vazio rowsRemoved ( evento TableModelEvent  )
          Equivalente a fireTableChanged().
 vazio setColumnIdentifiers ( Object [] newIdentifiers)
          Substitui os identificadores de coluna no modelo.
 vazio setColumnIdentifiers ( Vector  newIdentifiers)
          Substitui os identificadores de coluna no modelo.
 vazio setDataVector ( Object [][] newData, Object [] columnNames)
          Isso substitui o valor na variável de instância dataVector pelos valores na
matriz newData .
 vazio setDataVector ( Vector  newData, Vector  columnNames)
          Substitui a variável de instância dataVector atual pelo novo Vector de
linhas, newData .
 vazio setNumRows (int newSize)
          Define o número de linhas no modelo.
 vazio setValueAt ( Object aValue  , int row, int column)
          Define o valor do objeto para a célula na coluna e na linha .
 
Métodos herdados da classe com.sun.java.swing.table. AbstractTableModel
addTableModelListener , findColumn , fireTableCellUpdated , fireTableChanged ,
fireTableDataChanged , fireTableRowsDeleted , fireTableRowsInserted ,
fireTableRowsUpdated , fireTableStructureChanged , getColumnClass ,
removeTableModelListener
 
Methods inherited from class java.lang.Object
clone , equals , finalize , getClass , hashCode , notify , notifyAll , toString , wait , wait , wait
 

Field Detail
dataVector
protected Vector dataVector

The Vector of Vector of Object values

columnIdentifiers
protected Vector columnIdentifiers

The Vector of column identifiers

Constructor Detail
DefaultTableModel
public DefaultTableModel()

Constructs a default DefaultTableModel which is a table of zero columns and zero


rows.

DefaultTableModel
public DefaultTableModel(int numRows,
int numColumns)

Constructs a DefaultTableModel with numRows and numColumns of null object values.

Parameters:
numRows - The number of rows the table holds
numColumns - The number of columns the table holds
See Also:
#setValueAt()

DefaultTableModel
public DefaultTableModel(Vector columnNames,
int numRows)

Constructs a DefaultTableModel with as many columns as there are elements in


columnNames and numRows of null object values. Each column's name will be taken
from the columnNames vector.

Parameters:
columnNames - Vector containing the names of the new columns. If this null then
the model has no columns
numRows - The number of rows the table holds
See Also:
#setDataVector(), #setValueAt()

DefaultTableModel
public DefaultTableModel(Object[] columnNames,
int numRows)

Constructs a DefaultTableModel with as many columns as there are elements in


columnNames and numRows of null object values. Each column's name will be taken
from the columnNames array.

Parameters:
columnNames - Array containing the names of the new columns. If this null then the
model has no columns
numRows - The number of rows the table holds
See Also:
#setDataVector(), #setValueAt()

DefaultTableModel
public DefaultTableModel(Vector data,
Vector columnNames)

Constructs a DefaultTableModel and initializes the table by passing data and


columnNames to the setDataVector() method.

Parameters:
data - The data of the table
columnNames - Vector containing the names of the new columns.
See Also:
getDataVector(), #setDataVector()

DefaultTableModel
public DefaultTableModel(Object[][] data,
Object[] columnNames)

Constructs a DefaultTableModel and initializes the table by passing data and


columnNames to the setDataVector() method. The first index in the Object[][] is the row
index and the second is the column index.

Parameters:
data - The data of the table
columnNames - The names of the columns.
See Also:
getDataVector(), #setDataVector()

Method Detail
getDataVector
public Vector getDataVector()

This returns the Vector of Vectors that contains the table's data values. The vectors
contained in the outer vector are each a single row of values. In other words, to get to
the cell at row 1, column 5

((Vector)getDataVector().elementAt(1)).elementAt(5);

You can directly alter the returned Vector. You can change the cell values, the number
of rows. If you need to alter the number of columns in the model, you can do so with
addColumn(), removeColumn(), or the setDataVector() methods. Once you have
finished modifying the dataVector, you must inform the model of the new data using
one of the notification methods. The notification methods will generate the
appropriate TableModelListener messages to notify the JTable and any other listeners
of this model.

See Also:
#newDataAvailable(), #newRowsAdded(), #setDataVector()

setDataVector
public void setDataVector(Vector newData,
Vector columnNames)

This replaces the current dataVector instance variable with the new Vector of rows,
newData. columnNames are the names of the new columns. The first name in
columnNames is mapped to column 0 in newData. Each row in newData is adjusted to
match the number of columns in columnNames either by truncating the Vector if it is
too long, or adding null values if it is too short.

Parameters:
newData - The new data vector
columnNames - The names of the columns
See Also:
#newDataAvailable(), getDataVector()

setDataVector
public void setDataVector(Object[][] newData,
Object[] columnNames)

This replaces the value in the dataVector instance variable with the values in the array
newData. The first index in the Object[][] array is the row index and the second is the
column index. columnNames are the names of the new columns.

See Also:
setDataVector(Vector, Vector)

newDataAvailable
public void newDataAvailable(TableModelEvent event)
Equivalent to fireTableChanged.

newRowsAdded
public void newRowsAdded(TableModelEvent event)

This method will make sure the new rows have the correct number of columns. It does
so using the setSize method in Vector which truncates Vectors which are too long, and
appends nulls if they are too short. This method also sends out a tableChanged()
notification message to all the listeners.

See Also:
getDataVector()

rowsRemoved
public void rowsRemoved(TableModelEvent event)

Equivalent to fireTableChanged().

setColumnIdentifiers
public void setColumnIdentifiers(Vector newIdentifiers)

Replaces the column identifiers in the model.

Parameters:
newIdentifiers - Vector of column identifiers. A null means setting the model to
zero columns
See Also:
#setNumRows()

setColumnIdentifiers
public void setColumnIdentifiers(Object[] newIdentifiers)

Replaces the column identifiers in the model. If the number of newIdentifiers is greater
than the current numColumns, new columns are added to the end of each row in the
model. If the number of newIdentifier is less than the current number of columns, all
the extra columns at the end of a row are discarded.

Parameters:
newIdentifiers - Array of column identifiers. A null means setting the model to
zero columns
See Also:
#setNumRows()

setNumRows
public void setNumRows(int newSize)
Sets the number of rows in the model. If the new size is greater than the current size,
new rows are added to the end of the model If the new size is less than the current
size, all rows at index newSize and greater are discarded.

Parameters:
newSize - the new number of rows
See Also:
#setColumnIdentifiers()

addColumn
public void addColumn(Object columnName)

Add a column to the model. The new column will have the idenitifier columnName.
This method will send a tableChanged() notification message to all the listeners. This
method is a cover for addColumn(Object, Vector) which uses null as the data vector.

Parameters:
columnName - the identifier of the column being added
Throws:
IllegalArgumentException - if columnName is null

addColumn
public void addColumn(Object columnName,
Vector columnData)

Add a column to the model. The new column will have the idenitifier columnName.
columnData is the optional Vector of data for the column. If it is null the column is
filled with null values. Otherwise, the new data will be added to model starting with
the first element going to row 0, etc. This method will send a tableChanged()
notification message to all the listeners.

Parameters:
columnName - the identifier of the column being added
columnData - optional data of the column being added
Throws:
IllegalArgumentException - if columnName is null

addColumn
public void addColumn(Object columnName,
Object[] columnData)

Adds a column to the model with name columnName.

See Also:
addColumn(Object, Vector)

addRow
public void addRow(Vector rowData)
Add a row to the end of the model. The new row will contain null values unless
rowData is specified. Notification of the row being added will be generated.

Parameters:
rowData - optional data of the row being added

addRow
public void addRow(Object[] rowData)

Add a row to the end of the model. The new row will contain null values unless
rowData is specified. Notification of the row being added will be generated.

Parameters:
rowData - optional data of the row being added

insertRow
public void insertRow(int row,
Vector rowData)

Insert a row at row in the model. The new row will contain null values unless rowData
is specified. Notification of the row being added will be generated.

Parameters:
row - the row index of the row to be inserted
rowData - optional data of the row being added
Throws:
ArrayIndexOutOfBoundsException - if the row was invalid.

insertRow
public void insertRow(int row,
Object[] rowData)

Insert a row at row in the model. The new row will contain null values unless rowData
is specified. Notification of the row being added will be generated.

Parameters:
row - the row index of the row to be inserted
rowData - optional data of the row being added
Throws:
ArrayIndexOutOfBoundsException - if the row was invalid.

moveRow
public void moveRow(int startIndex,
int endIndex,
int toIndex)

Moves one or more rows starting at startIndex to endIndex in the model to the toIndex.
This method will send a tableChanged() notification message to all the listeners.
Examples of moves:

1. moveRow(1,3,5);

a|B|C|D|e|f|g|h|i|j|k - before a|e|f|B|C|D|g|h|i|j|k - after 2. moveRow(6,7,1);

a|b|c|d|e|f|G|H|i|j|k - before a|G|H|b|c|d|e|f|i|j|k - after

Parameters:
startIndex - the starting row index to be moved
endIndex - the ending row index to be moved
toIndex - the destination of the rows to be moved
Throws:
ArrayIndexOutOfBoundsException - if any of the indices are out of range. Or if
endIndex is less than startIndex.

removeRow
public void removeRow(int row)

Remove the row at row from the model. Notification of the row being removed will be
sent to all the listeners.

Parameters:
row - the row index of the row to be removed
Throws:
ArrayIndexOutOfBoundsException - if the row was invalid.

getRowCount
public int getRowCount()

Returns:
the number of rows in the model.

getColumnCount
public int getColumnCount()

Returns:
the number of columns in the model.

getColumnName
public String getColumnName(int column)

Returns:
a name for this column using the string value of the appropriate member in
columnIdentfiers. If columnIdentfiers is null or does not have and entry for this
index return the default name provided by the superclass.
Overrides:
getColumnName in class AbstractTableModel
isCellEditable
public boolean isCellEditable(int row,
int column)

Returns true if the cell at row and column is editable. Otherwise, the setValueAt() on
the cell will not change the value of that cell.

Parameters:
row - the row whose value is to be looked up
column - the column whose value is to be looked up
Returns:
true if the cell is editable.
Overrides:
isCellEditable in class AbstractTableModel
See Also:
#setValueAt()

getValueAt
public Object getValueAt(int row,
int column)

Returns an attribute value for the cell at row and column.

Parameters:
row - the row whose value is to be looked up
column - the column whose value is to be looked up
Returns:
the value Object at the specified cell
Throws:
ArrayIndexOutOfBoundsException - if an invalid row or column was given.

setValueAt
public void setValueAt(Object aValue,
int row,
int column)

Sets the object value for the cell at column and row. aValue is the new value. This
method will generate a tableChanged() notification.

Parameters:
aValue - the new value. This can be null.
row - the row whose value is to be changed
column - the column whose value is to be changed
Throws:
ArrayIndexOutOfBoundsException - if an invalid row or column was given.
Overrides:
setValueAt in class AbstractTableModel

convertToVector
protected static Vector convertToVector(Object[] anArray)
Returns a Vector that contains the same objects as the array

convertToVector
protected static Vector convertToVector(Object[][] anArray)

Returns a Vector of Vectors that contains the same objects as the array

Overview  Package   Class  Use  Tree  Deprecated  Index  Help  Java Platform 1.2


Beta 4
 PREV CLASS   NEXT CLASS FRAMES   NO FRAMES

SUMMARY:  INNER | FIELD | CONSTR | METHOD DETAIL:  FIELD | CONSTR | METHOD

Submit a bug or feature


Submit comments/suggestions about new javadoc look
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1998 Sun Microsystems, Inc. 901 San Antonio Road,
Palo Alto, California, 94303, U.S.A. All Rights Reserved.
This documentation was generated with a post-Beta4 version of Javadoc.

Você também pode gostar

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy