Professional Documents
Culture Documents
La Classe JTable
La Classe JTable
Institut Almat
Hem afegit un MouseAdapter per no tenir que implementar tots els mtodes de la interfcie.
Amb el mtode taula.rowAtPoint() s possible obtenir la fila del JTable on sha produt el
succs del ratol (prmer el ratol en aquest cas). Aix doncs, s suficient cridar aquest mtode
passant-li les coordenades x,y des succs del ratol, que sobt amb el mtode e.getPoint().
Material d APM.
Pgina 1 de 21
Institut Almat
Un cop sabem la fila, hem de comprovar si s major que -1. El mtode rowAtPoint() ens
retorna -1 si hem premut en el JTable, per fora de qualsevol fila. s el cas que el JTable tingui
un tamany en pxels superior al que correspon segons el seu nombre de files.
El mateix raonament serveis per a les columnes amb columnAtPoint().
Un cop hem obtingut la fila i sabem que no s -1, s fcil obtenir les dades corresponents a
travs del model. En aquest cas escriu per pantalla el valor de la fila i la columna
seleccionada.
Podeu observar que hem creat el nostre propi model de dades que fa que la columna 4
(Recordeu que els ndexs sinicien a la posici 0) de la taula sigui editable i la resta no. Ara
noms ens cal instanciar el JTable utilitzant aquest model i utilitzar-lo com abans.
MeuModel model = new MeuModel();
JTable taula = new JTable(model);
Pgina 2 de 21
Institut Almat
En aquest cas la primera columna ser boolean, la segona Integer i la resta Object.
Nota: Si fem una columna de tipus Boolean, el JTable el pintar com un JCheckBox.
o tamb:
JTable taula = new JTable();
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(taula);
Material d APM.
Pgina 3 de 21
Institut Almat
Material d APM.
Pgina 4 de 21
Institut Almat
Les Metadades.
Podem automatitzar el procs domplir un JTable amb un resultSet utilitzant la
informaci que ens faciliten les MetaDades dun ResultSet. El codi per obtenir aquestes
metadades seria:
ResultSetMetaData metaDades = rs.getMetaData();
Un cop tenim larray detiquetes hem de fer una crida al DefaultTableMode per
configurar el nombre de columnes. El codi seria:
model.setColumnIdentifiers(etiquetes);
Queda per lalumne el codi genric per omplir de forma automtica un JTable a partir
dun ResultSet qualsevol.
Material d APM.
Pgina 5 de 21
Institut Almat
JTABLE.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
Amb el JTable es pot visualitzar taules de dades i opcionalment editar-les. La segent
imatge mostra un exemple de JTable amb scroll pane:
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.JScrollPane;
javax.swing.JTable;
java.awt.Dimension;
java.awt.GridLayout;
java.awt.event.MouseAdapter;
java.awt.event.MouseEvent;
Material d APM.
Pgina 6 de 21
Institut Almat
Les dades de la taula les hem obtingut amb una taula de dues dimensions, on els
seus elements sn de tipus Object:
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)}
};
Material d APM.
Pgina 7 de 21
Institut Almat
Material d APM.
Pgina 8 de 21
Institut Almat
Utilitzar seleccions.
Per defecte podem seleccionar una o ms files. Podem ser contiges o no. La darrera
cella que indica lusuari t una indicaci visual especial; la cella t el focus.
La segent taula mostra les possibles opcions:
Mouse
Operation
Keyboard Action
Action
Select single row.
Click.
Up Arrow or Down Arrow.
Extend contiguous
selection.
Shift-Click or
Drag over
Shift-Up Arrow or Shift-Down Arrow.
rows.
Add row to
selection/toggle row
selection.
Material d APM.
Pgina 9 de 21
Institut Almat
javax.swing.*;
javax.swing.table.AbstractTableModel;
javax.swing.event.ListSelectionEvent;
javax.swing.event.ListSelectionListener;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.GridLayout;
java.awt.Dimension;
Material d APM.
Pgina 10 de 21
}
}
Institut Almat
if (!cellCheck.isEnabled()) {
table.setColumnSelectionAllowed(!rowCheck.isSelected());
}
else if ("Column Selection" == command) {
table.setColumnSelectionAllowed(columnCheck.isSelected());
//In MIS mode, row selection allowed must be the
//opposite of column selection allowed.
if (!cellCheck.isEnabled()) {
table.setRowSelectionAllowed(!columnCheck.isSelected());
}
else if ("Cell Selection" == command) {
table.setCellSelectionEnabled(cellCheck.isSelected());
else if ("Multiple Interval Selection" == command) {
table.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//If cell selection is on, turn it off.
if (cellCheck.isSelected()) {
cellCheck.setSelected(false);
table.setCellSelectionEnabled(false);
}
//And don't let it be turned back on.
cellCheck.setEnabled(false);
else if ("Single Interval Selection" == command) {
table.setSelectionMode(
ListSelectionModel.SINGLE_INTERVAL_SELECTION);
//Cell selection is ok in this mode.
cellCheck.setEnabled(true);
else if ("Single Selection" == command) {
table.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
//Cell selection is ok in this mode.
cellCheck.setEnabled(true);
}
//Update checkboxes to reflect selection mode side effects.
rowCheck.setSelected(table.getRowSelectionAllowed());
columnCheck.setSelected(table.getColumnSelectionAllowed());
if (cellCheck.isEnabled()) {
cellCheck.setSelected(table.getCellSelectionEnabled());
}
}
private void outputSelection() {
output.append(String.format("Lead: %d, %d. ",
table.getSelectionModel().getLeadSelectionIndex(),
table.getColumnModel().getSelectionModel().
getLeadSelectionIndex()));
output.append("Rows:");
for (int c : table.getSelectedRows()) {
output.append(String.format(" %d", c));
}
output.append(". Columns:");
for (int c : table.getSelectedColumns()) {
output.append(String.format(" %d", c));
}
output.append(".\n");
}
private class RowListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
output.append("ROW SELECTION EVENT. ");
outputSelection();
}
}
private class ColumnListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
output.append("COLUMN SELECTION EVENT. ");
outputSelection();
Material d APM.
Pgina 11 de 21
Institut Almat
}
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private 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)}
};
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];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
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);
}
}
/**
* Create the GUI and show it.
Material d APM.
Pgina 12 de 21
Institut Almat
La tercera fila i tercera columna t el focus. Podem triar el tipus de selecci que volem fer. Si
triem single selection noms podem fer seleccions duna sola fila. Si triem Single Interval
Selection podem fer seleccions de varies files contiges. Laltra opci permet fer selecci
mltiple i en files no contiges.
Material d APM.
Pgina 13 de 21
Institut Almat
Permetre la selecci per fila, per columna o per cella cal fer-ho utilitzant:
void setRowSelectionAllowed( boolean )
boolean getRowSelectionAllowed()
void setColumnSelectionAllowed( boolean )
boolean getColumnSelectionAllowed()
void setCellSelectionEnabled( boolean )
boolean getCellSelectionEnabled()
Crear un TableModel
Tots els objectes JTable utilitzen un objecte Table Model per gestionar les dades. Un table
model ha dimplementar la interfcie TableModel. Si el programador no facilita un objecte
table model, JTable automticament crea una instncia de DefaultTableModel. La relaci
entre aquests objectes s la segent:
Material d APM.
Pgina 14 de 21
Institut Almat
Material d APM.
Pgina 15 de 21
Institut Almat
Change
fireTableCellUpdated
fireTableRowsUpdated
fireTableDataChanged
fireTableRowsInserted
fireTableRowsDeleted
fireTableStructureChanged
Material d APM.
Pgina 16 de 21
Institut Almat
To detect row/column/cell
Use a selection listener as described in Detecting User
selections and deselections... Selections.
To detect mouse events on a
column header...
Exemple:
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;
}
}
Material d APM.
Pgina 17 de 21
Institut Almat
Ordernar I filtrar
Per ordenar i filtrar en una taula s gestiona amb un objecte sorter. La forma ms fcil
de fer-ho s utilitzant la propietat setAutoCreateRowSorter(true).
Exemple:
JTable table = new JTable();
table.setAutoCreateRowSorter(true);
Material d APM.
Pgina 18 de 21
Institut Almat
import
import
import
import
import
java.awt.Component;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
import
import
import
import
import
import
import
import
import
import
javax.swing.DefaultCellEditor;
javax.swing.JButton;
javax.swing.JCheckBox;
javax.swing.JFrame;
javax.swing.JOptionPane;
javax.swing.JScrollPane;
javax.swing.JTable;
javax.swing.UIManager;
javax.swing.table.DefaultTableModel;
javax.swing.table.TableCellRenderer;
/**
* @version 1.0 11/09/98
*/
public class JButtonTableExample extends JFrame {
public JButtonTableExample() {
super("JButtonTable Example");
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][] { { "button 1", "foo" },
{ "button 2", "bar" } }, new Object[] { "Button", "String" });
JTable table = new JTable(dm);
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor(
new ButtonEditor(new JCheckBox()));
JScrollPane scroll = new JScrollPane(table);
Material d APM.
Pgina 19 de 21
Institut Almat
getContentPane().add(scroll);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
JButtonTableExample frame = new JButtonTableExample();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
/**
* @version 1.0 11/09/98
*/
class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
setText((value == null) ? "" : value.toString());
return this;
}
}
/**
* @version 1.0 11/09/98
*/
class ButtonEditor extends DefaultCellEditor {
protected JButton button;
private String label;
private boolean isPushed;
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
Material d APM.
Pgina 20 de 21
Institut Almat
});
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else {
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
label = (value == null) ? "" : value.toString();
button.setText(label);
isPushed = true;
return button;
}
public Object getCellEditorValue() {
if (isPushed) {
//
//
JOptionPane.showMessageDialog(button, label + ": Ouch!");
// System.out.println(label + ": Ouch!");
}
isPushed = false;
return new String(label);
}
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
Material d APM.
Pgina 21 de 21