我想知道是否有可能灰色或使用我的数据库中的数据将我的JTable中的某些行渲染为不可见?
这些是我的JTable中的列:
public DutyModel(ArrayList<Duty> listOfObjects) {
rowCount = listOfObjects.size();
colCount = columnNames.length;
data = new Object[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
/* Copy an ArrayList element to an instance of MyObject */
Duty d1 = (Duty) (listOfObjects.get(i));
data[i][0] = d1.getDutyId();
data[i][1] = d1.getDutyName();
data[i][2] = d1.getDutyDesc();
data[i][3] = d1.getDutySectorName();
data[i][4] = d1.getDutyStatus();
}
}
当我的表格显示时,我想要d1.getDutyStatus()的行,其中dutyStatus =&#34; Inactive&#34;变得灰暗。我的表目前可以更新为&#34; Active&#34; (按更新按钮)或&#34;非活动&#34; (按下删除按钮)。我不希望用户能够编辑具有&#34;非活动&#34;的dutyStatus的任何职责。非常感谢任何帮助或帮助。谢谢!
以下代码是当用户在JTable中选择一行并按下&#34;更新&#34;和&#34;删除&#34;按钮。 同样,我尝试使用3层架构来运行我的代码,我的控制器类是RetrieveDutyControl,我的实体是Duty。
public void actionPerformed(ActionEvent e) {
int rowSelected = tblDutyList.getSelectedRow();
if (rowSelected >= 0) {
String idDuty = tblDutyList.getValueAt(rowSelected, 0)
.toString();
String name = tblDutyList.getValueAt(rowSelected, 1)
.toString();
String desc = tblDutyList.getValueAt(rowSelected, 2)
.toString();
String sector = tblDutyList.getValueAt(rowSelected, 3)
.toString();
String status = tblDutyList.getValueAt(rowSelected, 4)
.toString();
Duty duty = new Duty(Integer.parseInt(idDuty), name, desc,
sector, status);
RetrieveDutyControl rdc = new RetrieveDutyControl();
ArrayList<Duty> dutyList = rdc.processRetrieveDuties(duty);
JPanel contentPane = new RemoveDutyForm(myFrame, duty);
myFrame.getContentPane().removeAll();
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "No Record Selected",
"Alert", JOptionPane.ERROR_MESSAGE);
}
答案 0 :(得分:1)
尝试使用重写的prepareRenderer()
方法根据数据
示例代码:(使用第一列的值进行验证)
Object[] columnNames = { "A", "B", "C", "D" };
Object[][] data = {
{ "abc", new Double(850.503), 53, true },
{ "lmn", new Double(36.23254), 6, false },
{ "pqr", new Double(8.3), 7, false },
{ "xyz", new Double(246.0943), 23, true } };
JTable table = new JTable(data, columnNames) {
@Override
public java.awt.Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
java.awt.Component comp = super.prepareRenderer(renderer, row, col);
Object value = getModel().getValueAt(row, 0);
if (value.equals("lmn")) {
comp.setBackground(Color.lightGray);
} else {
comp.setBackground(Color.white);
}
return comp;
}
};
对于按钮检查值并不执行任何操作。
如何获取所选行的值?
if(table.getSelectedRow()!=-1){
int rowIndex=table.getSelectedRow();
Object value=table.getModel().getValueAt(rowIndex, 0);
if(value.equals("lmn")){
//do nothing
}else{
// perform desired operation
}
}