Cell selection color

I want to do something like this:

// init table and plug-in!
    table = new JTable(model)
    {
      public Color getSelectionBackground()
      {
        if(frame.hasFocus())
        {
          System.out.println("Explorer table HAS focus");
          return Configuration.SELECTION_IN_FOCUS;
        }
        else
        {
          System.out.println("Explorer table has NOT focus");
          return Configuration.SELECTION_OUT_FOCUS;
        }
       
      }
    };

over-ride the getSelectionBackground() method so that the selection color will change when the user clicks onto another frame.
but if the JTable has already been initialised elsewhere, then how do i over-ride these methods
i.e.
JTable table = anotherClass.getTable();

** now over-ride??

Also is this a good way to handle such things??  and what about look&feel - here i have hard coded colors!!

Thanks
cathalmchaleAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
You should use a custom CellEditor
0
expertmbCommented:
JTable table = anotherClass.getTable();

** now over-ride??
dont think so , you cant override it.
0
cathalmchaleAuthor Commented:
>> CellEditor
why ever so?
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

expertmbCommented:
override the TableCellEditor
getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
0
CEHJCommented:
Just reading your q again. If you're not talking about when editing, then the renderer can be considered:

http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender
0
cathalmchaleAuthor Commented:
But I dont want to edit cells!
0
cathalmchaleAuthor Commented:
>>  Just reading your q again. If you're not talking about when editing, then the renderer can be considered:

yeah i guess so, but when it comes down to it would a default renderer not be calling the JTable's getSelectionBackground anyway!?
0
petmagdyCommented:
try
JTable.isFocusOwner()
0
CEHJCommented:
>>would a default renderer not be calling the JTable's getSelectionBackground anyway!?

Probably not. I've never seen that in Sun's renderer examples
0
cathalmchaleAuthor Commented:
I tried this:

table = new JTable(model)
    {
      public Color getSelectionBackground()
      {
        if(this.isFocusOwner())
        {
          System.out.println("Explorer table HAS focus");
          return Configuration.SELECTION_IN_FOCUS;
        }
        else
        {
          System.out.println("Explorer table has NOT focus");
          return Configuration.SELECTION_OUT_FOCUS;
        }
       
      }
    };

and it "sort of" works, but for some reason, when i click on a different frame (so the JTable goes out of focus) the actual cell which is selected gets the SELECTION_OUT_FOCUS color, but the rest of the row appears selected with SELECTION_IN_FOCUS color.
  Any idea why??
0
cathalmchaleAuthor Commented:
strangely i get the same funny results when i do:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
  {
    int min = table.getSelectedRow(), max = table.getSelectedRow() + table.getSelectedRowCount() - 1;
    // set the text and icon on the JLabel (the super class) and return this component
    this.setText(value.toString());
    // determine selection color
    if (row >= min && row <= max)
    {
      if(table.isFocusOwner())
      {
        this.setForeground(table.getSelectionForeground());
        this.setBackground(table.getSelectionBackground());
      }
      else
      {
        this.setBackground(SELECTION_OUT_FOCUS);
      }
    }
    else
    {
      this.setForeground(table.getForeground());
      this.setBackground(table.getBackground());
    }

    return this;
  }

??
0
CEHJCommented:
'funny'?
0
zzynxSoftware engineerCommented:
>> Any idea why??
I think because you don't control when getSelectionBackground()/getTableCellRendererComponent() is called.

Maybe you could - whenever the focus is lost - force it by calling fireTableRowsUpdated() on the table's model.
0
cathalmchaleAuthor Commented:
>> funny = the post above:
and it "sort of" works, but for some reason, when i click on a different frame (so the JTable goes out of focus) the actual cell which is selected gets the SELECTION_OUT_FOCUS color, but the rest of the row appears selected with SELECTION_IN_FOCUS color.

also when i click on a cell for the first time (when the table has been out of focus) the result for
if( table.isFocusOwner )  is false  so thats an anomoly!
0
zzynxSoftware engineerCommented:
>>whenever the focus is lost
by adding a WindowListener to your frame.
Then fire in the function
     void windowDeactivated(WindowEvent e)
0
cathalmchaleAuthor Commented:
i can get things to work now using a table renderer in combination with a focus listener (which just calls table.repaint();)
but its difficult to make things generic and i cant help but feel there must be some more standard way for highlighting component focus for what is being worked on at that instance?

perhaps not
0
zzynxSoftware engineerCommented:
>> which just calls table.repaint();
OK, that's the "raw" implementation of my idea ;°)
Finer would be: only update what's needed: the selected row using fireTableRowsUpdated()
0
cathalmchaleAuthor Commented:
>> fireTableRowsUpdated()

i actually tried that, and i dont know why but it didnt work!
0
zzynxSoftware engineerCommented:
Did you call it like
     fireTableRowsUpdated( theTable.getSelectedRow(), theTable.getSelectedRow() );

?
0
cathalmchaleAuthor Commented:
no actually just called
tableModel.fireRowDataChanged();
0
zzynxSoftware engineerCommented:
You mean fireTableDataChanged()?
0
objectsCommented:
You don't need a custom renderer, or fire any events to implement what you need.
You should just need a FocusListener that sets the selection background

public class SelectionColorFocusListener
{
   public void focusGained(FocusEvent event)
   {
      JTable table = (JTable) event.getSource();
      table.setSelectionBackground(Configuration.SELECTION_IN_FOCUS);
      table.repaint();  // you may not need this
   }

   public void focusLost(FocusEvent event)
   {
      JTable table = (JTable) event.getSource();
      table.setSelectionBackground(Configuration.SELECTION_OUT_FOCUS);
      table.repaint();  // you may not need this
   }
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
cathalmchaleAuthor Commented:
 i have got things working here now, but i want to do the same for a JTree!?  there is only a setSelectionBackground and not foreGround (as far as I can see!) - how do I work things in this case?
0
objectsCommented:
A FocusListener as I posted above should also work fine for a tree.
You could even change it slightly so the same class worked for both trees and tables.

0
cathalmchaleAuthor Commented:
>> http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTable.html#setSelectionForeground(java.awt.Color)

but thats for JTable not JTree!

.. >>same for a JTree!?  there is only a setSelectionBackground and not foreGround (as far as I can see!) -
?
0
objectsCommented:
Sorry, getting late in the day here :)

For a tree you'll need to adjust the colour using the renderer

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#setTextSelectionColor(java.awt.Color)
0
zzynxSoftware engineerCommented:
So cathalmchale, if you might wonder how to use that for your needs:

     ((DefaultTreeCellRenderer)yourTree.getCellRenderer()).setTextSelectionColor( ... );
and
     ((DefaultTreeCellRenderer)yourTree.getCellRenderer()).setSelectionColor( ... );
0
objectsCommented:
thats what I just said??
0
objectsCommented:
And you'd be better off creating your renderer instance instead of assuming that DefaultTreeCellRendereris being used. A lot safer that way.
0
cathalmchaleAuthor Commented:
>>  Sorry, getting late in the day here :)
I wish I could say the same!! ;)

Thanks, this is all sorted now!
0
zzynxSoftware engineerCommented:
>>You don't need a custom renderer
So cathalmchale, the renderer idea is back ;°)
0
zzynxSoftware engineerCommented:
>> Thanks, this is all sorted now!
Good to hear.
0
objectsCommented:
(:
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.