我知道这已经得到了回答,但考虑到我仍然是一个新手,我不能找出一种方法来给动作和阻止单元格编辑,我已经尝试过几种方式,我可以成功渲染按钮但是当我点击它,它编辑单元格而不是按下按钮,我知道为了避免单元格编辑我应该创建一个抽象表并覆盖此方法:
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 3) {
return false;
} else {
return true;
}
}
但我使用默认的JTable,所以这是我用于Panel和单元格渲染器的代码:
class PlusMinusCellRenderer extends JPanel implements TableCellRenderer {
public Component getTableCellRendererComponent(
final JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
if(column < 3)
{
JLabel campo = new JLabel(value.toString());
this.add(campo);
}
if(column > 2)
{
//this is a button
this.add(botaoteste);
materialtable.revalidate();
materialtable.repaint();
}
return this;
}
这是我用来从sql检索数据到Jtable的代码(我自定义了DefaultJTable代码)
String[] columnNames={"teste","abc","def"};
Object[][] data = new Object[1][4];
if(createConnection())
{
try {
Statement statemt = conLogin.createStatement();
ResultSet rs = statemt.executeQuery("SELECT * FROM Materiais");
//ResultSet rs = statemt.executeQuery("SELECT * FROM Materiais");
rsmtdata = rs.getMetaData();
//int columns = rsmtdata.getColumnCount();
columnNames = new String[]{rsmtdata.getColumnName(1),rsmtdata.getColumnName(2),rsmtdata.getColumnName(3),"Deletar"};
if(rs.next())
{
data[0][0] = rs.getString(1);
data[0][1] = rs.getString(2);
data[0][2] = rs.getString(3);
data[0][3] = new Boolean(false);
}
while (rs.next())
{
Object[][] temp = new Object[data.length+1][4];
for(int i=0;i < data.length;i++)
{
for(int j = 0;j < 4;j++)
{
temp[i][j] = data[i][j];
}
}
temp[data.length][0] = rs.getString(1);
temp[data.length][1] = rs.getString(2);
temp[data.length][2] = rs.getString(3);
temp[data.length][3] = new Boolean(false);
data = temp;
}
materialtable = new javax.swing.JTable(data, columnNames);
materialtable = new javax.swing.JTable(data, columnNames){
public TableCellRenderer getCellRenderer( int row, int column ) {
return new PlusMinusCellRenderer();
}
};
materialtable.setRowHeight( 32 );
} catch (SQLException ex) {
Logger.getLogger(ProfessorForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Create the scroll pane and add the table to it.
materialtable.setBackground(new java.awt.Color(153, 255, 51));
materialtable.setSelectionBackground(new java.awt.Color(255, 255, 51));
materialtable.setSelectionForeground(new java.awt.Color(255, 102, 0));
jScrollPane3.setViewportView(materialtable);
所以基于这个线程渲染表格内的按钮: Adding Buttons inside cell of JTable along with data?
我的问题很简单,如何禁用行编辑(就像isCellEditable()方法一样)并对按钮进行操作? 非常感谢任何帮助,请考虑我仍然是新手,所以请详细信息或样品! 亲切的问候, Romulo Romero
答案 0 :(得分:2)
您需要 渲染器和以及编辑器,如此example所示。请参阅{{3>}的如何使用表:编辑器和渲染器。切线上,您应该覆盖isCellEditable()
中的方法TableModel
,而不是扩展JTable
。