通常我们需要为不同单元格实现不同的功能,如某单元格为下拉框、选择框、弹出框等。我们可以写成一个通用的控件。下面是一个弹出颜色选择框的实例代码:
package utils;
import java.awt.Color;
import javax.swing.JColorChooser;
import javax.swing.JPanel;
public class TableCellExpressionEditor extends JPanel {
// ...按钮
private javax.swing.JButton fileButton;
// 文件路径输入框
private javax.swing.JTextField valueField;
private java.awt.Component self;
public TableCellExpressionEditor() {
self = this;
initComponents();
}
private void initComponents() {
valueField = new javax.swing.JTextField();
fileButton = new javax.swing.JButton();
setLayout(new java.awt.BorderLayout());
valueField.setText("");
add(valueField, java.awt.BorderLayout.CENTER);
fileButton.setText("...");
fileButton.setMargin(new java.awt.Insets(0, 2, 0, 2));
fileButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileButtonActionPerformed(evt);
}
});
add(fileButton, java.awt.BorderLayout.EAST);
}
// 文件路径选择
private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {
String filePath = valueField.getText();
if (filePath != null && filePath.length() > 0) {
filePath = new java.io.File(filePath).getParent();
}
Color returnVal = JColorChooser.showDialog(this, "颜色选择框", Color.red);
if(returnVal!=null){
valueField.setText(returnVal.toString());
}
}
// 内部定制的TableCellEditor
class MyCustomCellEditor extends javax.swing.AbstractCellEditor implements
javax.swing.table.TableCellEditor {
public Object getCellEditorValue() {
return valueField.getText();
}
public java.awt.Component getTableCellEditorComponent(
javax.swing.JTable table, Object value, boolean isSelected,
int row, int column) {
if (value == null)
valueField.setText("");
else
valueField.setText(value.toString());
return self;
}
}
// 对外的接口方法
public void setColumn(javax.swing.table.TableColumn column) {
column.setCellEditor(null);
column.setCellEditor(new MyCustomCellEditor());
}
public String getValueFieldText(){
return valueField.getText();
}
}
如何使用该通用的控件:
TableCellExpressionEditor cellExp = new TableCellExpressionEditor();
cellExp.setColumn(curColumn);