Java UI-komponentit (JTable) Juha Järvensivu juha.jarvensivu@tut.fi 2008
Action Action
public class ActionDemo extends JPanel { protected Action firstaction; protected JMenuItem item; protected JButton btn; Action 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äintapahtumat Voidaan 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äytyy ikkunassa JPanel pane = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); pane.add(thecomponent, c);
GridBagConstraints public 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 1 public static final int CENTER 10 public static final int EAST 13 public static final int FIRST_LINE_END 24 public static final int FIRST_LINE_START 23 public static final int HORIZONTAL 2 public static final int LAST_LINE_END 26 public static final int LAST_LINE_START 25 public static final int LINE_END 22 public static final int LINE_START 21 public static final int NONE 0 public static final int NORTH 11 public static final int NORTHEAST 12 public static final int NORTHWEST 18 public static final int PAGE_END 20 public static final int PAGE_START19 public static final int RELATIVE -1 public static final int REMAINDER 0 public static final int SOUTH 15 public static final int SOUTHEAST 14 public static final int SOUTHWEST 16 public static final int VERTICAL 3 public 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)
JTable String[] 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 header public 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ääminen public 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 muuttaminen import 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 kuten listakomponentilla (JList) Oletuksena usean rivin valitseminen samaan aikaan mahdollista
Datan valitseminen table.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 Monipuolisempi toteutus? Oman Table modelin luonti
Taulukon luominen JTable() 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 column model, 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 column model, 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 column model, 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 Model TableModel View JTable
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 muuttui firetablecellupdated(row, col); }
JTable TableModel TableModelListener JTable ListSelectionModel SelectionListener TableColumn TableColumnModel ColumnModelListener
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 TableModel TableModelListener JTable ListSelectionModel SelectionListener TableColumn TableColumnModel ColumnModelListener TableCellRenderer TableCellEditor
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
TableCellRenderer Component gettablecellrenderercomponent( JTable table, Object value, boolean isselected, boolean hasfocus, int row, int column)
DefaultCellEditor DefaultCellEditor(JCheckBox checkbox) DefaultCellEditor(JComboBox combobox DefaultCellEditor(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 CellEditorrajapinnan
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)
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