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

Similar Messages

  • 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.

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

  • HT204382 hi , i have this extension .f4v  ,and i couldn't match it with any think please help me , thank u

    hi , i have this extension .f4v  ,and i couldn't match it with any think please help me , thank u

    http://en.wikipedia.org/wiki/Flash_Video

  • Why won't OS X Mavericks start downloading when I click the download button? It thinks and acts like it starts downloading with the thinking circle moving then stops and goes away. I have tried going to the purchases in the app store and restarting it the

    Why won't OS X Mavericks start downloading when I click the download button? It thinks and acts like it starts downloading with the thinking circle moving then stops and goes away. I have tried going to the purchases in the app store and restarting it there and that is not working either.

    Repair permissions, restart your computer & try again. 

  • 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;

  • I cant locate a file a had filled with pictures think i may have deleted is their anyway to recover it

    i cant locate a file a had filled with pictures think i may have deleted is their anyway to recover it

    Hi t,
    First, don't create or change any files. The more you do, the less chance you have of recovering any data. Google for Mac data recovery applications. There are several. At least one allows you to use it to see if you can recover data, without paying for it. If you decide to recover it, then you have to pay for the app in order for it to do the recovery.

  • 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 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

  • Example of JList with a ListModel

    I really need an example of a JList using a ListModel. I need that cause im thinking in have a line with hidden columns. I tried something but it didnt work.
    Tks, Ice

    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.DefaultListModel;
    public class listModel extends DefaultListModel
    Vector vctListData = new Vector();
    public listModel() {}
    public void buildListData(Vector vctListData, int startIndex, int endIndex)
    this.vctListData = vctListData;
    fireContentsChanged((Object) vctListData, startIndex, endIndex);
    public int getSize() {
    return vctListData.size();
    public Object getElementAt(int position) {
    if ( vctListData.size() == 0 ) return "";
    else return vctListData.elementAt(position);
    now in your prog when u create a JList set the model
    lst.setModel(listModel)
    to put the data call the method
    public void buildListData(Vector vctListData, int startIndex, int endIndex)
    lst.buildListData(vctData,0,vctData.size() );
    vctData is the vector that contains the data that is to be displayed in the list. 0 is the starting index and the end index is the size of the vector.
    Hope this will help u
    Nagaraj

Maybe you are looking for

  • Dreamweaver 8 not properly displaying php file in display area...

    Hi... I have made I new site... www.tresfjording.com It's all in Norwegian, but it seems to work fine in MSIE7 But in my Dreamweaver's design window it's a mess. In fact it shows just parts of the page and even that is garbled... Have installed WampS

  • Need help Staffing a Portal Project

    Can anyone tell me how many people are needed to staff a sun Portal implementation project. We are estimating 2 fulltime developers for a 6 month duration. The client wants the follwing features: Personalization, Online forums/collaboration, Portlets

  • TargetServerURL & Checkbox

    I'm converting Access 2003 reports to .NET. I have two issues: After importing reporting using Business Intelligence Tool, when I try to run the report, it asks for TargetServerURL. 1) What should this be? It doesnt accept the server name, errors tha

  • Pattern recognition and stitching images to reconstruct a panorama

    H,  I am taking around two hundreds snapshots of an object of 1m long and I would like to recreate a full panoramic image. I can basically do it manually (it works fine) by imposing a identical offset in between all pictures but sometimes a small del

  • Help - Unable to use Phone in Brazil

    I have traveled to 12 countries with my iPhone and it always just jumps on the network right when I get off the plane. Whether im in the Eastern Block (Prague) or in Thailand. NEver had a problem. Here I am in Rio De Janeiro Brazil and it says "No Se