Soạn thảo bảng

Khi tổ chức dữ liệu dưới dạng bảng, nhiều khi ta muốn hiển thị dữ liệu ờ các cột với nhiều kiểu khác nhau để có nhiều thông tin hơn. Khi ta định nghĩa phương thức Class getColumnClas(int colưmnĩndex) trong mô hình bảng để biết được kiểu cùa cột, thì JTable sẽ cung cấp các kiểu Imagelcon  Kiểu hình ảnh

Boolean                Hộp kiểm tra (Check box)

Object                                      Xâu ký tự (string)

Các ô trong bảng có thề thay đồi màu, trạng thái và thực hiện .cập nhật giống như các nút trên cây mà ta đã tìm hiểu ở phần trước. Giao diện TableCellRenderer có phương thức

public Component getTableCellRendererCơmponent(JTable table,

Object value, boolean isSelected, boolean hasFocus, int row, int aolưm) được cải đặt để cho phép thay đổi màu nền, màu vẽ, các tham sổ của từng ô trong bảng.

Để soạn thảo (thay đổi tham số của ô), mô hình bàng phải chì ra những cột, ô nào được phép thực hiện thông qua phương thức isCellEditable(). Ví dụ

public boolean isCellEditable(ìnt r, int c){

return c == NAME_COLUMN I I c == MOON_COLUMN I I

c == COLOR_COLUMN Il c == GASEOUS_COLUMN;

}

cho phép thay đồi 4 cột tương ứng với các hằng nêu trên.

Ví dụ 4.9. Hây tố chức một bảng mô tả các hành tinh với các dạng biểu diễn thông tin ờ các cột: Planet, Moons, Gaseous, và Color là có thể thay đổi, cập nhật được. Khi chạy chương trình, ta có thể kích vào hộp Combo Box để thay đổi trạng thái được đánh dấu (tích vào hộp Combo Box) hoặc không tương ứng với hành tinh là thể khí hay không. Tương tự, ta có thể kích đúp chuột vào ô ờ cột (Moons), cột tên gọi (Planet) và thay đổi được số vệ tinh, tên gọi của hành tính tương ứng, nhưng không thay đổi được bán kính của nó. Nghĩa là ờ những ô đó ta có thể cập nhật được các giá trị, thay đổi được các trạng thái, v.v. như hình 4.13.

// TableCellR.ender.java

import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*;

public class TableCellRender{

public static void main(String args[]){

JFrame fr = new TableCellRenderFrame(); fr.show();

}

}

/*

Mô hình bảng cho phép xác định các đặc tính của tùng ô, từng cột trong bảng. Trong đó cho phép thay đổi cột tên gọi (NAME_COLUMN), số vệ tinh (MOON_COLUMN), thể khí (GASEOUS_COLUMN) và cột màu (COLOR_COLUMN).

*/

class PlanetTableModel extends AbstractTableModel{

public static final int NAME_COLUMN = 0; public static final int MOON_COLUMN = 2; public static final int GASEOUS_COLUMN = 3; public static final int COLOR_COLUMN = 4;

public Class getColumnClass(int c){ return cells[0][c].getciass();

}

public String getColumnName(int c){ return columnNames[c] ;

}

public int getColumnCount(){ return cells[0].length;

)

public Object getValueAt(int r, int c){ return cells[r][c] Ỉ

)

public void setValueAt(Object aValue, int r, int c){ cells[r][c] = aValue;

}

public int getRowCount(){ return cells.length;

}

// Được phép thay đổi giá trị trong các cột tương ứng

public boolean ísCellEditable(int r, ìnt c){

return c == NAME_COLUMN II c == MOON_COLƯMN I I

c == COLOR_COLUMN I I c == GASEOUS_COLUMN;

}

private Object[] [] cells = í

{“Mercury”, new Double (2440) , new In’teger(O), Boolean.FALSE, Color.yellow},

{“Venus”, new Double(6052), new Integer (0), Boolean.FALSE, Color.yellow},

{“Earth”, new Double{6378), new Integer(1), Boolean.FALSE, Color.blue},

{“Mars”, new Double{3397), new Integer(2), Boolean.FALSE, Color.red},

{“Jupiter”, new Double(71492), new Integer (16), Boolean.TRUE, Color.orange},

{“Saturn”, new Double(60268), new Integer(18), Boolean.TRUE, Color.orange},

{“Uranus”, new Double(25558), new Integer (17), Boolean.TRUE, Color„blue},

{“Neptune”, new Double(24766), new Integer(8), Boolean.TRUE, Color.blue},

{“Pluto”, new Double(1137), new Integer (1),

Boolean.FALSE, Color.black}

‘ } ;

private string[] columnNames = {

“Planet”, “Radius”, “Moons”, “Gaseous”, “Color”

};

}

class TableCellRenderFrame extends JFrame

{

public TableCellRenderFrame(){

setTitle ( “Table Cell Rendering”); setsize(300, 200);

addWindowListener(new WindowAdapter (){

public void windowclosing(WindowEvent e){ System.exit(0) ;

}

}) ;

TableModel model = new PlanetTableModel();

JTable table ~ new JTable(model);

// Thạy đổi màu và cho phép soạn thảo, thay đổi các giá trị trong các ô đưcrc phép

table. setEefaultRencferer (Color. class, new GolorTahleGelIRerdererO); table.setDefaultPenderer(Cblor.class, nsrf ColorTableCellEditor ());

JComboBox moonCombo = new JComboBox(); for(int 1=0; i <= 20; i++)

moonCombo.addltern(new Integer(i)); TableColumnlfodel columnModel = table.getColumnModel();

TableColumn moonColumn

= columnModel. getColumn (PlanetTableModel. MOON_COLUMN); // Hiển thị bảng sau khi thay đổi table.setRowHeight(100);

Container content = getContentPane(); content.add(new JScrollPane(table), “Center”);

‘ }

}

// Lớp hỗ trợ thay đồi màu

class ColorTableCellRenderer implements TableCellRenderer { private JPanel panel = new JPanelO ;

public Component getTableCellRendererCamponent(JTable table, Object value, boolean i.^TPlerteri, boolean hasEbcus, int row, int CDlưm)

{

panel.setBackground((Color)value); return panel;

}

}

class ColorTableCellEditor extends ColorTableCellRenderer implements TableCellEditor{ private Color color; private JCo lor Chooser colorChooser-; private JDialog colorDialog;

private EventListenerList listenerList = new EventListenerList (); private ChangeEvent event = new ChangeEvent(this);

ColorTableCellEditor(){

// Chuẩn bị hội thoại về màu

colorChooser = new JColorChooser(); colorDìalog = JColorChooser.createDialog(null,

“Planet Color”, false, colorChooser, new cnlÁstmer () ( public void actionPerformed(ActìonEvent event){ fireEdìtingStopped() ;

},

new ActìonListener(){

public void actionPerformed(ActionEve^t event){ fireEditingCanceled();

}

}) ;

public Component getTableCellEditorCornponent(JTable table, Object value, boolean isSelected, int row, int column)(

// Ở đây ta nhận được màu để thay đổi colorChooser.setColor((Color)value); return getTableCellRendererComponent(table,value, isSelected, true, row, column);

}

public boolean isCellEditable(Eventobject anEvent){ return true;

}

// Bất đầu soạn thảo

public boolean shouldSelectCell(Eventobject anEvent){ colorDialog.setvisible(true) ; return true;

}

public void cancelCellEditi.ng () {

// Huy bò sự thay đổi

colorDìalog.setvisible(false);

}

public boolean stopCellEditing(){ // Kết thúc việc soạn thảo colorDialog.setvisible(false); return true;

}

public Object getCellEditorValue(){ return colorChooser.getColor();

}

public void addCellEditorListener(CellEditorListener 1){ listenerList.add(CellEditorListener.class, 1);

}

public void removeCellEditorListener(CellEditorListener 1){ listenerList.remove(CellEditorListener.class, 1);

}

protected void fireEditingStopped () {

Objectn listeners = listenerList.getListenerList(); for(int i = listeners.length; i >= 0; i -= 2)

((CellEditorListener)listeners[i + 1]).editingStopped(event);

}

protected void fireEditingCanceled(){

Object[] listeners = listenerList.getListenerList(); for(int i = listeners.length; i >= 0; i -= 2)

((CellEditorListener) listeners [i + 1]).editinglanceled(event);’

}

}

Lưu ý: Ngoài những khả năng đã đề cập ở trên, ta còn có thể thao tác trên các hàng, các cột của bảng. Ta có thể đặt lại kích cỡ của các cột, bổ sung hay loại bỏ một số hàng, lựa chọn một số hàng, cột, một số ô và che giấu hay hiển thị chúng, v.v.