我知道这已经得到了回答,但考虑到我仍然是一个新手,我想不出一种方法来执行操作并阻止单元格编辑,我已经尝试了几种方法,我可以成功呈现按钮但是当我点击它时,它编辑单元格而不是按下按钮,我知道为了避免单元格编辑,我应该创建一个抽象表并覆盖此方法:
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,所以这是我用于面板和单元格渲染器的代码:
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);
所以要根据这个线程在表格中呈现按钮: 在 JTable 的单元格中添加按钮以及数据?
我的问题很直接,我如何禁用行编辑(就像 isCellEditable() 方法的用法一样)并对按钮进行操作?非常感谢这里的任何帮助,请考虑一下我还是新手,所以请提供详细信息或样品!亲切的问候, 罗慕洛·罗梅罗