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;

Similar Messages

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

  • Send a mail with a picture from mime repository

    Hello,
    I want to send a mail with a picture from mime repository.
    The mail is sended OK, but the receiver hasn't  the picture on the mail  (don't find the picture).
    Here is my syntax :
       st_objtxt-line = '<IMG SRC="SAPR3://005056B2002D1EE3BF8F5B5ECDCA55E1" ALIGN=RIGHT WIDTH="100" HEIGHT="80">'.
        append st_objtxt to t_objtxt.
    "SAPR3://005056B2002D1EE3BF8F5B5ECDCA55E1" is url of my object mime .
    Have you a idea to resolve this problem ? It's the syntax OK ?
    Thank for your responses.
    Regards.
    JCAIL

    Have you tried storing your picture as a business document?  Have a look at the class  cl_bds_document_set to read your picture from the BDS.

  • Calendars - aligning pictures within date cells

    When inserting pictures on certain dates ie on October 1st, normally you can double click the picture to align it properly within the date cell. With some pictures, you double click on the picture on that date but you don't get the popup window to customise the alignment. From the moment you try to align one picture and it doesn't work, then the following issues begin: you can't remove this picture at all - a grey box remains permenantly on that date cell. Also the calendar is bound to crash if you click the Gallery to look for more pictures and then click back the calendar you were working on, iphoto will loop indefinitely with message "Loading Calendar... ". Then you have to close iPhoto and when you go back in iPhoto, the Calendar has disappeared. You have to start over! It happened to me 6 times.

    Hitting detele or dragging a pic to a different cell normally works but not once you start getting the problem. Dragging the problematic pic to other cells simply leaves a grey cell behind and puts the pic on the new cell. And if you try dragging to a new then same process happens. I was trying dates 1 October and 18 October. But then i played around with more dates and there were problems too. I suspect the problem is related not with the date but with certain pictures. I made a new calendar, didn't insert any pictures apart from that particular pic and tried to align it - still it wouldn't let me. That pic was taken with an older Nikon Coolpix 4500 while the ones that do work are taken with a Canon EOS 350D (digital rebel xt).
    Any other clues?

  • Since updating to I.O.S7 on my ipad2 all i get when i turn it on is a loading screen with a picture of a charger going into an ITUNES sign? HELP nothing will work not interactive at all?

    all i get when i turn it on is a loading screen with a picture of a charger going into an ITUNES sign? HELP nothing will work not interactive at all.aince updating to I.O.S7.0.2???
    What should i do currently have it on charge for several hours not done a thing and have been locking and unlocking and resetting

    Please see: http://support.apple.com/kb/HT1808 for further info.  It sounds like you are already in Recovery mode so if the image in Step 4 is the one you see, skip to Step 5.
    Regards,
    Steve

  • Preview of Ken Burns effect doesn't work with some pictures

    I just recently installed a new graphics card (ATI Radeon 7500) on my Sawtooth, 1.2 GHz, so I could utilize the Ken Burns effect in imovie HD. It works but only partly. It works great but with some pictures the preview pane doesn't show the photo. What I see is a what looks like bad reception on an old TV (fuzzies and the picture is distorted so bad you can't even make it out). With other pictures the preview shows up fine. I'm sure I've loaded the drivers. What else can I do?

    Hi Tonyy13.
    I am presenting the same problem. I can set the Ken Burns' effect while I am with the pictures before placing them in the Clip or Timeframe viewer. After placing them there, if I try to edit the picture (either by right clicking and choosing -edit picture or by control clicking and doing the same, I ended up with a black background. If you change the setting in this black ackground and update this changes they will be effective. So, you can change the slide duration, and everything in the sliders but without an image.
    I was running System 10.3.9 and I thought this was the reason. Today, I went and bought Tiger but it didn't sove the problem. I do believe it is a bug in the program. According to Apple's Help and David Pogue's "The Missing Manual" this shouldn't happen.
    If you solve this problem reply to this posting. If I did I will reply to your posting. Thank You.

  • I am trying to connect my Macbook pro 2010 to my Samsung HDTV using a mini display port to hdtv cable. Trying to play a slide show in IPhoto but I only get sound with no picture. Does anyone have any suggestions?

    I am trying to connect my Macbook pro 2010 to my Samsung HDTV using a mini display port to hdtv cable. Trying to play a slide show in IPhoto but I only get sound with no picture. Does anyone have any suggestions?

    I keep saying this over and over, in the hope that people who do a search will find it.  Apple cannot possibly test for or be reponsible for the bazillion combinations of adapter, cables, and TV's out there.  The only monitors that are 100% guaranteed to work with the MacBook Pro are the Cinema Displays and Thunderbolt Displays, because, they're made by Apple.  They're expensive, but they work perfectly.
    My guess is that you bought a cheap MDP to HDMI cable, or have a defective one.  From my reading of these boards over the past few months, cheap cables have a high failure rate.  And the regular priced ones have only a slightly less of one.  Try a new one.  Make sure you do not damage the Thunderbolt port.

  • My iphone is no longer working I have black screen with a picture of the itunes logo and a USB cable.  When I try to connect my iphone to itunes the device is not detected, can anyone help me? I desperatley need my phone back

    My iphone is no longer working I have black screen with a picture of the itunes logo and a USB cable.  When I try to connect my iphone to itunes the device is not detected, can anyone help me? I desperatley need my phone back

    I have had a 3GS for 2+ years.  After upgrading to IOS 4 (now 4.3.5) I began having problems.  In the past week, my screen went to the itunes logo and USB cable twice -- unprovoked -- just found it sitting there like that!  I connected to itunes and it did restore from a backup but it is a major inconvenience.  I am also searching for answers, but better back-up regularly!

  • 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

  • I updated to IOS 6 and now it is frozen with a picture of a cord to connect to ITunes

    Hi I updated to IOS 6 on my IPod touch and now it is frozen with a picture to connect to ITunes

    What happens when you connect the iPod to your computer and restore via iTunes?
    If iTunes does not see your iPod
    Try:
    - iOS: Not responding or does not turn on
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - If still not successful that indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
    Apple Retail Store - Genius Bar

  • How can I quickly view pdf files like I can do with Windows Picture and Fax viewer for jpg files?

    How can I quickly view pdf files like I can do with Windows Picture and Fax viewer for jpg files? I need to look at several thousand PDF files. It takes too long to open each one individually. The only thing I could think of is combining them into large groups and then using the Navigation index. But I like the way windows Picture and Fax Viewer does it because you can keep the files separate. Combining PDFs causes loss of individual file names. That would be a problem since I do need to have the individual file names.

    Windows Picture and Fax Viewer is a DLL and is started via a rundll32.exe call and can't be set as an application to handle images in Firefox 3 and later versions.
    Try to set Windows Picture and Fax Viewer as the default viewer in Windows, then it should be listed automatically in the Mozilla Firefox Browse dialog.
    *http://www.winhelponline.com/articles/115/1/Windows-Picture-and-Fax-Viewer-as-the-default-viewer-in-Mozilla-Firefox.html
    '''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.'''

  • Recently, when I create a new album (untitled), it immediately fills with picture either from the album above it or, if I have a Faces collection open, with the pictures from that collection. Why and how do I fix it?

    Recently, when I create a new album (untitled), it immediately fills it immediately fills with picture either from the album above it or, if I have a Faces collection open, with the pictures from that collection. Why and how do I fix it?

    When a new album is created it will fill with whatever is in the right hand window,  If you're in the Events or Photos mode it will contain all photos in the library.  Yes, strange behavior.
    OT

  • How can I send a text with a picture attachment on my new iPhone5c?

    How can I send a text with a picture attachment on my new iPhone5c? It won't send or recieve!!.

    Does your carrier support it?
    Follow the steps in this guide.
    http://www.imore.com/how-send-photo-using-imessage

  • Scrollable picture with other pictures attached to it?

    Any ideas how and with what classes this should be done?
    I want to make a GUI with largish picture in the background.
    The size of the picture exceeds the size of the window
    so it needs to be scrollable.
    Then I want to have other smaller images on top of that.
    These images should also move when the background is scrolled
    and my plan is to be able to drag them around with mouse
    (i.e. change their position in relation to the background picture).
    I managed to create the scrollable picture, but weren't
    able to display anything on top of it.
    I'm using JDK 1.3.1 (and Borland's Java Builder 7)

    All right, I managed to do it all. This Java is pretty quick to use
    (when you know what class to inherit ;)
    Here's the sollution for those draggable pictures
    public class DraggablePic extends JLabel implements MouseMotionListener, MouseListener {
      int clickPositionX;
      int clickPositionY;
      // constructors
      public DraggablePic() {
        super();
        addMouseMotionListener(this);
        addMouseListener(this);
      public DraggablePic(Icon image) {
        super(image);
        addMouseMotionListener(this);
        addMouseListener(this);
      // mouse motions
      public void mouseDragged(MouseEvent e) {
        super.setLocation(e.getX()-clickPositionX+this.getX(),
                          e.getY()-clickPositionY+this.getY());
      public void mouseMoved(MouseEvent e) {
      // mouse events
      public void mouseClicked(MouseEvent e) {
      public void mouseEntered(MouseEvent e) {
      public void mouseExited(MouseEvent e) {
      public void mousePressed(MouseEvent e) {
        clickPositionX = e.getX();
        clickPositionY = e.getY();
      public void mouseReleased(MouseEvent e) {

  • I have just purchased an iphone today and it is coming up with a picture on the screen of the usb connector and itunes symbol. It also says that I now have no service and can only make emergency calls

    I have just purchased an iphone today and it is coming up with a picture on the screen of the usb connector and itunes symbol. It also says that I now have no service and can only make emergency calls

    Just a thought, but maybe consider returning the device.  Seems it might be a bit too complicated for you.

Maybe you are looking for

  • Using a .bat file to use Values in Registry from another Registry

    I recently starting working in an IT Department and for years my superiors/co-workers have always had a piece of software called "cyt.exe". When ever I logged in someones computer as Admin, this software allowed me to log out with their username stil

  • Purchasing and transferring issues!!

    I bought a movie from my device, transferred it to my itunes library from the device, for whatever reason it removed the movie from my device, it shows up in my itunes library but i cannot watch it, or transfer it back onto my device? PLS HELP!

  • Adobe Connect Pro Customization

    Hello, I need help to customize my account. I firts created a trial account and I was able to upload my company´s logo, change colors and so on... After the trial ended, we really liked the application and decided to buy it. I don´t know exactly what

  • PFI Compilation never ends

    Hi, I have been developping my app since 2 month now and I never had any problem with creating test ipas (ie:target = ipa-test). But when I decided to create my final build for the app store (target = ipa-app-store) the process never ends. I run the

  • N80 MP3 problem

    My wife's just got her new N80 and it seems to have some issues playing MP3s. There's quite a few i've just transferred straight from my SE K750 to the N80 that upon trying to play them the phone just says "Unable to play media clip". They're just st