Java UI-komponentit (JTable)grako/2008/luennot/java_ui_komponentti...int gridx, int gridy, int...

Post on 06-Aug-2020

29 views 0 download

Transcript of Java UI-komponentit (JTable)grako/2008/luennot/java_ui_komponentti...int gridx, int gridy, int...

Java UI-komponentit (JTable)

Juha Järvensivujuha.jarvensivu@tut.fi

2008

Action

Action

Actionpublic class ActionDemo extends JPanel {

protected Action firstAction;protected JMenuItem item;protected JButton btn;

public ActionDemo() {firstAction = new FirstAction(”Toiminnon nimi”, icon);

item = new JMenuItem();item.setAction(firstAction);

btn = new JButton();btn.setAction(firstAction);

}

public class FirstAction extends AbstractAction {

public void actionPerformed(ActionEvent e) {setEnabled(false);

}}

NäppäintapahtumatVoidaan toteuttaa Action-olioiden sekä InputMap ja ActionMap luokkien avulla

public class ActionDemo extends JPanel {

public ActionDemo() {InputMap im = getInputMap();ActionMap am = getActionMap();

KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_1,0);im.put(ks, “1");

am.put( new KeyAction(), “1");}

public class KeyAction extends AbstractAction {public void actionPerformed(ActionEvent e) {

// Näppäinkäsittelijän toteutus tänne…}

}

GridBagLayout

JPanel

public void add(Component comp,Object constraints, int index) ;

GridBagLayout GridBagContraints

GridBagContraints

• Määrittelee miten komponentti käyttäytyyikkunassa

JPanel pane = new JPanel(new GridBagLayout());GridBagConstraints c = new GridBagConstraints();

pane.add(theComponent, c);

GridBagConstraintspublic GridBagConstraints(int gridx,int gridy,int gridwidth,int gridheight,double weightx,double weighty,int anchor,int fill,Insets insets,int ipadx,int ipady)

public static final int BOTH 1public static final int CENTER 10public static final int EAST 13public static final int FIRST_LINE_END 24public static final int FIRST_LINE_START 23public static final int HORIZONTAL 2public static final int LAST_LINE_END 26public static final int LAST_LINE_START 25public static final int LINE_END 22public static final int LINE_START 21public static final int NONE 0public static final int NORTH 11public static final int NORTHEAST 12public static final int NORTHWEST 18public static final int PAGE_END 20public static final int PAGE_START19public static final int RELATIVE -1public static final int REMAINDER 0public static final int SOUTH 15public static final int SOUTHEAST 14public static final int SOUTHWEST 16public static final int VERTICAL 3public static final int WEST 17

GridBagConstraints

• int gridx, gridy– Kertoo mihin soluun komponentti sijoitetaan

• int gridWidth, gridHeight– Kertoo kuinka monta solua komponentille

varataan tilaa

GridBagConstraints

• Anchor– Asettaa komponentin sijainnin, jos

komponentti on pienempi kuin sille varattu tila

Button 1

GridBagConstraints

• Fill– Kertoo muutetaanko komponentin kokoa, jos

komponentti eri kokoinen kuin sille varattu tila– NONE– HORIZONTAL– VERTICAL– BOTH

Button 1

Button 1

Button 1

GridBagContraints

• ipadx, ipady– Kertoo kuinka paljon ylimääräistä tilaa

komponentille varataan– minimikoko = comp.minimumWidth+ipadx

• insets– Kertoo kuinka paljon ylimääräistä tilaa

komponentin ympärille varataan– Insets(int top, int left, int bottom, int right)

GridBagConstraints

• weightx, weighty– Arvo normaalisti välillä 0.0 – 1.0– Kertoo miten käytettävissä oleva tila jaetaan

komponenttien kesken

Button 1 (weighty = 0.33)

Button 2 (weighty = 0.66)

UI-komponentit (JTable)

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

JTable

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); }

}

Table header

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);

}

Vierityspalkkien lisääminen

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);}

}

Sarakeleveyden muuttaminen

Datan valitseminen

• Oletuksena alkioiden valinta toimii kutenlistakomponentilla (JList)

• Oletuksena usean rivin valitseminensamaan 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

• 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 defaultcolumn model, and a default selection model.

JTable(int numRows, int numColumns)Constructs a JTable with numRows and numColumns of empty cells usingDefaultTableModel.

JTable(Object[][] rowData, Object[] columnNames)Constructs a JTable to display the values in the two dimensional array, rowData, withcolumn 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, withcolumn names, columnNames.

TableModel

ViewJTable

ModelTableModel

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 useimmilleTableModel-rajapinnan funktioille

• Itse pitää toteuttaa ainoastaan– public int getRowCount();– public int getColumnCount();– public Object getValueAt(int row, int column);

DefaultTableModel

• Kirjaston tarjoama oletustoteutusTableModel-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äändatan 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));

DefaultCellEditor

CellEditor (interface)– Void addCellEditorListener(CellEditorListener l)– Void cancelCellEditing()– Object getCellEditorValue()– Boolean isCellEditable(EventObject anEvent)– Void removeCellEditorListener(CellEditorListener l)– Boolean shouldSelectCell(EventObject anEvent)– Boolean stopCellEditing()

AbstractCellEditor

• implements CellEditor• Abstrakti luokka, joka toteuttaa CellEditor-

rajapinnan

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 voijakaa saman datamallin (esim lista jataulukko-komponentit voivat näyttääsamaa dataa saman DataModelin kautta)

Lähteitä

• JTable– http://java.sun.com/j2se/1.5.0/docs/api/javax/s

wing/JTable.html– http://java.sun.com/docs/books/tutorial/uiswin

g/components/table.html