I need to make bold a row in a JList component to show the active row. It should be done dynamically to let user see the change in the active row immediately. How can I do this?
Asked
Active
Viewed 934 times
2 Answers
5
Take a look on CustomCellRenderer in your renderer you could change the color of the presented label based on isSelected argument.

AlexTheo
- 4,004
- 1
- 21
- 35
-
I created a `CustomCellRenderer` and also created a mothod in it to set the index of bold row (so renderer can understand which one should Be bolded) then i assigned it to my JList. but when i call my method (`((boldCellrenderer)jList1.getCellRenderer()).SetBoldedIndex(boldIndex);`) it doesn't update view until i do something like clicking on another row. i tried to call `updateUI()` in my setter method and it worked, is this the correct way or i should do something else? – Ariyan Dec 05 '11 at 19:37
-
here is an simple example of using it. https://github.com/alekstheod/Promasi-V2/blob/master/org.promasi.client_swing/src/org/promasi/client_swing/components/JList/MenuCellRenderer.java Component getListCellRendererComponent will be called each time when you need to redraw a current cell. So in case if isSelected is true you have to change a color of your label and return it, otherwise change a color to white. – AlexTheo Dec 05 '11 at 19:56
-
@AlexTheo: But my problem is that i have a JList and a JButton. User can select any item in JList and nothing should be done; but when user clicks JButton the active (selected) item in JList should be stored as current value and be bolded. – Ariyan Dec 05 '11 at 20:13
-
1HHHmm I did it with an new class (Entry) which contain an boolean variable that show us if it is selected and and an object which store your real entry. So instead of your object you will pass the Entry instance which contains your object and this boolean variable. After you will be able to check if the entry was selected by checking the boolean var in your CustomCellRenderer. – AlexTheo Dec 05 '11 at 20:24
2
Just in case you want to change the Color of the selected item you can use:
list.setSelectionForeground(Color.RED);
there is another similar API for setting background of selected item:
list.setSelectionBackground(Color.BLUE);

mprabhat
- 20,107
- 7
- 46
- 63