Apr 10, 2018
JTable
• Datan esittäminen taulukkomuodossa• Datan valitseminen taulukosta• Datan muokkaaminen (lisääminen,
muokkaaminen, poistaminen)
JTableString[] columnNames = {"First Name", "Last Name", "Sport", "# of Years“,
"Vegetarian"};
Object[][] data = {{"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)},{"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},{"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)},{"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)},{"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}};
JTable table = new JTable(data, columnNames);add(table); // Add table to JPanel
Taulukon ominaisuuksia…
• Taulukon käyttö yksinkertaista• Kaikki solut saman tyyppisiä (string)• Solut automaattisesti editoitavissa• Sarakkeiden otsikko ei oletuksena
näkyvissä
Table headerpublic class TableDemo extends JPanel {
public TableDemo() {super(new BorderLayout());String[] columnNames = {…};Object[][] data = {…};JTable table = new JTable(data, columnNames);
add(table.getTableHeader(), BorderLayout.PAGE_START); add(table, BorderLayout.CENTER); }
}
Vierityspalkkien lisääminenpublic class TableDemo extends JPanel {
public TableDemo() {String[] columnNames = {…};Object[][] data = {…};JTable table = new JTable(data, columnNames);
JScrollPane spane = new JScrollPane(table);table.setPreferredScrollableViewportSize(new Dimension(500, 70));add(spane,BorderLayout.CENTER);
}
Sarakeleveyden muuttaminenimport javax.swing.table.*;
…..
TableColumn column = null; for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i); if (i == 2) {
column.setPreferredWidth(200); //sport column is bigger } else {
column.setPreferredWidth(50); }
}
Datan valitseminen
• Oletuksena alkioiden valinta toimii kuten listakomponentilla (JList)
• Oletuksena usean rivin valitseminen samaan aikaan mahdollista
Datan valitseminentable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Ask to be notified of selection changes. ListSelectionModel rowSM = table.getSelectionModel();rowSM.addListSelectionListener(new MyListSelectionListener());
class MyListSelectionModel implements ListSelectionListener{
public void valueChanged(ListSelectionEvent e) {ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (lsm.isSelectionEmpty()) {
...//no rows are selected} else {
int selectedRow = lsm.getMinSelectionIndex();...//selectedRow is selected
} }
}
Taulukon ominaisuuksia
• Taulukon käyttö yksinkertaista• Solut automaattisesti editoitavissa• Kaikki solut saman tyyppisiä (string)• Data joudutaan kopioimaan taulukkoon tai
vektoriin
Oman Table modelin luontiMonipuolisempi toteutus?
Taulukon luominenJTable()
Constructs a default JTable that is initialized with a default data model, a default column model, and a default selection model.
JTable(int numRows, int numColumns) Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel.
JTable(Object[][] rowData, Object[] columnNames) Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames.
JTable(TableModel dm) Constructs a JTable that is initialized with dm as the data model, a default columnmodel, and a default selection model.
JTable(TableModel dm, TableColumnModel cm) Constructs a JTable that is initialized with dm as the data model, cm as the columnmodel, and a default selection model.
JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) Constructs a JTable that is initialized with dm as the data model, cm as the columnmodel, and sm as the selection model.
JTable(Vector rowData, Vector columnNames) Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames.
TableModel (interface)Void addTableModelListener(TableModelListener l)Class getColumnClass(int columnIndex) Int getColumnCount()String getColumnName(int columnIndex) Int getRowCount() Object getValueAt(int rowIndex, int columnIndex)Boolean isCellEditable(int rowIndex, int columnIndex)Void removeTableModelListener(TableModelListener l)Void setValueAt(Object aValue, int rowIndex, int columnIndex)
TableModel myData = new MyTableModel(); JTable table = new JTable(myData);
AbstractTableModel
• Antaa oletustoteutuksen useimmille TableModel-rajapinnan funktioille
• Itse pitää toteuttaa ainoastaan– public int getRowCount(); – public int getColumnCount(); – public Object getValueAt(int row, int column);
DefaultTableModel
• Kirjaston tarjoama oletustoteutus TableModel-rajapinnalle
• Käyttää vektoreita datan tallentamiseen
MyDataModel (1/2)class MyTableModel extends AbstractTableModel{
private String[] columnNames = …private Object[][] data = ...
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(); }
}
MyDataModel (2/2)class MyTableModel extends AbstractTableModel{
// Kertoo onko taulukon solu editoitavissa. public boolean isCellEditable(int row, int col) {
if (col < 2) { return false; } else { return true; }
}
// Tarvitaan, jos solun arvoa halutaan muuttaa. public void setValueAt(Object value, int row, int col) {
data[row][col] = value; // Kerrotaan taulukolle, että solun arvo muuttuifireTableCellUpdated(row, col);
} }
JTable
SelectionListener
ColumnModelListener
TableModelListenerTableModel
TableColumnModel
ListSelectionModelJTable
TableColumn
Kuuntelijoita
• ListSelectionListener– Tarkkailee alkioiden valintaa– valueChanged(ListSelectionEvent e);
• TableModelListener– Tarkkailee TableModelin muutoksia– tableChanged(TableModelEvent e);
Kuuntelijoita• TableColumnModelListener
– Tarkkailee TableColumnModelin muutoksia– columnAdded– columnMariginChanged– columnMoved– columnRemoved
• CellEditorListener– Kuuntelee CellEditorin muutoksia– editingCanceled– editingStopped
JTable
SelectionListener
ColumnModelListener
TableModelListenerTableModel
TableColumnModel
ListSelectionModel
TableCellRenderer
JTable
TableCellEditor
TableColumn
CellRenderer & CellEditor
• CellRenderer– Määrittelee mitä komponenttia käytetään
datan näyttämiseen• CellEditor
– Määrittelee mitä komponenttia käytetään datan muokkaamiseen
DefaultTableCellRenderer
• Boolean - CheckBox• Number - Right aligned label• Double - Label + NumberFormat• Date - Label + DateFormat• ImageIcon - Centered Label• Object - label
TableCellRendererComponent getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
DefaultCellEditor
DefaultCellEditor(JCheckBox checkBox)DefaultCellEditor(JComboBox comboBoxDefaultCellEditor(JTextField textField)
TableColumn sportColumn = table.getColumnModel().getColumn(2); JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");….
comboBox.addItem("None");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
CellEditor (interface)– Void addCellEditorListener(CellEditorListener l)– Void cancelCellEditing() – Object getCellEditorValue()– Boolean isCellEditable(EventObject anEvent)– Void removeCellEditorListener(CellEditorListener l)– Boolean shouldSelectCell(EventObject anEvent)– Boolean stopCellEditing()
TableCellEditor (interface)
• extends AbstractCellEditor
Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
Työkaluvihjeet//Set up tool tips for the sport cells. DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();renderer.setToolTipText("Click for combo box");sportColumn.setCellRenderer(renderer);
Shared model
• Kaksi tai useampi UI-komponentti voi jakaa saman datamallin (esim lista ja taulukko-komponentit voivat näyttääsamaa dataa saman DataModelin kautta)