TableCellRenderer selected cell problem - java

I want to implement a tablecellrenderer of a JTable component, which should show a different color depending on the cell data. I got this, but I can't change the color of the selected cell. I tried to do this:
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
{
if (isSelected) {
this.setBackground((Color)UIManager.get("Table.selectionBackground"));
this.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
} else {
this.setForeground((Color)UIManager.get("Table.foreground"));
this.setBackground((Color)UIManager.get("Table.background"));
this.setBorder(BorderFactory.createEmptyBorder());
}
...
}
but it does not work :S .. I can not see the problem because the JTable does not show anything different when I click on a cell.

I want to implement a tablecellrenderer of a JTable component, which should show a different color depending on the cell data
The code you posted does not do this. Basically all your code does is duplicate the default behaviour of the renderer
You may find the Table Row Rendering approach easier to implement.

Assuming you're using a JLabel as the base of the component, setting the background will have no effect unless you also set opaque to true. JLabels default to not opaque and so do not paint the background.

Related

Trying to color specific rows of JTable using Custom Renderer, instead all my rows are colored

for my Java program basically when the value in column 4 of my JTable is greater than column 3, I want those specific rows to be colored in red and not the other rows.
I have implemented the following code, but for some reason all my rows are getting colored in red rather than just the ones matching the criteria.
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){
#Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
int Value1= Integer.parseInt(table.getModel().getValueAt(row, 3).toString());
int Value2= Integer.parseInt(table.getModel().getValueAt(row, 4).toString());
if (Value2>=Value1) {
setBackground(Color.red);
}
return this;
}
});
Any suggestions/tips on how to fix this?
A DefaultTableCellRenderer instance uses a template component to render all cells (namely itself, see documentation). Once you set its color, the template will have that color and will be applied to all subsequent cells.
What you need to do is in your logic, set the color to red in the cases you need, and set it to the default background color in all other cases.
if(!isSelected) {
if (Value2>=Value1) {
setBackground(Color.red);
} else {
setBackground(table.getBackground()); // or use another color for another background
}
}
Looking at your code again, I'm noticing you are making an error with regards to model versus view indices. The getTableCellRendererComponent method is called with view indices, yet you are using these to index the model (eg in table.getModel().getValueAt(row, 3)). When your table is sorted, results will be incorrect as model indices and view indices will differ.
If you need to get values from the model, you first need to convert the view indices to model indices. Use JTable.convertRowIndexToModel and JTable.convertColumnIndexToModel to do that. Eg:
int modelRowId = table.convertRowIndexToModel(row);
int Value1= Integer.parseInt(table.getModel().getValueAt(modelRowId, 3).toString());
int Value2= Integer.parseInt(table.getModel().getValueAt(modelRowId, 4).toString());
Take a look at Table Row Rendering which shows how to do this by overriding the prepareRenderer(...) method of the JTable.
Using this approach you don't need a custom renderer for each data type in the table.

Change the background color of a row in a JTable

In Netbeans(IDE 7.0) at advanced search keyrealese event I want to change the Jtable row colors under the condition.If system date(current date) is equal to that table(in database) coloumn name "Date" and system time(current time) is less than to table coloum name "Time" then I want to display that row in Green color else want to display in Red colour.Please share your knowledge.It will very usefull to me.:.respect.
hints-The table name is in DB is "Vehicle",The coloumns are "Date","Time","Veh_No","Model"..
I think we want to use "If" condition,and create two other variables to store system date and system time before give and condition.Plz help me..
Write a custom cell renderer.
public class CustomCellRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(....) {
Color color = getRowBackGroundColor(table, value, isSelected, hasFocus, row, column);
comp.setBackground(color);
return comp;
}
}
Override the prepareRenderer method of JTable. Logic remains similar to getTableCellRendererComponent().
I prefer overriding the prepareRenderer method.

Java - Is it possible to put an image and a String in the same JTable cell?

I know how to put a String into a JTable cell, and I know how to put an image into a JTable cell. But is it possible to put an image and a String into the SAME JTable cell?
The reason for this is that I have a 'status' column in my JTable, which at the moment contains either a green, amber or red image. And in order to fulfill the design requirement, I need to add some explanatory text alongside each image (so the text next to the green image would be "Online", the text next to the amber image would be "Unknown" and the text next to the red image would be "Offline"). I need to do this in a single column (or what looks/behaves like a single column) rather than two columns.
I have researched this, but found no info at all.
Yes.
You need to use a custom cell renderer. Check out How to use Tables for more details.
You actually have two choices, you could simply set the icon and the text of the cell or you could use the renderers tooltip text instead...
public class IconTextCellRemderer extend DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setText(...);
setIcon(...);
setToolTipText(...);
return this;
}
}
Of course you need to apply the renderer to the column...
TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(x).setCellRenderer(new IconTextCellRemderer());

Hiding an individual cell in JTable depending on model value

I have a JTable showing values from a model allowing integer values 0, 1 and 2. The values are shown in a 9 by 9 grid (like a sudoku game board).
My question is: How do I hide the zero values from the GUI?
That is, in the table cells that has a model value of zero, I dont want the GUI to show any value. The model must however contain the zero value due to calculations being done.
I have tried to use a DefaultTableCellRenderer and setting the cell component to invisible by using setVisible(true) (as in this question), but I get no result.
I have managed to use a DefaultTableCellRenderer to toggle any cell's background color depending on the model state (if a cell is considered "negative"). I do want to keep the background color visible.
I am a bit new to java, so maybe this is just an update issue?
Here is my DefaultTableCellRenderer:
private static class GameTableRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
#Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
GameModel model = (GameModel) table.getModel();
if(model.isNegative(row, column))
c.setBackground(Color.lightGray);
else
c.setBackground(Color.white);
if(model.getAbsoluteValueAt(row, column) == 0)
c.setVisible(false);
else
c.setVisible(true);
return c;
}
}
The "getAbsoluteValueAt" method returns an integer 0, 1 or 2. The change of background color works perfectly fine.
My model extends AbstractTableModel, and the JTable uses the renderer like this:
table.setDefaultRenderer(int.class, renderer);
I hope this information is enough to explain my problem and the efforts I so far have put in. Please ask for more information and I will provide it.
Thank you in advance. /Fredrik
Or you can use the following:
if(model.getAbsoluteValueAt(row, column) == 0)
c.setForeground(c.getBackground());
else
c.setForeground(Color.BLACK);
Instead of making the component invisible, set its text to the empty string:
if (model.getAbsoluteValueAt(row, column) == 0) {
((JLabel) c).setText("");
}

How to change background color of the selected item in JList dynamically

How can I change the background color of the item which is selected in JList dynamically?
Something like the following should help as a starting point:
public class SelectedListCellRenderer extends DefaultListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (isSelected) {
c.setBackground(Color.RED);
}
return c;
}
}
// During the JList initialisation...
jlist1.setCellRenderer(new SelectedListCellRenderer());
An easier way would be to go to design mode in Eclipse, and in the properties of your JList, click on the button that has two small arrows with a big yellow arrow inbetween to open up "show advanced properties." then scroll down and change the color where it says "selectionBackground" and change the color there (it will probably be gray, but it will still change). Now, when you run your program, whatever you select, the background will be that color.
jList1.setSelectedIndex(currentLine);
jList1.setSelectionBackground(Color.red);
Just Set Selected index of all the items you want to color in a loop and Change the color Accordingly!
If I am clearly understanding you, look into javax.swing.ListCellRenderer.
You need to reimplement it or extend javax.swing.DefaultListCellRenderer and customize the getListCellRendererComponent method.

Categories

Resources