How to add image in jlist - java

Hi i have created a j list and there i want to add an image before any text in that text how can i do this i tried but i am not able to achieve my goal i want to add an image before list element"Barmer".
public class ListDemo extends JPanel
implements ListSelectionListener {
private JList list;
private DefaultListModel listModel;
public ListDemo() {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("Barmer");
//Create the list and put it in a scroll pane.
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
list.setVisibleRowCount(5);
list.setBackground(new java.awt.Color(0,191,255));;
list.setFont(new Font("Arial",Font.BOLD,35));
list.setForeground( Color.white );
list.setFixedCellHeight(60);
list.setFixedCellWidth(50);
list.setBorder(new EmptyBorder(10,20, 20, 20));
JScrollPane listScrollPane = new JScrollPane(list);
add(listScrollPane, BorderLayout.CENTER);
}
public void valueChanged(ListSelectionEvent e) {
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ListDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ListDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
How can i do this help me?
Thanks in advance

You want to look as a custom ListCellRenderer. You can look at Provding a Custom Renderer for JComboBox. It the same for a JList. The tutorial over-complicates a bit for simple scenarios. They extends JLabel and implements ListCellRender where you have to implement a few unnecessary things if you just want basic functionality but with am image.
You can just instead extends or create a anonymous DefaultListCellRender and just get the JLabel render component and add to it, like setting Font and ImageIcon. Something like this
public class MarioListRenderer extends DefaultListCellRenderer {
Font font = new Font("helvitica", Font.BOLD, 24);
#Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
label.setIcon(imageMap.get((String) value));
label.setHorizontalTextPosition(JLabel.RIGHT);
label.setFont(font);
return label;
}
}
What happens is that each cell uses this renderer and calls the getListCellRendererComponent method. The value you see passed to the method is the value in each cell, in my case, one of the character names in the list. I then map that to the corresponding ImageIcon and set the Icon on the JLabel renderer component.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class MarioList {
private final Map<String, ImageIcon> imageMap;
public MarioList() {
String[] nameList = {"Mario", "Luigi", "Bowser", "Koopa", "Princess"};
imageMap = createImageMap(nameList);
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MarioListRenderer extends DefaultListCellRenderer {
Font font = new Font("helvitica", Font.BOLD, 24);
#Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
label.setIcon(imageMap.get((String) value));
label.setHorizontalTextPosition(JLabel.RIGHT);
label.setFont(font);
return label;
}
}
private Map<String, ImageIcon> createImageMap(String[] list) {
Map<String, ImageIcon> map = new HashMap<>();
for (String s : list) {
map.put(s, new ImageIcon(
getClass().getResource("/marioscaled/" + s + ".png")));
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MarioList();
}
});
}
}
Side Note
AndrewThompson is correct about just checking the tutorial first. You could have easily found an example implementation, then tried it out. Swing tutorials can be found here. Look under the Using Swing Components for how to use different components.
Swing apps should be run on the Event Dispatch Thread (EDT). You can do so by wrapping your creatAndShowGui() in a SwinUtilities.invokeLater.... See more at Initial Threads
UPDATE with internet images.
new Code
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class MarioList {
private final Map<String, ImageIcon> imageMap;
public MarioList() {
String[] nameList = {"Mario", "Luigi", "Bowser", "Koopa", "Princess"};
imageMap = createImageMap(nameList);
JList list = new JList(nameList);
list.setCellRenderer(new MarioListRenderer());
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(300, 400));
JFrame frame = new JFrame();
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class MarioListRenderer extends DefaultListCellRenderer {
Font font = new Font("helvitica", Font.BOLD, 24);
#Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
label.setIcon(imageMap.get((String) value));
label.setHorizontalTextPosition(JLabel.RIGHT);
label.setFont(font);
return label;
}
}
private Map<String, ImageIcon> createImageMap(String[] list) {
Map<String, ImageIcon> map = new HashMap<>();
try {
map.put("Mario", new ImageIcon(new URL("http://i.stack.imgur.com/NCsHu.png")));
map.put("Luigi", new ImageIcon(new URL("http://i.stack.imgur.com/UvHN4.png")));
map.put("Bowser", new ImageIcon(new URL("http://i.stack.imgur.com/s89ON.png")));
map.put("Koopa", new ImageIcon(new URL("http://i.stack.imgur.com/QEK2o.png")));
map.put("Princess", new ImageIcon(new URL("http://i.stack.imgur.com/f4T4l.png")));
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MarioList();
}
});
}
}

Related

How to change font of JComboBox

I want to change the font size of my JComboBox.
However only not selected item are change, like that :
https://imgur.com/a/WnnyPA6
So I want that selected item are also bold.
I done a custom combobox classe like that :
public class CustomComboBox extends JLabel implements ListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel label = new JLabel(){
public Dimension getPreferredSize(){
return new Dimension(200, 80);
}
};
label.setText(String.valueOf(value));
label.setFont(new Font("Serif", Font.BOLD, 30));
return label;
}
}
You can simply set font for combo box. Something like this:
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
/**
* <code>ComboTest</code>.
*/
public class ComboTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ComboTest()::startUp);
}
private void startUp() {
JComboBox<String> combo = new JComboBox<>(new String[] {"A", "B", "C"});
combo.setFont(new Font("Serif", Font.BOLD, 30));
combo.setRenderer(new ComboRenderer());
JFrame frm = new JFrame("Combo test");
frm.add(combo);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private static class ComboRenderer extends BasicComboBoxRenderer {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 80);
}
}
}
When my suggstion is not helpful in your case please create a small runnable example, so we can also start and debug it.
You can set font for Combo box by using
combo.setFont(new FontUIResource("Roboto",Font.PLAIN,12);

how to add a checkbox into JList (java netbeans)?

I have added a checkbox into JList its working successfully but problem is it not select multiple checkbox in same time and the multi-selection code for checkbox not working and I also add the image.
lstsubsub.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
public class CheckboxListCellRenderer extends JCheckBox implements
ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
setComponentOrientation(list.getComponentOrientation());
setFont(list.getFont());
setBackground(list.getBackground());
setForeground(list.getForeground());
setSelected(isSelected);
setEnabled(list.isEnabled());
setText(value == null ? "" : value.toString());
return this;
}
}
Don't use a JList for the JCheckBoxes... Use a JPanel with GridLayout like so:
import java.awt.GridLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
private final JCheckBox checkReg, checkPerm, checkAcc;
public Main() {
super(new GridLayout(0, 1)); //1 column, any number of rows...
super.add(checkReg = new JCheckBox("User Registration"));
super.add(checkPerm = new JCheckBox("User Permission"));
super.add(checkAcc = new JCheckBox("User Accounts"));
}
public static void main(final String[] args) {
final JFrame frame = new JFrame("List of checkboxes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Main());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

custom JList Cell Renderer - Cell Selection?

Good day.
I'm pretty new to CellRenderer and stuff and I am still reading a lot about it. Right now, I'm stuck with something I'm not sure how to work. I was able to put a JPanel inside my JList by setting it's CellRenderer to a custom one. But here is the million dollar question: How can I interact with the controls?
I mean, I want to be able to right click into the cell that contains my jPanel,
Right click to show some actions, and Highlight the selected row.
How can I achieve this?
heres is my code:
import java.awt.CardLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class cellTest extends JPanel{
JLabel label;
public cellTest(){
buildInterface();
}
private void buildInterface(){
label = new JLabel();
setLayout(new CardLayout());
add(label);
}
public void setText(String text){
String pre = "<html><body style='width: 200px;'>";
label.setText(pre+text);
}
}
Second Part:
import Read.Medicine_Cell;
import java.awt.CardLayout;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class testjava {
public static void main(String args[]){
JFrame jf = new JFrame();
jf.setSize(500, 500);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new CardLayout());
JList list = new JList();
DefaultListModel dlm = new DefaultListModel();
dlm.addElement("This is a test");
dlm.addElement("I wanna know if it works");
dlm.addElement("Pardon if im not that good yet");
dlm.addElement("or my problem is basic");
list.setModel(dlm);
list.setCellRenderer(new MyCellRenderer());
jf.add(new JScrollPane(list));
jf.show();
}
static class MyCellRenderer extends DefaultListCellRenderer{
final cellTest cellx = new cellTest();
#Override
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean hasFocus){
final String text = (String) value;
cellx.setText(text);
return cellx;
}
}
}

Change color of selection (after selection) in a JComboBox

I'm writing a GUI using Swing. I have a custom written JComboBox using a ListCellRenderer and a BasicComboBoxEditor.
In my getListCellRendererComponent() method I change the color of the the list based on whether the item is "selected" (mouse is hovering above), which is nice and all, but I don't want the selection to change background color once a choice is made, which it currently does.
The first picture shows how the interface looks before a selection is made, and the second one shows how it looks after.
QUESTION
How do I change the background of the "selection" to the "stockColor"?
MCVE
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.plaf.basic.BasicComboBoxEditor;
public class TFComboBox extends JComboBox{
public static void main(String[] args){
createAndShowGUI();
}
public static void createAndShowGUI(){
JFrame frame = new JFrame("MCVE");
JPanel pane = new JPanel(new BorderLayout());
TFComboBox cb = new TFComboBox();
boolean[] tf = {true, false};
cb.addItems(tf);
JButton b = new JButton("Click me!");
pane.add(cb, BorderLayout.CENTER);
pane.add(b, BorderLayout.LINE_END);
frame.add(pane);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private DefaultComboBoxModel model;
private Vector<Boolean> comboBoxItems;
private JComboBox comboBox;
public TFComboBox(){
comboBoxItems = new Vector<Boolean>();
comboBoxItems.add(Boolean.TRUE);
comboBoxItems.add(Boolean.FALSE);
comboBox = new JComboBox(comboBoxItems);
model = new DefaultComboBoxModel();
setModel(model);
setRenderer(new TrueFalseComboRenderer());
setEditor(new TrueFalseComboEditor());
}
public void addItems(boolean[] items){
for(boolean anItem : items){
model.addElement(anItem);
}
}
}
class TrueFalseComboRenderer extends JPanel implements ListCellRenderer {
private JLabel labelItem = new JLabel();
private Color stockColor = labelItem.getBackground();
public TrueFalseComboRenderer(){
setLayout(new BorderLayout());
labelItem.setOpaque(true);
labelItem.setHorizontalAlignment(JLabel.CENTER);
add(labelItem);
setBackground(Color.LIGHT_GRAY);
}
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
boolean tempValue = (boolean) value;
labelItem.setText(Boolean.toString(tempValue));
if(isSelected){
labelItem.setBackground(stockColor.darker());
labelItem.setForeground(Color.WHITE);
} else {
labelItem.setBackground(stockColor);
labelItem.setForeground(Color.BLACK);
}
return this;
}
}
class TrueFalseComboEditor extends BasicComboBoxEditor {
private JLabel labelItem = new JLabel();
private JPanel panel = new JPanel();
private Object selectedItem;
public TrueFalseComboEditor() {
labelItem.setOpaque(false);
labelItem.setHorizontalAlignment(JLabel.CENTER);
labelItem.setForeground(Color.WHITE);
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 2));
panel.setBackground(Color.BLUE);
panel.add(labelItem);
}
public Component getEditorComponent(){
return this.panel;
}
public Object getItem(){
return this.selectedItem;
}
public void setItem(Object item){
if(item == null){
return;
}
this.selectedItem = item;
labelItem.setText(item.toString());
}
}
EDIT
I've added a MCVE and as you can see it is the "problem" that the JComboBox is focused that has to do with my issue. I've placed a button next to the ComboBox to help with removing the focus from the ComboBox.
Simply doing a setFocusable(false) would fix it, but also take away some of the functionality of the rest of the program, so this is not desired.
for better help sooner post an SSCCE / MCVE, short, runnable, compilable, with hardcoded value for JComboBox / XxxComboBoxModel in local variable
JList has Boolean array implemented as default in API (no idea whats hidden in
String trueFalseItem = Boolean.toString(tempValue); and with value stored JComboBox model)
this is just code minimum to test isSelected and to change JList.setSelectionXxx inside DefaultListCellRenderer
for example (code in SSCCE / MCVE form)
.
.
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class ComboBoxBooleanModel {
private javax.swing.Timer timer = null;
private Vector<Boolean> comboBoxItems;
private JComboBox box;
public ComboBoxBooleanModel() {
comboBoxItems = new Vector<Boolean>();
comboBoxItems.add(Boolean.TRUE);
comboBoxItems.add(Boolean.FALSE);
box = new JComboBox(comboBoxItems);
box.setRenderer(new 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 (c instanceof JLabel) {
JLabel l = (JLabel) c;
if (Boolean.TRUE.equals(value)) {
l.setBackground(Color.RED);
if (isSelected) {
list.setSelectionForeground(Color.RED);
list.setSelectionBackground(Color.BLUE);
}
} else if (Boolean.FALSE.equals(value)) {
l.setBackground(Color.BLUE);
if (isSelected) {
list.setSelectionForeground(Color.BLUE);
list.setSelectionBackground(Color.RED);
}
}
return l;
}
return c;
}
});
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(box);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
box.setSelectedIndex(1);
}
});
start();
}
private void start() {
timer = new javax.swing.Timer(2250, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (box.getSelectedItem() == (Boolean) false) {
box.setSelectedItem((Boolean) true);
} else {
box.setSelectedItem((Boolean) false);
}
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboBoxBooleanModel comboBoxModel = new ComboBoxBooleanModel();
}
});
}
}
Here is a short demo of 2 JCombos, one of which will not change its background color when selected :
public static void main(String[] args){
JFrame frame = new JFrame("Combos BG Color test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().setPreferredSize(new Dimension(400, 40));
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1,2));
frame.add(mainPanel);
JComboBox<String> aCombo = new JComboBox<>(new String[]{"A","B","C"});
mainPanel.add(aCombo);
JComboBox<String> bCombo = new JComboBox<>(new String[]{"1","2","3"});
Color bgColor = bCombo.getBackground();
bCombo.setRenderer(new DefaultListCellRenderer() {
#Override
public void paint(Graphics g) {
setBackground(bgColor);
super.paint(g);
}
});
mainPanel.add(bCombo);
frame.pack();
frame.setVisible(true);
}
(Most of the credit goes to this answer)

Making JComboBox transparent

I have a problem with making JComboBox transparent. I tried setting opaque to false and alpha of background 0 but it doesnt work. I guess that i need to change some class that does rendering or something similar.And here is the code..
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboBoxUI;
import java.awt.Color;
public class App {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App window = new App();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.GREEN);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setBounds(149, 99, 155, 20);
comboBox.setOpaque(false);
//comboBox.setBackground(new Color(0,0,0,0));
((JTextField)comboBox.getEditor().getEditorComponent()).setOpaque(false);
comboBox.setUI(new BasicComboBoxUI(){
public void paintCurrentValueBackground(Graphics g,Rectangle bounds,boolean hasFocus){}});
frame.getContentPane().add(comboBox);
}
}
Assuming you just want the ComboBox's text field transparent (not the popup as well), using the following code should work. You need to mess with the ComboBox renderer instead of the editor. The editor is used for if you can type into the ComboBox; The renderer is used if the ComboBox is a list of values only.
comboBox.setOpaque(false);
comboBox.setRenderer(new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JComponent result = (JComponent)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
result.setOpaque(false);
return result;
}});
JComboBox myComboBox = new JComboBox(array);
myComboBox .setOpaque(false);
myComboBox .setEditable(true);
JTextField boxField = (JTextField)myComboBox .getEditor().getEditorComponent();
boxField.setBorder(BorderFactory.createEmptyBorder());
boxField.setBackground(new Color(0, 0, 0, 0));
boxField.setFocusable(false);
The answer is in http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6687960
You need to preset this few things
jcombo.setOpaque(false);
jcombo.setContentAreaFilled(false);
jcombo.setBorderPainted(false);
try this.
yourComboBox.setOpaque(false);
((JTextField)yourComboBox.getEditor().getEditorComponent()).setOpaque(false);
setUI(new BasicComboBoxUI() {
#Override
public void paintCurrentValueBackground(
Graphics g, Rectangle bounds, boolean hasFocus) {
}
});

Categories