Best way to have a JTable populate with objects? - java

Let's say I have an array of People. These people have a bunch of fields like name, position, title, salary.
I've seen most questions be about filling a JTable with 2D arrays which, unless I'm wrong, isn't exactly what I'm trying to do.
I would like to be able to click a button and have the JTable look at the array of People and display that table.
Thanks!
Edit: I'm hoping to be able to just change the setModel arguments here to update using certain values.
JButton btnRefresh = new JButton("Refresh");
btnRefresh.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
table_1.setModel(new DefaultTableModel(new Object[][] {}, new String[] {
"#", "Song", "Artist", "Time" }));
table_1.getColumnModel().getColumn(0).setPreferredWidth(22);
table_1.getColumnModel().getColumn(1).setPreferredWidth(191);
table_1.getColumnModel().getColumn(2).setPreferredWidth(179);
panel_3.revalidate();
}
});
So I'm able to change the column headers by changing these string values but what can I change the new Object[][]{} to?

This code fragment does exactly what I needed it to do.
JButton btnRefresh = new JButton("Refresh");
btnRefresh.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
table.setModel(new DefaultTableModel(dataArray(),
new String[] { "first", "second", "third", "fourth" }));//Changes the column headers
panel.revalidate();
}
private Object[][] dataArray() {
Object[][] table = new Object[5][4];//5 = rows 4 = columns
for (int i = 0; i < 5; i++) {
for(int j = 0; j< 4; j++){
if(j == 0){
table[i][j] = i+1;
}else if(j== 1){
table[i][j] = "Second Row";//Change these strings to whatever variable you want to fill the second row with, same with the other 3.
}else if(j== 2){
table[i][j] = "Third Row";
}else{
table[i][j] = "Fourth Row";
}
}
}
return table;
}
});

Related

Copying (some columns of) a JTable to a new JTable

I have a JTable displayed in a frame. This table must remain unmodified for
later processing. At some point I want to show a column reduced version of this
table in a dialog. So I make a copy of the original table in creating a new
TableModel and TableColumnModel, thereby skipping the columns not needed.
Everything is fine until the dialog is set to visible. Then I run into an
endless error loop, starting with an "ArrayIndexOutOfBoundsException: 3 >= 2".
If 3 is the index to a table row, then it's indeed too large.
As the reduced table has only two columns, a column index of 2 would already exceed. Checking the columns with
getColumnCount() shows that the values are ok.
I suspect my copyTable method to be the culprit, but have no idea where the 3
index is coming from.
Instead of filling the rows of the table's model one by one, I succeeded using DefaultTableModel.addColumn(Object columnName, Object[] columnData) as suggested here. Then, however, I lose the columns' width information. Hence I would still like to know my fault in the current code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class CopyTable extends JFrame {
public static final long serialVersionUID = 100L;
public CopyTable() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JTable table= createTable();
JScrollPane scroll= new JScrollPane(table);
add(scroll, BorderLayout.CENTER);
JButton b= new JButton("Show dialog");
b.addActionListener(e -> createAndShowDialog(table));
add(b, BorderLayout.SOUTH);
setSize(table.getColumnModel().getTotalColumnWidth()+11, 240);
setVisible(true);
}
static public void main(String args[]) {
EventQueue.invokeLater(CopyTable::new);
}
// #param columns Indices of columns to be copied into the new table.
public JTable copyTable(JTable table, int... columns) {
DefaultTableModel tblModel= new DefaultTableModel(0, columns.length);
DefaultTableModel oldModel= (DefaultTableModel)table.getModel();
Object[] row= new Object[columns.length];
int iRow= 0;
while (iRow<oldModel.getRowCount()) {
for (int i=0; i<columns.length; i++) {
row[i]= oldModel.getValueAt(iRow, columns[i]);
}
tblModel.addRow(row);
iRow++;
}
DefaultTableColumnModel colModel= new DefaultTableColumnModel();
DefaultTableColumnModel oldColModel=
(DefaultTableColumnModel)table.getColumnModel();
for (int i=0; i<columns.length; i++) {
colModel.addColumn(oldColModel.getColumn(columns[i]));
/* Creating a new column didn't help.
TableColumn tc= new TableColumn();
tc= oldColModel.getColumn(columns[i]);
colModel.addColumn(tc);
*/
}
return new JTable(tblModel, colModel);
}
private void createAndShowDialog(JTable table) {
JTable tbl = copyTable(table, 0, 3); // Copy only columns 0 and 3.
JOptionPane.showMessageDialog(this, ""+tbl.getModel().getRowCount()+", "+
tbl.getModel().getColumnCount()+", "+
tbl.getColumnModel().getColumnCount(),
"Checking row/column count",
JOptionPane.INFORMATION_MESSAGE);
JDialog dlg= new JDialog(this, "Reduced table", true);
dlg.setLocationRelativeTo(this);
JScrollPane scroll = new JScrollPane(tbl);
dlg.add(scroll, BorderLayout.CENTER);
dlg.pack();
dlg.setVisible(true);
}
private JTable createTable() {
String headers[] = {"Fruit", "Colour", "Count", "Price"};
Object data[][] = {
{"Apple", "Green", 6, .3},
{"Banana", "Yellow", 3, .4},
{"Cherry", "Red", 10, 1.1}
};
DefaultTableModel model = new DefaultTableModel(data, headers) {
public Class<?> getColumnClass(int column) {
Class<?> returnValue;
if (column>=0 && column<getColumnCount() && getValueAt(0,column)!=null)
returnValue= getValueAt(0, column).getClass();
else
returnValue= Object.class;
return returnValue;
}
};
JTable tbl= new JTable(model);
TableColumnModel tcm= tbl.getColumnModel();
int[] width= new int[] {60, 50, 40, 40};
for (int i=0; i<headers.length; i++) {
tcm.getColumn(i).setPreferredWidth(width[i]);
tcm.getColumn(i).setWidth(width[i]);
}
return tbl;
}
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 2
at java.base/java.util.Vector.elementAt(Vector.java:466)
at java.desktop/javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:661)
at java.desktop/javax.swing.JTable.getValueAt(JTable.java:2763)
at java.desktop/javax.swing.JTable.prepareRenderer(JTable.java:5780)
at java.desktop/javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2207)
at java.desktop/javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2109)
at java.desktop/javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1905)
at java.desktop/javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
at java.desktop/javax.swing.JComponent.paintComponent(JComponent.java:852)
java 18
There is no need to copy the TableModel (they are shareable by design) - all you need is a new TableColumnModel containing clones of the original: note that the relevant coordinate system is the model index.
Example:
TableColumnModel sourceColumnModel = sourceTable.getColumnModel();
DefaultTableColumnModel reducedColumnModel = new DefaultTableColumnModel();
for (int i = 0; i < sourceColumnModel.getColumnCount(); i++) {
TableColumn sourceColumn = sourceColumnModel.getColumn(i);
int modelIndex = sourceColumn.getModelIndex();
if (modelIndex % 2 == 0) { // replace with your condition
TableColumn column = new TableColumn(modelIndex, sourceColumn.getPreferredWidth());
column.setHeaderValue(sourceColumn.getHeaderValue());
reducedColumnModel.addColumn(column);
}
}
JTable reducedTable = new JTable(sourceTable.getModel(), reducedColumnModel);
#g00se
Your solution works. Thank you. The only drawback is that removing columns from the TableColumnModel doesn't remove them from the TableModel. So I added the following to your code
int icnt= oldModel.getRowCount();
for (int j=0; j<icnt; j++) {
Vector<?> vec= (Vector<?>)data.get(j);
for (int i=columns.length-1; i>=0; i--) {
vec.removeElementAt(columns[i]);
}
data.setElementAt(vec, j);
}
((DefaultTableModel)result.getModel()).setDataVector(data, headers);
return result;
But due to lack of Generics knowledge, I cannot make the code compile. Still an idea for that?
Just copying/creating a new model would avoid any removal. So I am still curious as for my original error.
Edit
----------------------------------------------------------
Generics:
Vector<Vector<Object>> data = ...
...
Vector<Object> vec= data.get(j);
----------------------------------------------------------
Finally I got my original version to work. colModel.addColumn(oldColModel.getColumn(columns[i])); passes only a reference of the column. But one has to create a new instance for each column in the new table.
// #param columns Indices of columns to be copied into the new table.
public JTable copyTable(JTable table, int... columns) {
DefaultTableModel oldModel= (DefaultTableModel)table.getModel();
DefaultTableModel tblModel= new DefaultTableModel(0, columns.length) {
public Class<?> getColumnClass(int column) {
Class<?> returnValue;
if (column>=0 && column<getColumnCount() && getValueAt(0,column)!=null)
returnValue= getValueAt(0, column).getClass();
else
returnValue= Object.class;
return returnValue;
}
};
Object[] row= new Object[columns.length];
int icnt= oldModel.getRowCount();
for (int i=0; i<icnt; i++) {
for (int j=0; j<columns.length; j++) {
row[j]= oldModel.getValueAt(i, columns[j]);
}
tblModel.addRow(row);
}
DefaultTableColumnModel oldColModel=
(DefaultTableColumnModel)table.getColumnModel();
DefaultTableColumnModel colModel= new DefaultTableColumnModel();
for (int i=0; i<columns.length; i++) {
// colModel.addColumn(oldColModel.getColumn(columns[i])); // Endless err loop
TableColumn tc= oldColModel.getColumn(columns[i]);
TableColumn tcNew= new TableColumn(i, tc.getPreferredWidth(),
tc.getCellRenderer(), tc.getCellEditor());
tcNew.setHeaderValue(tc.getHeaderValue());
colModel.addColumn(tcNew);
}
return new JTable(tblModel, colModel);
}
private void createAndShowDialog(JTable table) {
JTable tbl = copyTable(table, 0, 1, 3); // Copy only columns 0, 1 and 3.
JDialog dlg= new JDialog(this, "Reduced table", true);
JScrollPane scroll = new JScrollPane(tbl);
scroll.setPreferredSize(
new Dimension(tbl.getColumnModel().getTotalColumnWidth(), 80));
dlg.add(scroll, BorderLayout.CENTER);
dlg.pack();
dlg.setLocationRelativeTo(this);
dlg.setVisible(true);
}
I can't say I know quite why you get that exception, but this is a possible problem-free alternative, involving cloning the table then removing unwanted columns. This is based on the intuitive ascending ordering of required columns. Obviously the logic could be made easier by passing an array of columns to be removed rather than retained.
// #param columns Indices of columns to be copied into the new table.
public JTable copyTable(JTable table, int... columns) {
DefaultTableModel oldModel = (DefaultTableModel) table.getModel();
#SuppressWarnings("unchecked")
Vector<? extends Vector> data = (Vector<? extends Vector>) oldModel.getDataVector().clone();
Vector<Object> headers = new Vector<>();
TableColumnModel cmSource = table.getColumnModel();
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
headers.add(cmSource.getColumn(i).getIdentifier());
}
JTable result = new JTable(data, headers);
TableColumnModel cmTarget = result.getColumnModel();
Set<Integer> columnsToCopy = new HashSet<>();
for (int i = columns.length; --i >= 0;) {
columnsToCopy.add(columns[i]);
}
for (int i = cmTarget.getColumnCount(); --i >= 0;) {
if (!columnsToCopy.contains(i)) {
cmTarget.removeColumn(cmTarget.getColumn(i));
}
}
return result;
}

How can I dynamically change the number of items in a JComboBox

private void dropDownMenu(JPanel jp1, String prodId){
int len = storeManager.getInv().getStockAmount(prodId);
int[] nums = new int[len];
String[] numPossible = new String[len];
for (int i=0; i<len; i++){
nums[i] = i+1;
}
for (int i=0; i<len; i++){
numPossible[i] = String.valueOf(nums[i]);
}
JComboBox<String> cb = new JComboBox<String>(numPossible);
JButton okButton = new JButton("Add To Cart");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Product p1 = storeManager.getInv().getProd(prodId);
String quan = (String) cb.getSelectedItem();
int quantity = Integer.parseInt(quan);
if (quantity > storeManager.getInv().getStockAmount(prodId)) {
System.out.println("Not Enough Stock.");
} else {
storeManager.getCart().addToCart(p1, quantity);
storeManager.getInv().removeStockAmount(prodId, quantity);
//update the dropdown menu here
}
}
});
jp1.add(cb);
jp1.add(okButton);
}
Essentially what i am looking for is that whenever i select a number from the drop down menu, i want the number of items in the menu to be reduced by the amount that was added to cart. for example if i add 5 to cart then i want the dropdown menu to go from allowing me to choose 10 to 5 only.
Image of GUI
As a thought...Instead of doing all these conversions from integer to string and string to back to integer in order to fill your combo box, why not just have a combo box of Integer? You're dealing initially with integer quantity values anyways:
JComboBox<Integer> cb = new JComboBox<>();
int len = storeManager.getInv().getStockAmount(prodId);
for (int i = 1; i <= len; i++) {
cb.addItem(i);
}
cb.setSelectedIndex(0);
Your action listener might look something like this now:
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Product p1 = storeManager.getInv().getProd(prodId);
int quantity = (int) cb.getSelectedItem();
/* This 'if' statement below would be moot if the Combo-Box
is properly updated unless editing is allowed in the combo
which in this case...disable that feature. */
if (quantity > storeManager.getInv().getStockAmount(prodId)) {
System.out.println("Not Enough Stock.");
} else {
storeManager.getCart().addToCart(p1, quantity);
len = storeManager.getInv().removeStockAmount(prodId, quantity);
cb.removeAllItems();
for (int i = 1; i <= len; i++) { cb.addItem(i); }
cb.setSelectedIndex(0);
}
}
});
Possibly better yet would be to utilize the JSpinner component instead of a Combo Box. A drop-down list in this use case always seems a bit obtrusive in my opinion.

Getting old values from Jtable

I am facing a strange problem with the Jtable. I have a small standalone java application in which I have used Jtable that shows data that is retrieved from database. User can view and edit the data. Once he edit the cell and presses the update button then the edited values will be updated in the database. Now what happening is for the first time when user edit the data and click on update button then the values are properly persisted in the database and user gets out of the module. But again if he/she goes to the same module and edits some more cells and click on update button then in back end i get old value from those cells although the Jtable shows the latest updated values in the cells.
Below is the code.
private JTable jt;
private TableRowSorter<TableModel> tableSorter;
private Dao dao=new Dao();
updateDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean isSuccessful = true;
int rowCount = jt.getRowCount();
List<EmployeeMaster> empMasterList = new ArrayList<>();
int j = 0;
for (int i = 0; i < rowCount; i++) {
EmployeeMaster master = new EmployeeMaster();
j = 0;
try {
master.setEmpId(Long.parseLong((String) jt.getValueAt(i, j)));
j++;
compId.setName(Long.parseLong((String) jt.getValueAt(i, j)));
j++;
compId.setNumber((String) jt.getValueAt(i, j));
j++;
empMasterList.add(master);
}
dao.updateAllEmpDetails(empMasterList);
homePanel.setVisible(true);
UpdateEmp.setVisible(false);
}
}
});
getDataFromDBtoJtable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
List<EmployeeMaster> empMasterList = dao.getAllEmpDetails();
String data[][] = new String[empMasterList.size()][3];
int i = 0;
int j = 0;
for (EmployeeMaster employeeMaster : empMasterList) {
j = 0;
data[i][j] = String.valueOf(employeeMaster.getEmpId());
j++;
data[i][j] = String.valueOf(employeeMaster.getName());
j++;
data[i][j] = String.valueOf(employeeMaster.getNumber());
i++;
}
String column[] = { "ID", "Name", "Number"};
jt = new JTable(data, column) {
public boolean isCellEditable(int row, int column) {
if (column == 0 || column == 1 || column == 2)
return false;
else
return true;
};
};
tableSorter = new TableRowSorter<TableModel>(jt.getModel());
jt.setBounds(12, 12, 1200, 400);
jt.setRowSorter(tableSorter);
homePanel.setVisible(false);
UpdateEmp.setVisible(true);
JScrollPane pane = new JScrollPane(jt);
pane.setBounds(1, 40, 1150, 300);
setBounds(0, 0, 2000, 800);
UpdateEmp.add(pane);
}
});
updateDetails -> button to get the data from jtable and update it in database
getDataFromDBtoJtable -> button to get data from Database and show it in Jtable
Whenever user hits the updateDetails i am updating the database and forcing user to get out of the module. So everytime whenever user get into jtable module he/she gets new Jtable instance. But still unable to identify what's going wrong.

JTable select and deselect not working

I have a problem with my JTable. Firstly I selected some entries in my table. However when I deselect some of them, the table could not understand it.
Example scenario: I select job1 and 2 for the testing after that I change my mind and de-select job2. But in the result I saw job1 job1 and job2 ( job 1 seen 2 times and even though I dis-select job 2 I saw them.) Or after selected all the jobs ( choose all button) I want to deselect all of them (Clear button) when I click clear all the table seems empty. It is good but somehow the background of the program still protect the all old selection. How can I solve this?
Try:
I created the row of my table by read csv file.
public class JobSelectionListPanel extends JPanel {
private static final long serialVersionUID = 5198916547962359735L;
private static JobSelectionListPanel INSTANCE = new JobSelectionListPanel();
public static JobSelectionListPanel getInstance() {
return INSTANCE;
}
private JTable table;
private JButton next, back, btnClear, btnNewButton, btnChooseAll;
private JobList fnnJobList = new JobList();
private JobSelectionListPanel() {
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
table.setBorder(new CompoundBorder());
// Read all FNN jobs from file
try {
fnnJobList.readFromFile("rules.csv");
} catch (IOException e1) {
System.out.println("You are not able to read the rules.csv file");
}
// Create ArrayList of JobNames
Object[][] initialData = new Object[fnnJobList.size()][1];
int i = 0;
for (Job jobDes : fnnJobList) {
initialData[i][0] = (Object) jobDes.getJobname();
i++;
}
String[] columnNames = new String[] { "", "Your preferences" };
table.setModel(new DefaultTableModel(initialData, columnNames) {
private static final long serialVersionUID = 1L;
#SuppressWarnings("rawtypes")
Class[] columnTypes = new Class[] { Object.class, Boolean.class };
#SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
table.getColumnModel().getColumn(1).setPreferredWidth(80);
table.getColumnModel().getColumn(1).setMinWidth(40);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setCellSelectionEnabled(true);
I user want to choose all rows then I implemented this.
btnChooseAll = new JButton("Choose all");
btnChooseAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel chooseAllData = (DefaultTableModel) table.getModel();
if (DeviceGroups.DeviceAList.size() == 0 || DeviceGroups.DeviceBList.size() == 0
|| DeviceGroups.DeviceCList.size() == 0 || DeviceGroups.DeviceDList.size() == 0)
JOptionPane.showMessageDialog(null,
"You should choose at least 1 device for each test device to apply this test case", "Invalid OPTION",
JOptionPane.ERROR_MESSAGE);
else
for (int i = 0; i < chooseAllData.getRowCount(); i++) {
for (int j = 1; j < chooseAllData.getColumnCount(); j++) {
chooseAllData.setValueAt(true, i, j);
}
}
}
});
For clear all preferences :
btnClear = new JButton("Clear all");
// Clear button create a model of JTable and delete all the rows of table!!
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel clearTableData = (DefaultTableModel) table.getModel();
for (int i = 0; i < clearTableData.getRowCount(); i++) {
for (int j = 1; j < clearTableData.getColumnCount(); j++) {
clearTableData.setValueAt(null, i, j);
}
}
}
});
I see the following problem in your code: mixing up view indexes and model indexes. This is the offending snippet:
for (int i = 0; i < table.getRowCount(); i++) {
if (table.getValueAt(i, 1) != null) {
if (((Boolean) table.getValueAt(i, 1)).booleanValue()) {
String jobName = (((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString());
You are using the i variable to denote view row indices, since you are checking values in this statement: table.getValueAt(i, 1) != null.
But then a bit further you are using i to index the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString();
If i is to be a view index, you need to convert it to a model index before indexing the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(table.convertRowIndexToModel(i), 0).toString();
Also, when columns would be switched around in the view (ie on screen in your GUI), the following will probably not work as intended:
table.getValueAt(i, 1) != null
You most likely mean to say, get the second column value in the model, not the view. Best rewrite then as
table.getValueAt(i, table.convertColumnIndexToView(1)) != null

Disable particular row in JTable using data from database

I was wondering if it's possible to grey out or render some rows in my JTable to be invisible using the data from my data base?
These are the columns in my 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();
}
}
When my table is displayed, I want the rows with d1.getDutyStatus() where dutyStatus = "Inactive" to be greyed out. My table can currently be updated to either "Active" (By pressing an update button), or "Inactive" (By pressing a remove button). I don't want the user to be able to edit any of the duties that have the dutyStatus of "Inactive". Any assistance or help is greatly appreciated. Thanks!
The below code is what happens when the user selects a row in the JTable and presses the "Update" and "Delete" button. Also, I'm trying to use a 3 tier architecture to run my codes, my controller class is RetrieveDutyControl and my entity is 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);
}
Try with overridden prepareRenderer() method to gray out the row based on data
Sample code: (use first column's value to validate)
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;
}
};
For buttons check for value and do nothing.
How to get the value of the selected row?
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
}
}

Categories

Resources