JList with ImageIcon

Hello,
Can I have JList with an ImageIcon beside it?e.g
"imageicon" "sometext"
code snippet would be helpful.
Thanks

Hello,
little improvement-update, custom ListCellRenderer now checks whether object is a String only or a JLabel with an ImageImage. You can use it for both versions of JLists.
import javax.swing.*;
import java.awt.*;
public class ImageTextList extends JFrame
     private static String[]text = new String[10];
     private static JLabel[]labels = new JLabel[text.length];
     private static ImageIcon[] icons = new ImageIcon[labels.length];
     static
          for(int i=0; i<text.length; i++)
               text[i]   = "Images " + (i+1);
               icons[i]  = new ImageIcon(     "../testproject/img/" + (i+1) + ".jpg");
               labels[i] = new JLabel(text, icons[i], JLabel.CENTER);
     public static void main(String[] args)
          new ImageTextList();
     public ImageTextList()
          super("Image+Text in a JList");
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //test with labels and text
          JList list = new JList(labels);
          list.setCellRenderer(new MyCellRenderer());
          getContentPane().add(new JScrollPane(list));
          pack();
          setLocationRelativeTo(null);
          setVisible(true);
     class MyCellRenderer extends JLabel implements ListCellRenderer
          private JLabel label = null;
          // This is the only method defined by ListCellRenderer.
          // We just reconfigure the JLabel each time we're called.
          public Component getListCellRendererComponent(
               JList list,
               Object value,
          // value to display
          int index, // cell index
          boolean isSelected, // is the cell selected
          boolean cellHasFocus) // the list and the cell have the focus
               String s = value.toString();
               ImageIcon icon = null;
               //checks whether the source is a label or another object(String only)
               if(value instanceof JLabel)
               {System.out.println("label");
                    label = (JLabel)value;
                    icon = (ImageIcon)label.getIcon();
                    s = label.getText();
               setText(s);
               setIcon(icon);
               if (isSelected)
                    setBackground(list.getSelectionBackground());
                    setForeground(list.getSelectionForeground());
               } else
                    setBackground(list.getBackground());
                    setForeground(list.getForeground());
               setEnabled(list.isEnabled());
               setFont(list.getFont());
               setOpaque(true);
               return this;
regards
Tim

Similar Messages

  • JList with aligned pictures

    What would be the best way to make a JList with a picture for each item?
    I have all the pictures loaded as ImageIcons btw.

    Write a custom list renderer, see http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/ListCellRenderer.html
    Then, to get the text aligned, you'll need to use the setIconTextGap method of JLabel. If the maximum icon width is 16 and your current icon is 13 pixels wide, then just set the icon-text-gab to 3.
    Something like this:
    import java.awt.*;
    import javax.swing.*;
    public class Dummy
         public static void main(String [] args)
              JList list = new JList(new Object[]{
                   new JLabel("small", new ImageIcon("d:/java/resources/java logo 16x16.png"), JLabel.LEFT),
                   new JLabel("large", new ImageIcon("d:/java/resources/java logo 32x32.png"), JLabel.LEFT)
              list.setCellRenderer(new MyCellRenderer());
              JFrame f = new JFrame();
              f.getContentPane().add(list);
              f.setSize(400,400);
              f.setVisible(true);
         static class MyCellRenderer extends JLabel implements ListCellRenderer
              public MyCellRenderer()
                   setOpaque(true);
              public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   JLabel label = (JLabel)value;
                   setText(label.getText());
                   setIconTextGap(4 + 32 - label.getIcon().getIconWidth());
                   setIcon(label.getIcon());
                   setBackground(isSelected ? Color.red : Color.white);
                   setForeground(isSelected ? Color.white : Color.black);
                   return this;

  • Populating JList with a single database column

    Hi all,
    I have the following code and i'm trying to popluate the JList with a particular colum from my MySQL Database..
    how do i go about doing it??
    Can some one please help
    import java.awt.*; import java.awt.event.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; public class RemoveD extends JDialog {     private JList list;     private JButton removeButton;     private JScrollPane scrollPane;     private Connection conn = null;     private Statement stat = null;         public RemoveD(Frame parent, boolean modal) {         super(parent, modal);         initComponents();     }     private void initComponents() {         scrollPane = new JScrollPane();         list = new JList();         removeButton = new JButton();         setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);         getContentPane().setLayout(new GridLayout(2, 0));         scrollPane.setViewportView(list);         getContentPane().add(scrollPane);         removeButton.setText("Remove");         removeButton.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent evt) {                 removeButtonActionPerformed(evt);             }         });         getContentPane().add(removeButton);         pack();         try {             Class.forName("com.mysql.jdbc.Driver");                    } catch (ClassNotFoundException ex) {             ex.printStackTrace();                    }         try {             String userID = "";             String psw = "";             String url;             url = "jdbc:mysql://localhost:3306/names";             conn = DriverManager.getConnection(url, userID, psw);             stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,                     ResultSet.CONCUR_READ_ONLY);             stat.close();             conn.close();         } catch (SQLException ex) {             ex.printStackTrace();         }     }     private void removeButtonActionPerformed(ActionEvent evt) {     }     public static void main(String args[]) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 RemoveD dialog = new RemoveD(new JFrame(), true);                 dialog.addWindowListener(new WindowAdapter() {                     public void windowClosing(WindowEvent e) {                         System.exit(0);                     }                 });                 dialog.setVisible(true);             }         });     } }

    I figured out how to do it

  • JTable/jlist with word wrapping cells?

    Hello all,
    I got a simple looking problem but i can't seem to find any working solution for it:
    A jtable or jlist with cells that wordwrap text (cells differ in height).
    I found many examples on groups.google and this forum but they all seem to suffer a 100% processor load when 2 or more cells differ in height.
    Can anyone point me to a working example?
    Kind regards,
    Twan

    Thanks! That's a real live saver.
    I had been looking for a solution for several days, strange google did not yet found the mentioned page, cause it contains usefull information.
    I've just implemented the multiline table and it works without any problems and most important without 100% cpu usage.
    The bucks are comming your way ;-)

  • Populatin a JList with elements from a DB (access here)

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

  • Resizing a JList with variable row heights, not updating the "picture"

    Firstly I would like to apologize for posting this Swing question here, but I was unable to find the Swing category, if someone could direct me to that I would be most grateful.
    Ok, so in abstract what I am trying to do is have a JList with resizable rows to act as a row header for a JTable (exactly like the row headers in OO Calc or MS Excel).
    What I have is a RowHeaderRenderer:
    public class RowHeaderRenderer extends JLabel implements ListCellRendererand it has a private member:
    private Vector<Integer>        _rowHeights            = new Vector<Integer>();which contains a list of all the variable row heights.
    Then there is my getListCellRendererComponent method:
        public Component getListCellRendererComponent(    JList         list,
                                                          Object        value,
                                                          int           index,
                                                          boolean       isSelected,
                                                          boolean       cellHasFocus)
            // Make sure the value is not null
            if(value == null)
                this.setText("");
            else
                this.setText(value.toString());
            // This is where height of the row is actually changed
            // This method is fed values from the _rowHeights vector
            this.setPreferredSize(new Dimension(this.getPreferredSize().width, _rowHeights.elementAt(index)));
            return this;
        }And then I have a row header:
    public class RowHeader extends JList implements TableModelListener, MouseListener, MouseMotionListenerand you may be interested in its constructor:
        public RowHeader(JTable table)
            _table = table;
            _rowHeaderRenderer = new RowHeaderRenderer(_table);
            this.setFixedCellWidth                        (50);
            this.setCellRenderer                        (_rowHeaderRenderer);
            // TODO: grab this value from the parent view table
            JScrollPane panel = new JScrollPane();
            this.setBackground(panel.getBackground());
            this.addMouseMotionListener                    (this);
            this.addMouseListener                        (this);
            this.setModel                                (new DefaultListModel());
            table.getModel().addTableModelListener        (this);
            this.tableChanged                            (new TableModelEvent(_table.getModel()));
        }and as you can see from my mouse dragged event:
        public void mouseDragged(MouseEvent e)
            if(_resizing == true)
                int resizingRowHeight = _rowHeaderRenderer.getRowHeight(_resizingRow);
                _rowHeaderRenderer.setRowHeight(_resizingRow, resizingRowHeight + (e.getPoint().y - _cursorPreviousY));
                _cursorPreviousY = e.getPoint().y;  
        }all I am doing is passing the rowHeaderRenderer the values the currently resizing row should be, which works fine. The values are being changed and are accurate.
    The issue I am having is that while this dragging is going on the row does not appear to be resizing. In other words the "picture" of the row remains unchanged even though I change the values in the renderer. I tried calling:
    this.validate();and
    this.repaint();at the end of that mousedDragged method, but to no avail, neither of them worked.
    Again, I verified that I am passing the correct data in the RowHeaderRenderer.
    So, anyone have any ideas how I should get the image of the RowHeader (JList) to update after calling my MouseDragged event?
    Thank you for your time,
    Brandon

    I was able to fix this some time ago. Here is the solution:
         public void mouseDragged(MouseEvent e)
              if(_resizing == true)
                   int newHeight = _previousHeight + (e.getPoint().y - _cursorPreviousY);
                   if(newHeight < _minRowHeight)
                        newHeight = _minRowHeight;
                   _rowHeaderRenderer.setRowHeight(_resizingRow, newHeight);
                   _table.setRowHeight(_resizingRow, newHeight);
              this.updateUI();
         }

  • Synchronize JList with JScrollPane

    hi all,
    I want to automatically move the scroll in the JScrollPane when I change the selected position in the JList with setSelectedIndex, right now the list is correctly selected, but the scroll remains on the top, how could I move it to position the list to see the selected item?
    thanks!
    mykro

    JComponent has a scrollRectToVisible method you could use along with JList's getCellBounds method. Maybe register a ListSelectionListener with the list, then in valueChanged get the newly selected cell's bounds from getCellBounds and call scrollRectToVisible on the JList with the cell bounds.

  • Traversing JList with arrow keys

    I've got a small problem when i try to traverse a JList with the arrow keys. When I'm at the first index of the list and press the UP arrow, I want to select the last index of the list.
    switch (keyCode){
            case VK_UP:
                    if(list.isSelectedIndex(list.getFirstVisibleIndex()))
                        list.setSelectedIndex(list.getLastVisibleIndex());
                    break;
    }When I use this code, the program selects the second last index (not the last). How can I fix this problem?
    Any suggestions will be appreciated.

    I found this thread useful but ultimately solved this another way using key binds. Maybe someone will find this useful.
    public MyDialogConstructor() {
        bindKeys();
    private void bindKeys() {
              InputMap inputMap = getJList().getInputMap(JComponent.WHEN_FOCUSED);
              KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
              inputMap.put(key, "jlist:UP");
              getJList().getActionMap().put("jlist:UP", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getFirstVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getLastVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() - 1);
              key = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
              inputMap.put(key, "jlist:DOWN");
              getJList().getActionMap().put("jlist:DOWN", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getLastVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getFirstVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() + 1);
         }

  • JList with Images for solitaire?

    could i use JList with gif images of cards for Solitaire(klondike)? if i have 7 vertical panes and one JList in each pane? or is this impossible?

    but that solution didnt work for me1) Where in the posting did you state that?
    2) if it doesn't work then you are doing something wrong.
    I think you have a better chance with your original approach. I don't see how a JList would work.

  • JList with LineBorder think=2

    hello all
    i am writing a look and feel .
    and when i have a JList with LineBorder with thinness = 2 and a item is selected ,
    i cant see the complete text of the selected item
    my question is there a simple way to make this work
    without changing the list preferred size inside my application ?
    thank you
    here is an example
    (please select the third item 'ccccccccccccccc')
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.border.LineBorder;
    public class DialogTest extends JDialog{
      public DialogTest(JFrame f){
        super(f);
        JList list = new JList(new String[]{"aaaaaaaaaaaa" ,"bbbbbbbbbbbbbbb" ,"cccccccccccccccccc"});
        list.setCellRenderer(new DefaultListCellRenderer(){
          public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if(isSelected){
              setBorder(new LineBorder(Color.GREEN ,2));
            }else{
              setBorder(null);
            setText(value.toString());
            return this;
        setLayout(new BorderLayout());
        add(new JScrollPane(list) ,BorderLayout.CENTER);
        pack();
      public static void main(String[] args){
        DialogTest t = new DialogTest(new JFrame());
        t.setVisible(true);
    }

    ok, thanks now this works on the demo also for me.
    but when settings my UI ,i get same result
    i want this border no mater what Render the user will put
    this is what i do
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.ComponentOrientation;
    import java.awt.Graphics;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JComponent;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    import javax.swing.ListSelectionModel;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.basic.BasicListUI;
    import org.jtpc.gui.borders.RoundBorder;
    import org.jtpc.gui.defaultTheme.FocusBorderHandler;
    import org.jtpc.utils.JTPCThemeManager;
    public class JTPCListUI extends BasicListUI{
      public void installUI(JComponent c){
        super.installUI(c);
        if(c instanceof JList){
          JList listJtpc = (JList)c;
          listJtpc.setCellRenderer(new JTPCListCellRenderer());
      public static ComponentUI createUI(JComponent c) {
        return new JTPCListUI();
      LineBorder m_borderSelected     = new LineBorder (Color.GREEN ,3);
      EmptyBorder m_borderDeselected  = new EmptyBorder(new Insets(3, 3, 3, 3));
       * COPY PASTE CODE FROM PARENT 'BasicListUI' ,IN JAVA VERSION  jdk1.6.0_18
       * Paint one List cell: compute the relevant state, get the "rubber stamp"
       * cell renderer component, and then use the CellRendererPane to paint it.
       * Subclasses may want to override this method rather than paint().
       * @see #paint
      protected void paintCell(
          Graphics g,
          int row,
          Rectangle rowBounds,
          ListCellRenderer cellRenderer,
          ListModel dataModel,
          ListSelectionModel selModel,
          int leadIndex)
        Object value = dataModel.getElementAt(row);
        boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
        boolean isSelected = selModel.isSelectedIndex(row);
        Component rendererComponent = cellRenderer.getListCellRendererComponent(list, value, row, isSelected, cellHasFocus);
        FocusBorderHandler h = new FocusBorderHandler();
        if(isSelected){
          ((JComponent)rendererComponent).setBorder(m_borderSelected);
        }else{
          ((JComponent)rendererComponent).setBorder(m_borderDeselected);
        int cx = rowBounds.x;
        int cy = rowBounds.y;
        int cw = rowBounds.width;
        int ch = rowBounds.height;
        boolean isFileList = Boolean.TRUE.equals(list.getClientProperty("List.isFileList"));
        if (isFileList) {
          // Shrink renderer to preferred size. This is mostly used on Windows
          // where selection is only shown around the file name, instead of
          // across the whole list cell.
          int w = Math.min(cw, rendererComponent.getPreferredSize().width + 4);
          if (!(list.getComponentOrientation() == ComponentOrientation.LEFT_TO_RIGHT)) {
            cx += (cw - w);
          cw = w;
        rendererPane.paintComponent(g, rendererComponent, list, cx, cy, cw, ch, true);
      class JTPCListCellRenderer extends DefaultListCellRenderer {
        public  Component   getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
          setText(value.toString());
          return this;
    }Edited by: shay_te on 17:34 15/05/2010

  • JList with Checkboxes

    For my application, I require a JList with each row containing a text label, and two check boxes which can be checked or unchecked in the list. I have written the code below to render list elements in this way, however the checkboxes cannot be checked in the list. Is there something else that I have to do to enable this?
    Code:
    public class NodeListCellRenderer implements ListCellRenderer {
          * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList,
          *      java.lang.Object, int, boolean, boolean)
         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                   boolean cellHasFocus) {
              //Convert Value to node
              final Node n=(Node)value;
              //Create JPanel object to hold list element
              JPanel listElement=new JPanel();
              listElement.setLayout(new GridLayout(1,3));
              //Create Label to hold node name
              JLabel nodeName=new JLabel(n.toString());
              //Create checkbox to control trace
              final JCheckBox traceBox=new JCheckBox("Trace",n.isTraceEnabled());
              //Add Event Listener
              traceBox.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        n.setTrace(traceBox.isSelected());
              //Create Checkbox to control
              final JCheckBox failedBox=new JCheckBox("Failed",n.hasFailed());
              //Add Event Listener
              failedBox.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        n.setFailed(failedBox.isSelected());
              //Colour All Components Grey if Selected
              if (isSelected) {
                   nodeName.setBackground(Color.LIGHT_GRAY);
                   failedBox.setBackground(Color.LIGHT_GRAY);
                   traceBox.setBackground(Color.LIGHT_GRAY);
                   listElement.setBackground(Color.LIGHT_GRAY);
              //Build List Element
              listElement.add(nodeName);
              listElement.add(traceBox);
              listElement.add(failedBox);
              return listElement;
    }

    Thanks for the pointer to that. I have created a mouse listener for my list, which in a very crude way is able to set the checkbox values on a list click, by changing the underlying objects that are stored in the list.
    The problem that I'm having now is that if I click a checkbox in the currently selected list element, the value in the underlying object is set immediately, but the Checkbox does not update until i select another element in the list.
    This seems to indicate that the getListCellRendererComponent method is not called when you click on the currently selected list element. Is there any way round this?
    Here's my current mouse listener code:
    list.addMouseListener(new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                        //get index of element clicked
                        int index=list.locationToIndex(e.getPoint());
                        //Get Element at Index
                        Node n=(Node)list.getModel().getElementAt(index);
                        /*Work out X position, if 33-66% of width, "trace" checkbox clicked
                        otherwise if >66% of width, "failed" checkbox clicked*/
                        if (e.getX()>(list.getWidth()*0.33) && (e.getX()<list.getWidth()*0.66)) {
                             n.setTrace(!n.isTraceEnabled());
                             list.revalidate();
                        } else if (e.getX()>(list.getWidth()*0.33)) {
                             n.setFailed(!n.hasFailed());
                             list.revalidate();
              });

  • JList with few imageIcon

    I need a few imageIcon in a single JList. I was trying to get help from "The Java Tutorial" but failed.
    If someone know please tell me the method.
    Thanks in advance.

    There is no trick to doing this. You simply add multiple ImageIcons to the ListModel.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JList with JLabels

    I'm a final year university student working on a major project for my degree and I'm really struggling with the GUI for the application. I'd really appreciate it if someone could help me out here.
    I'm trying to make a JList of JLabels. I don't know whether this is possible but heres the jist of my code :
    Vector listContents = new Vector();
    JList list = new JList(listContents);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane listScrollPane = new JScrollPane(list);
    ImageIcon icon = new ImageIcon(fyp.MainFrame.class.getResource("image.png"));
    ImageIcon icon2 = new ImageIcon(fyp.MainFrame.class.getResource("image.png"));
    JLabel lab = new JLabel("Test");
    lab.setIcon(icon);
    JLabel lab2 = new JLabel("Test 2");
    lab2.setIcon(icon2);
    listContents.add(lab);
    listContents.add(lab2);If I use strings instead of labels it works fine. However, I want to have icons next to each string in the list.
    Can anyone help with this? If this won't work at all, is there another way I should make a list of strings with an icon to the left of each entry?

    I'm afraid I can't seem to use this information to
    help me, the examples go into too much detail with
    custom data models and whatever which really isn't
    what I want to do.That may not be what you want to do, but it's what you have to do.
    I simply want to display an icon next to the string of
    the list entry.
    I'd be really greatful if you guys could give me a
    straightforward way of doing this - I'm terrible with
    Swing and its pretty difficult for me to understand
    these previous examples :(Those examples ARE the straightforward way of doing it. Go to the API documentation for JList and hit the page-down key three times. There's the example you need. It's got setIcon() in it, what else do you need?

  • Help with ImageIcon

    Hi,
    I'm giving Java another try and I'm working through the short courses and Magercises. I'm having a problem with the code below.
    <pre>
    package examples.myapps.test;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FirstSwing extends JFrame {
    // The initial width and height of the frame
    public static int WIDTH = 300;
    public static int HEIGHT = 300;
    // images for buttons
    public Icon bee = new ImageIcon("bee.gif");
    public Icon dog = new ImageIcon("dog.gif");
    public FirstSwing(String lab) {
    super(lab);
    JButton top = new JButton("A bee", bee);
    top.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("bee");
    JButton bottom = new JButton("and a dog", dog);
    bottom.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("dog");
    top.setMnemonic (KeyEvent.VK_B);
    bottom.setMnemonic (KeyEvent.VK_D);
    Container content = getContentPane();
    content.setLayout(new GridLayout(2,1));
    content.add(top);
    content.add(bottom);
    public static void main(String args[]) {
    FirstSwing frame = new FirstSwing("First Swing Stuff");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
    </pre>
    The problem is that the icons don't appear. The image files (bee.gif and dog.gif) are in the same directory as the source file. I get no errors, the images just do not appear in the button like they are supposed to according to the example. What am I doing wrong?
    Thanks,
    Mike

    I had the same problem with ONE STUDIO 4 trying the example below ... the image is in the same directory as the class is and it�s ok ... it only work fine if I set the full absolute path, but not with a relative one ....
    But I tryed the same example in the same dir with Jbuider 3 ... and it works fine and the ImageIcon appears .... I think it�s something related to Filesystems in the Studio One ....
    Jo�o Carlos
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class LabelTest extends JFrame {
    private JLabel label1, label2, label3;
    public LabelTest()
    super( "Testing JLabel" );
    Container c = getContentPane();
    c.setLayout( new GridLayout(3,1) );
    // JLabel constructor with a string argument
    label1 = new JLabel( "Label with text" );
    label1.setToolTipText( "This is label1" );
    c.add( label1 );
    // JLabel constructor with string, Icon and
    // alignment arguments
    //Icon bug = new ImageIcon( "C:\\Documents and Settings\\Administrador\\examples\\ch12\\fig12_04\\bug1.GIF" );
    Icon bug = new ImageIcon( "bug1.GIF" );
    label2 = new JLabel( "Label with text and icon",
    bug, SwingConstants.LEFT );
    label2.setToolTipText( "This is label2" );
    c.add( label2 );
    // JLabel constructor no arguments
    label3 = new JLabel();
    label3.setText( "Label with icon and text at bottom" );
    label3.setIcon( bug );
    label3.setHorizontalTextPosition(
    SwingConstants.CENTER );
    label3.setVerticalTextPosition(
    SwingConstants.BOTTOM );
    label3.setToolTipText( "This is label3" );
    c.add( label3 );
    setSize( 275, 170 );
    show();
    public static void main( String args[] )
    LabelTest app = new LabelTest();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    if your source is in
    C:\foo\examples\myapps\test
    put the gifs in
    C:\fooThanks, but this isn't working either. My source is
    in:
    c:\java-ide\sampledir\examples\myapps\test.
    I've placed the gifs in c:\java-ide,
    c:\java-ide\sampledir, c:\java-ide\sampledir\examples,
    etc. (all directories) and nothing shows the gifs in
    the buttons. Any ideas?

  • Japplet with imageicon

    Hi, im working on a simple paint program in a Japplet. I'm stuck right now on getting an icon on a button by giving the ImageIcon constructor a file path. I get an error when I try to run the applet with the imaging code in, not without.
    I've read in a few places that this won't work for general applets or jar files. Is there anyway that i can get it to load from my computer without resorting to having to load the .gif files from a internet site?
    // i have this (which doesn't work)
          JButton draw = new JButton(new ImageIcon("images/0.gif"));
          draw.addActionListener(canvas);
          toolsPanel.add(draw);
    //as compared to this (which does without an image)
          JButton line = new JButton("Line");        
          line.addActionListener(canvas);            
          toolsPanel.add(line);

    JButton draw = new JButton(new ImageIcon(new java.net.URL(getCodeBase(),"images/0.gif")));

Maybe you are looking for