我尝试创建一个组合框并添加到我的表格列中。我用这个例子。当我尝试这样做col5.setCellRenderer(cmbRender);
时会抛出:
“ComboBoxRenderer 无法转换为 TableCellRenderer”。
组合渲染器
class ComboBoxRenderer extends JLabel
implements ListCellRenderer {
private Font uhOhFont;
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
int selectedIndex = ((Integer)value).intValue();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
String pet = petStrings[selectedIndex];
setUhOhText(pet + " (no image available)",
list.getFont());
return this;
}
protected void setUhOhText(String uhOhText, Font normalFont) {
if (uhOhFont == null) { //lazily create this font
uhOhFont = normalFont.deriveFont(Font.ITALIC);
}
setFont(uhOhFont);
setText(uhOhText);
}
}
我试着这样打电话
ComboBoxRenderer cmbRender = new ComboBoxRenderer();
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(cmbRender);// give me error here
我想在我的表列中创建在 petString 中分配的值。请指教。
这就是我为 TextBox 做的事情
TextRenderer2 renderer2 = new TextRenderer2();
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
MyTableCellEditor editor = new MyTableCellEditor();
col5.setCellEditor(editor);
col5.setCellRenderer(renderer2);
col5.setPreferredWidth(100);
文本渲染器
class TextRenderer2 extends JLabel implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JPanel jp_panel = new JPanel();
JTextPane jta_text = new JTextPane();
JScrollPane jsp_scroll = null;
String valStr = value.toString();
jta_text.setText(valStr);
jp_panel.setLayout(new BorderLayout());
jsp_scroll = new JScrollPane(jta_text);
jp_panel.add(jsp_scroll, BorderLayout.CENTER);
return jp_panel;
}
}