How can I change background of several cells with a click? - java

I have a table which every cell keep a string. Actually I used the table as a page of book and it contains text. My problem is that I want to click on a cell and all similar words' background color in the table change to one unique color. For instance, when I click on the cell which contains 'and', all 'and' in my table become highlighted. I implemented defaulttablecellrenderer and I know that when java wants to draw table recall it for every cell. I tried to use intrinsic repetition capability and set the color but it does not work in the way I expected. These are my codes:
JTable t=new Jtabale();
//Filling my table....here....
t.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
int column=((JTable)e.getSource()).getSelectedColumn();
int row=((JTable)e.getSource()).getSelectedRow();
JTable table=(JTable)e.getComponent();
Object myS=table.getValueAt(row, column);//value of that cell saved
CustomCellRenderer r=(CustomCellRenderer)table.getCellRenderer(row, column);
r.setCell(myS);
table.repaint();
}
});
and this is my DefaultTableCellRenderer implementation:
public class CustomCellRenderer extends DefaultTableCellRenderer {
Object myStr;
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);
if(myStr==value){
c.setBackground(Color.YELLOW);
}
else
c.setBackground(table.getBackground());
return c;
}
public void setCell(Object val){
myStr=val;
}
I do not know what's wrong with this code? This is only highlight that cell which I click. But I expected it change the background of several cells together! Even I put println inside the if but even it goes once in the if brace! I got confused. What is your idea?!

Related

How to stop minimize, scrollpane,resize from coloring all my jtable

As you can see in my pictures:
Before minimize:
After minimize
My renderer takes the last color that have used and paints all my table.
Bellow is my custom renderer class:
public class MyCellRenderer extends DefaultTableCellRenderer {
public static double fstValue;
public static double sndValue;
public MyCellRenderer() { }
public MyCellRenderer(double fstValue, double sndValue) {
this.fstValue = fstValue;
this.sndValue = sndValue;
//System.out.println(this.fstValue+" 2ndvalue"+this.sndValue+" ston constructor");
}
#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);
if(!isSelected) {
if(compare(this.fstValue,this.sndValue)== 1){
c.setBackground(Color.GREEN);
}else if (compare(this.fstValue,this.sndValue)== -1) {
c.setBackground(Color.red);
}else{
c.setBackground(null);
}
}
return c;
}
}
I m updating the table fast, and I have no problem with that.
But when I resize or minimize or scroll down, the coloring change.
When I minimize and resize, my table change color all, but when I scroll down only the table that I scrolled change color.
I suspect that it has something to do with the repaint or paint method that my renderer calls and have trouble fixing it.
I use threads and every thread calls the code below for the update:
if( home.text().equals(hometmp.toString())==false)
{
MyCellRenderer cellRenderer = new MyCellRenderer(valuehm,valuehmt);
table1.setValueAt(home.text(),i-1,1);
}
You have two calls to super.getTableCellRendererComponent(...). Get rid of the second. Also, there is no need to cast the first call to a label. The method return a Component which has a setBackground() method.
You don't need the synchronized keyword on the method.

Set Background Color of a clicked table cell

I'm new to Java and I want to change the background color of a Specific cell, the one I clicked on, of a JTable.
I know that I have to use a MouseListener which I already did, also, the mousePressed. But at this point I am pretty lost.
EDIT: Forgot to add that the table is disabled, so you can't select a cell.
Can anyone help me? Thanks!
You must create a custom TableCellRenderer and pass it to the table
like this
public class ColorRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
// get the DefaultCellRenderer to give you the basic component
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
// apply your rules
if(table.isRowSelected(row) && table.isColumnSelected(col))
c.setBackground(Color.GREEN);
else{
c.setBackground(table.getBackground());
}
return c;
}
}
in this class we check if the given cell if the selected cell (which is pretty much what happens when we click it) and paint it differently (in my case I paint it green) , else we paint with the default color or any color you like.
don't forget to set the custom renderer you just created
table.setDefaultRenderer(Object.class, new ColorRenderer());
Edit 1
you must get the row and col of the clicked cell.
create 2 int variables that will hold the position
private int clickedRow=-1,clickedCol=-1;
add a mouse listener that updates the position variables
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent event) {
clickedRow= table.rowAtPoint(event.getPoint());
clickedCol= table.columnAtPoint(event.getPoint());
}
});
after that you change the renderer so it paints only the clicked cell with the special color
if( clickedRow == row && clickedCol == col){
c.setBackground(Color.GREEN);
}

Custom TableCellRenderer negative numbers align to right

I have Jtable with custom cells' renderer, which should align its content to right:
public class BriefViewCellRenderer extends JTextArea implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setText("-200");
}
}
JTable looks nice, except negative numbers. The minus sign apears behind the actual number.
Does anyone knows how to fix it?

JTable Custom TableCellRenderer displaying images

I have a JTable which I would like to display an image depending on the content of a cell, I understand in order to accomplish this I have to implement my own custom cell renderer, which I have already, however, as soon as the first image is drawn on the cell the programme draws the image on other cells regardless of their content. I have tried pretty much everything and have also scoured the internet for a solution, all with no avail. Here is my code:
public class GameBoard extends JTable
{
public GameBoard()
{
super(new GameBoardModel());
setFocusable(false);
setCellSelectionEnabled(true);
setRowHeight(26);
TableColumn column = null;
for (int i = 0; i < getColumnCount(); i++)
{
column = getColumnModel().getColumn(i);
column.setPreferredWidth(26);
}
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setDefaultRenderer(Object.class, new CellRenderer());
}
private class CellRenderer extends DefaultTableCellRenderer
{
private CellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
#Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column)
{
if (value.toString().equals("X"))
{
URL test = getClass().getResource(resources/icon.png");
setIcon(new ImageIcon(test));
}
else
setText(value.toString());
return this;
}
}
Forgive me if I'm doing something silly somewhere along those lines. . .
Thanks in advance,
Zig.
Don't forget to invoke:
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
at the start of the method so you get the default settings of the renderer.
If the above doesn't fix the problem then your code may need to be something like:
if (value.toString().equals("X"))
{
URL test = getClass().getResource(resources/icon.png");
setIcon(new ImageIcon(test));
setText("");
}
else
{
setIcon(null);
setText(value.toString());
}
Also, you should never read the image in the renderer. The render gets called multiple times so you don't want to read the image every time. Read the image in the constructor of the class.

Options instead of JTable

I want to color each rows of table,
by using particular values of database
spcification of mine database is some what like
**
id name color
1 pavan red
2 xyz white
**
i can give a color to complete table using
table.setBackground(new color(158,145,134);
please provide me some solution or hint to approch towards answer,
Thanks in advance.
This isn't hard at all with a JTable! In fact, it's incredibly easy!
See my answer here: Highlight a cell in JTable via custom table model
Reproduced for ease:
...Subclass JTable and override JTable.preparedRenderer(TableCellRenderer renderer, int row, int column). If the row and column numbers are the same, you can change the background color of the Component returned as the display (usually a JLabel);
Here's an example that highlights the row the mouse is over:
#Override
public Component prepareRenderer(final TableCellRenderer renderer, final int row, final int column) {
final Component c = super.prepareRenderer(renderer, row, column);
if (row == this.itsRow) {
c.setBackground(Color.RED);
}
return c;
}
where this.itsRow is an int field updated by a MouseMotionListener:
this.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
SubclassedJTable.this.itsRow = SubclassedJTable.this.rowAtPoint(e.getPoint());
SubclassedJTable.this.repaint();
}
public void mouseDragged(MouseEvent e) {/***/}
});

Categories