List selection is not happening in swing - java

HI, I've a JLIST and assigned it a cellRenderer. but i was not able select element in list. Actually it is selected but visually we can not see that it is selected means i was not able to see which item is selected in list.
Screen shot of my list:
and what is expected is
The second screen shot is without CellRenderer. But when i add CellRenderer i was not able to see the selected item in list.
is it normal behaviour that when you add CellRenderer to list.
what am i doing wrong ???
EDIT:-
this is my CellRenderer class:
public class ContactsRender extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
ImageIcon img;
public ContactsRender(){
setOpaque(true);
setIconTextGap(12);
setBackground(Color.WHITE);
setForeground(Color.black);
}
#Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if(value != null){
User user = (User) value;
String pres = user.getPresence().toLowerCase();
if(pres.contains("unavailable")){
img = new ImageIcon("res/offline.jpg");
} else {
img = new ImageIcon("res/online.jpg");
}
setText(user.getName());
setIcon(img);
return this;
}
return null;
}

You implemented your cell renderer incorrectly. The renderer is responsible for setting the renderer background to the selection color.
Read the JList API and follow the link to the Swing tutorial on "How to Use Lists" where you will find working examples that use a JList. You will also find a section on writing a renderer and an example.
Edit: Also, I just noticed you are reading your icon in the renderer code. You should never do this. The icon should only be read once when the renderer is created and then you cache the Icon. Every time a cell needs to be repainted the renderer is called so it is not efficient to keep reading the icon.

On your cell renderer, you have to implement the case for isSelected is true. For your ListCellRenderer :
Component getListCellRendererComponent(JList<? extends E> list,
E value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if (!isSelected) doThis(index);
else doThatForSelectedItem(index);
}

Related

Why doesn't my Combobox update its color properly?

I am implementing a dark mode into my program and everything works just fine, except a Combobox, which doesn't want to change its color as I want.
(source: bilder-upload.eu)
So as you can see, the "popup" of the Combobox changes the color just fine, but the Combobox itself doesn't. Also the Foreground color of the Combobox changes, but the background not.
I guess, the Look and Feel might cause the issue.
In my main-class:
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
Where I change to Darkmode:
TeamInterface.userFilterComboBox.setBackground( darkBackgroundColor );
TeamInterface.userFilterComboBox.setForeground( fontColor );
SwingUtilities.updateComponentTreeUI( TeamInterface.userFilterComboBox );
I have to use the updateComponentTreeUI-Method, because otherwise the "popup" also remains white.
If I remove the look and feel in my main-class, the combobox looks good,as you can see in this picture,
(source: bilder-upload.eu)
but I doesn't want to get rid of the system look and feel, so I tried to manually edit the UI of the combobox to metal with this code :
userFilterComboBox.setUI( new MetalComboBoxUI() );
but.. the result is just awful, even thoe theoretically (at leats thats what I think) it should look the same as without look and feel
(source: bilder-upload.eu)
The Combobox not is a component only to the background and the foreground but is the complex component.
An example:JComboBox is composed to:
ArrowButton
List of itme
Border (and it have a color)
the item selected
So for change all you can add inside your UIManager, all constant or you can define a new UIComponent.
So an PersonalComboBoxUI can the following:
/**
* #contributor https://github.com/vincenzopalazzo
*/
public class PersonalComboBoxUI extends BasicComboBoxUI {
public static ComponentUI createUI (JComponent c) {
return new PersonalComboBoxUI ();
}
#Override
public void installUI (JComponent c) {
super.installUI (c);
JComboBox<?> comboBox = (JComboBox<?>) c;
comboBox.setBackground (UIManager.getColor ("ComboBox.background"));
comboBox.setForeground (UIManager.getColor ("ComboBox.foreground"));
comboBox.setBorder (UIManager.getBorder ("ComboBox.border"));
comboBox.setLightWeightPopupEnabled (true);
}
#Override
protected JButton createArrowButton () {
Icon icon = UIManager.getIcon ("ComboBox.buttonIcon");
JButton button;
if (icon != null) {
button = new JButton (icon);
}
else {
button = new BasicArrowButton (SwingConstants.SOUTH);
}
button.setOpaque (true);
button.setBackground (UIManager.getColor ("ComboBox.buttonBackground"));
button.setBorder (BorderFactory.createLineBorder(Color.black));
return button;
}
#Override
protected ListCellRenderer createRenderer() {
return new MaterialComboBoxRenderer();
}
}
You should be defined also the PersonalComboBoxRenderer
/**
* #contributor https://github.com/vincenzopalazzo
*/
public class PersonalComboBoxRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JComponent component = (JComponent) super.getListCellRendererComponent (list, value, index, isSelected, cellHasFocus);
component.setBorder (BorderFactory.createEmptyBorder (5, 5, 5, 5));
component.setForeground (UIManager.getColor ("ComboBox.foreground"));
component.setBackground (isSelected || cellHasFocus ?
UIManager.getColor("ComboBox.selectedInDropDownBackground") :
UIManager.getColor("ComboBox.background"));
return component;
}
}
ps: in this case, I'm using the UIManager.put("ComboBox.background", COLOR) for add and stratification inside the JComponent.
So I want to add two information regarding if you using the personal color inside the UIManager or the PersonalComboBoxUI the color should be defined with this code
Color PINK_400 = new ColorUIResource (236, 64, 122);
because when you go to remove look and feel the color couldn't remove but if you used ColorUIResource the look and feel should be removed correctly.
To finish, if you do not have needed the default look and feel, I want to suggest you use a library.
The material-UI-swing has a system theming for creating the personal timing in your app and the all theme is personalizable.
This is the repo vincenzoapalazzo/material-ui-swing and atarw/material-ui-swing are the same repository and the same developer so, the vincenzopalazzo/material-us-swing is the developer branch, an contains more fix and test.
An example of the library is
.
Ps: I am the designer of the MaterialTheming System.

Changing the colour of elements in a List Box / List Model

If a room is in emergency mode then I would like to display it on the list box as red. My List box uses a List Model to display all of it's items.
GUI displaying the rooms
Is there anyway of looping through each element in the List Box to change the colour of its text?
Add a custom cell renderer. The example below is cribbed from here:
public class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
final static ImageIcon longIcon = new ImageIcon("long.gif");
final static ImageIcon shortIcon = new ImageIcon("short.gif");
// This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called.
public Component getListCellRendererComponent(
JList<?> list, // the list
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // does the cell have focus
{
String s = value.toString();
setText(s);
if (room.getMode() == RoomConstants.EMERGENCY_MODE) {
setForeground(Color.RED);
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
}
myList.setCellRenderer(new MyCellRenderer());
Hope that helped.

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);
}

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.

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

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?!

Categories