JList ListCellRenderer No events

Hello,
I have managed to add some components to a panel and then
create a ListCellRenderer for it to be added to a JList, it works fine
but components do not listen to any event at all when in the JList.
I have tried adding listeners to the subcomponents of the object returned by getListCellRendererComponent but it doesn't work at all.
Is it possible to add components such as jTextFields to a JList and communicate the changes to the real item the CellRenderer represents?
Thanks in advance,
Ramon Talavera

Maybe you should be listening to changes in the underlying model that the JList is displaying, and not the events being fired by the component.

Similar Messages

  • JList ListCellRenderer Help

    Hello All,
    I have a small query in regards to a ListCellRenderer implementation.
    I have my own ListCellRenderer implementation, and it is working fine in regards to bolding text, colors and so on. But I was wondering about how I would go making a nice "glowing" effect on the mouseover event of the List item.
    I have been a web programmer for a while, and have had many nice experiences with JavaScript and using timing events, to slowly change the color of an HTML element, to give it that glowing effect.
    I was kind of hoping to do the same for a JList, is there anyone out there that has had experiences with this kind of thing?
    Any help is appreciated, I will also post if I find anything on my own.
    Cheers,
    Mark

    I've no idea of what glowing effect you are after, but I was bored and have been playing with timers and colors and came up with this effect. If you develop your glow effect, please post your code so we can play with it.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    class GlowSwing2 extends JPanel
        private static final int TIMER_PERIOD = 60;
        private static final int DIMEN = 400;
        private static final int GRID_SIZE = 5;
        private static final int COLOR_STEPS = 16;
        private Color currentColor = Color.black;
        private Color originalColor = Color.black;
        private int colorIndex = 0;
        private JLabel[][] labels = new JLabel[GRID_SIZE][GRID_SIZE];
        private JLabel currentLabel = null;
        private Timer timer = new Timer(TIMER_PERIOD, new MyTimerAction());
        private Color[] colors;
        GlowSwing2()
            setPreferredSize(new Dimension(DIMEN, DIMEN));
            int ebGap = 10;
            setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
            setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
            for (int i = 0; i < GRID_SIZE; i++)
                for (int j = 0; j < GRID_SIZE; j++)
                    JLabel jl = new JLabel("Hello");
                    jl.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 24));
                    jl.addMouseListener(new LabelMouseListener());
                    add(jl);
                    labels[i][j] = jl;
            initColors();
            timer.start();
         * creates a nice sin wave of blue color
        private void initColors()
            colors = new Color[COLOR_STEPS];
            double periodStep = 2 * Math.PI / COLOR_STEPS;
            for (int i = 0; i < colors.length; i++)
                int c = (int)(256 * (Math.sin(i * periodStep) + 1)/2);
                if (c == 256)
                    c = 255;
                colors[i] = new Color(c, c, 255);
        private class LabelMouseListener extends MouseAdapter
            @Override
            public void mouseEntered(MouseEvent mEvent)
                JLabel source = (JLabel)mEvent.getSource();
                originalColor = source.getForeground();
                currentLabel = source;
                super.mouseEntered(mEvent);
            @Override
            public void mouseExited(MouseEvent mEvent)
                currentLabel = null;
                ((JLabel)mEvent.getSource()).setForeground(originalColor);
                super.mouseExited(mEvent);
        private class MyTimerAction implements ActionListener
            public void actionPerformed(ActionEvent arg0)
                myTimerAction(arg0);
         * changes the colors of the labels
         * @param arg0
        private void myTimerAction(ActionEvent arg0)
            if (currentLabel != null)
                colorIndex++;
                colorIndex %= colors.length;
                currentColor = colors[colorIndex];
                currentLabel.setForeground(currentColor);
                currentLabel.repaint();
        private static void createAndShowGUI()
            JFrame frame = new JFrame("GlowSwing Application");
            frame.getContentPane().add(new GlowSwing2());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • JList/ListCellRenderer/JScrollPane

    Hi Listeners!
    I'm using a JList using an own renderer for displaying the data.
    Every cell contains among other components a text field embedded in a scroll pane. The text field may contain text or images (animated ones).
    Both components have information about the available sizes.
    The problem comes with displaying the cells because neither the scroll pane nor the animated gif work correctly. Altough the scroll pane is shown I cannot use it and it seems that the scroll pane cannot or does not receive (mouse) events. Finally the animated gif changes to a standard gif without animation. All other things do work.
    Has anybody tried to use the JList for presenting scroll pane based content?
    ThanX
    franzR

    Thanks for the suggestion. With those changes, though, it seems I still have to set the width (setColumns()) inside the renderer in order to get the wrap to occur. getPreferredSize() returns the size of a single line without setting it.
    Do you know any way I can access the width of the JList (or the containing JScrollPane), or pass it to the renderer? getPreferredSize() of the JList object yields a StackOverflowError when accessed from within the renderer.

  • Best way to delegate events to parent

    Hi to all.
    I have a problem with a GUI i'm programming. I have the Shop class that extends a JFrame and have several JPanel and other components. Inside one of this JPanel i have an InventoryPanel that extends JPanel and contains JTextfields and a JList.
    I've no problems to handle events inside InventoryPanel, but depending on some factors (i.e. the property of objects selected in the JList) sometimes the event must be delegate to the Shop class (so i can disable/enable buttons or set text). Which is the best way to do such a thing?
    I thought i could call a method of Shop, but InventoryPanel "doesn't know" how to reference it... should i pass the reference in some way (constructor)?
    Or should I conditionally delegate in some way the event to a Shop EventListener? and in this case, how can i do this? I searched through the tutorials and the forum, but it's not too clear to me
    Thanks for any help
    Wil

    The simplest way to implement addListener and removeListener is something like:
    public class Foo
      private Vector mFooListeners = new Vector();
      public void addFooListener(IShiftListener listener) {
        mFooListeners.addElement(listener);
      public void removeFooListener(IShiftListener listener) {
        mFooListeners.removeElement(listener);
      protected void fireFooEvent(FooEvent event) {
         for (Enumeration enum = mFooListeners.elements(); enum.hasMoreElements(); ) {
          IFooListener listener = (IFooListener)enum.nextElement();
          listener.fooHappened(event);
      // and somewhere in here you do something that requires a call to fireFooEvent()...
    }Note that this code was developed under JDK 1.1.4 so I used Enumeration instead of Iterator. Other than that this is a respectable way to handle listeners.

  • Jlist validate

    Hi friends
    I am trying to transfer the data between multiple JList.
    this is what my code looks like
    initialization
    int selectedIndex[] = null;
    DefaultListModel dlmAddressAll;
    JList jltAddressAll
    if(event.getSource() == sbtnDeselectCC) {
    selectedIndex = jltAddressCC.getSelectedIndices();
    for(int i = 0; i < selectedIndex.length ; i++ ) {
    dlmAddressAll.addElement(dlmAddressCC.get(selectedIndex));
    jltAddressCC.validate();
    for(int i = 0 ; i < selectedIndex.length ; i++) {
    dlmAddressCC.remove(selectedIndex[i]);
    i am using JDK 1.6
    i am facing some problems regarding this function
    ListSelectionModel is MULTIPLE_INTERVAL_SELECTION.
    1.When i select all the rows from the list and then transfer to another List, they get added in target list but while removing from the original list only half of the rows are removed.
    2.Many times i face ArrayIndexOutOfBound exception when while removing the elements equal to size of list.
    Also after we add any element to a list model we perform validate method on list . But is it right to call that method on the list from which elements are removed.
    If any one know the solution .
    Thanks
    --Sunny Jain
    null

    1. Use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.
    2. No need to call validate on any of the lists.
    3. This can't be your code because there's no remove int[] function in DefaultListModel.
    4. You probably meant dlmAddressCC.remove(selectedIndex);
    But you have to reverse the loop and remove the last index first, because if you remove the first index first all the indexes that follow in the list are changed, and the list size is decreased by 1, which may cause an ArrayIndexOutOfBound exception.
    for(int i =  selectedIndex.length-1; i >=0 ; i--) {
        dlmAddressCC.remove(selectedIndex);

  • JList with mouseListener

    I have add the mouselistener to my JList to apply the double click to open up a dialog.
    My problem now is this apply to anywhere on my frame no matter my mouse point on to the Jlist object or not..
    I want to deselect the item in the list when my mouse click on other place ..how can i do it in the mouse click event?

    Most likely you are adding the listener to the wrong object. I can't tell for sure without the code.
    If you want to deselect your list selection, then you would need to add the listener to your frame indeed and check if the mouse co-ordinates are within your JLlist.
    If not, then you can deselect your JList in the event handler.
    Hope this helps.
    Neelesh

  • Get All images from a website and put them in a listbox.

    Hi Everyone, I am new to Java Programming.
    I wanted to know if there is a way to get all the images in a website and put them in a listbox. And if an item is clicked in list box, view it in a picturebox.

    Harsimran_Singh wrote:
    what is the whole idea about .Net vs. Java...guys, .NET users are so friendly and helpful, they don't even judge english
    This is not putting a good impression of Java Users on me.good luck with .net. im sorry that things didnt work out with java.
    unfortunately, .net is essentially a clone of java so you may find that you will be looking
    to learn exactly the same things but for an expensive propriety platform.
    if you change your mind, read:
    [swing tutorials|http://java.sun.com/docs/books/tutorial/uiswing/]
    jlist
    listcellrenderer
    [list tutorial|http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]
    [advanced list programming|http://java.sun.com/products/jfc/tsc/tech_topics/jlist_1/jlist.html]
    on your way out thank the moderators : )

  • ListSelection Listener is executing two times

    Hi,
    I am using my own cell renderer for the JList and adding some buttons in the JList.I am adding ListSelectionListener to my JList.When i am selecting a item in the JList, the listselection event is fired two times.How should i rectify this.

    I've had the same problem, and I solved it by by asking my ListSelectionEvent's getValueIsAdjusting() method:
    rowTypeSM.addListSelectionListener(new AbstractListSelectionListener(){
    public void doValueChanged(ListSelectionEvent e){
    if(!e.getValueIsAdjusting()){
    // Stick your code here
    Hope this helps.

  • Button Event Handler in a JList, Please help.

    Hi everyone,
    I have created a small Java application which has a JList. The JList uses a custom cell renderer I named SmartCellRenderer. The SmartCellRenderer extends JPanel and implements the ListCellRenderer. I have added two buttons on the right side inside the JPanel of the SmartCellRenderer, since I want to buttons for each list item, and I have added mouse/action listeners for both buttons. However, they don't respond. It seems that the JList property overcomes the buttons underneath it. So the buttons never really get clicked because before that happens the JList item is being selected beforehand. I've tried everything. I've put listeners in the Main class, called Editor, which has the JList and also have listeners in the SmartCellRenderer itself and none of them get invoked.
    I also tried a manual solution. Every time the event handler for the JList was invoked (this is the handler for the JList itself and not the buttons), I sent the mouse event object to the SmartCellRenderer to manually check if the point the click happened was on one of the buttons in order to handle it.
    I used:
    // Inside SmartCellRenderer.java
    // e is the mouse event object being passed from the Editor whenever
    // a JList item is selected or clicked on
    Component comp = this.getComponent (e.getX(), e.getY())
    if(!(comp instanceof JButton)) {
              System.out.println("Recoqnized Event, but not a button click...");
              //return;
    } else {
              System.out.println("Recognized Event, IT IS A MOUSE CLICK, PROCESSING...");
              System.out.println("VALUE: "+comp.toString());
    What I realized is that not only this still doesn't work (it never realizes the component as a JButton) it also throws an exception for the last line saying comp is null. Meaning with the passed x,y position the getComponent() returns a null which happens when the coordinates passed to it are outside the range of the Panel. Which is a whole other problem?
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.
    Can anyone help me with this. Thanks.

    A renderer is not a component, so you can't click on it. A renderer is just used to paint a representation of a component at a certain position in your JList.
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.Thats probably because this is not a common design. The following two designs are more common:
    a) Create a separate panel for your JButtons. Then when you click on the button it would act on each selected row in the JList
    b) Or maybe like windows explorer. Select the items in the list and then use a JPopupMenu to perform the desired functionality.
    I've never tried to add a clickable button to a panel, but this [url http://forum.java.sun.com/thread.jspa?threadID=573721]posting shows one way to add a clickable JButton as a column in a JTable. You might be able to use some of the concepts to add 2 button to the JPanel or maybe you could use a JTable with 3 columns, one for your data and the last two for your buttons.

  • Event handling in JList

    hello to all!!!
    i am having a problem in JList event handling.Following is my code--
    public void valueChanged(ListSelectionEvent  lse)
    {index = list.getSelectedIndex();
    if(index==0)
                     System.out.println( "index"+index);
                     System.out.println("1st frame now opened");
               JFrame f2=new JFrame();
                    JPanel p1=new JPanel();
              f2.getContentPane().add(p1);                    
              JLabel l10=new JLabel("id");
              JTextField t100=new JTextField(20);
              p1.add(l10);
              p1.add(t100);
              p1.add(l11);//declared in constructor
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              f2.setVisible(true);
    if(index==1)
              System.out.println("now index is"+index);
              }My problem is that 2 frames get opened whenever index==0 .even the code written in System.out.println() is displayed 2 times on the screen.2 JFrames open up whenever index==0.i want that only 1 JFrame should be opened.and moreover 1 of the JFrame does not contain the JLabel that is declared in the constructor.and when index==1,then The index value is displayed 2 times on the screen.i want that only 1 value should be there.any help would be highly appreciated.thanks in advance.

    even after entering if (lse.getValueIsAdjusting())
    }index = list.getSelectedIndex();i am having the same value.my problem is not when value of index changes.even if i use only 1 st index (i.e. only click on academic record) than also 2 frames open up.i entered this code after if(index==0) and if if(index==1).but it was of no help.same problem of 2 times each event occuring is there.
    urgent Help required.any help would be highly appreciated.thnx in advance

  • What type of event handling does the JList has?

    hello
    I know how to use handling using " anonymous inner class " when handling a JList, I don't like this way it is so confusing I would like to use the same way of handling JButton like this:
    class Class1 extends JFrame implements ActionListener
    //and the method is this one
    public void actionPerformed( ActionEvent event )it is much better than the anonymous class. What is the handler of selecting in JList? is it this one?
    ListSelectionListener
    and the method is this?
    public void valueChanged(ListSelectionEvent e)
    I'm new in GUI Components so that's why I want to get used to the same old way of handling that I learned earlier :)
    Could you provide me with an example please?
    thank you

    Have a look at [Selecting Items in a List|http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#selection] in Sun's Tutorial. The ListDemo class implements ListSelectionListener.

  • Capturing JButton event in a JList

    All,
    I have a JList that renders each list item with some special formatting of a JLabel and a Jbutton. The button is an 'OK' button that must be acknowledged. When the OK button is acknowledged it should be deleted from the list model. I am having trouble capturing the event of the button. I am not interested in the list selection event per se just the selected Index, which I know how to get. Any ideas on getting to the button click event even though it is in a list?
    Thanks much.

    I'm not sure I understand exactly what you're doing (you have a JButton inside a JList?), but to answer your last question, you get access to the button click even the same way you would with any other JButton:
    JButton myListButton = new JButton("click me");
    myListButton.addActionListener(new ActionListener()
      public void actionPerformed(ActionEvent e)
        // remove button from list or do whatever
        // other processing is required

  • Catch a JList event, which JList is in a JTable

    I have got a JTable and in its cells are JLists or JLabels (it depend on data)
    Here is code spinnet:
    DefaultTableCellRenderer ownRenderer = new DefaultTableCellRenderer() {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    NERecordSet nyers = (NERecordSet)tData.getModel();
    if (nyers.getValueAt(row, column).getClass().getName().equals("com.nextent.corridor.db.NERecordSet")) {
    JList listCell = new JList();
    listCell.setModel((NERecordSet)nyers.getValueAt(row, column));
    listCell.setCellRenderer(ownListCellRenderer);
    listCell.setForeground(Color.BLACK);
    if (isSelected) {
    listCell.setBackground(Color.blue);
    else {
    listCell.setBackground(Color.LIGHT_GRAY);
    return listCell;
    else {
    JLabel lCell = new JLabel();
    lCell.setToolTipText(tooltip);
    return lCell;
    I'd like to catch the event 'click to one of elements of JList' -> How can I do it? (I tried to add an event handler in the renderer (JList.addMouseListener()), but it was wrong)
    other questions: I'd like to add tooltip to the elements of JList, but I can't
    Please help me to solve these problems!
    Thanks!
    rflair

    Try this:
    listCell.addListSelectionListener(
        new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                System.out.println("value changed in JList: " + evt);
    );Good luck!

  • JList Selection Event

    Hi, here is one problem i am facing.
    i have a JList and i am using Selection Listener for that. Now selection listener has only one even in it valueChanged. which is only fired when some value is changed in the JList, i.e., if we select the same value twice consecutively, this event is fired only once only when that value is selscted for the first time. but i want this even to be fired every time i select a value (even twice or thrice consecutively). can u plz help me or tell me any other event?
    -Ashish

    problem is I cannot recieve which chat room is selected (let's say I don't know how to get it :) )Sorry I didn't get the humor :-( So let's try a dry answer:
    Try "jlist.getSelectedValue()" and cast it to the common supertype of all objects stuffed in the JList's model (I assume they are String or ChatRoom objects).
    and also selected index is appended twice when I click on any of them ? Can it be done by double click ?You receive two events (deselection of current item - selection of new item). You can distinguish them with event.getValueIsAdjusting().
    Brgds.

  • JList event listener problem

    I'm trying to define an event listener for a JList component. The code is shown below. The problem i'm having is that when elements are added to the JList none of the functions (callFunctionHere()) are being called. Can anyone tell me what i'm doing wrong? (elements are being added to the list using DefaultListModel.addElement())
            pnlWhere.lstCond.getModel().addListDataListener(new javax.swing.event.ListDataListener() {
                public void contentsChanged(ListDataEvent e) {
                    callFunctionHere();
                public void intervalRemoved(ListDataEvent e) {
                    callFunctionHere();
                public void intervalAdded(ListDataEvent e) {
                    callFunctionHere();
            });Thanks,
    Danny.

    Check out the KeyListener interface. You can create an implementation that searches for a string starting with the character of the key that was pressed.

Maybe you are looking for

  • Access to HTTPS port failed

    Hi Access to Https port failed after changing the Keystore to "Custom Identity and Trust". I have generated the identity and trust certificates and placed the path info with passphrase. I have also set my SSL private key alias name to the key name ge

  • Help!! Can't launch Acrobat 7 Pro (Error locating "updater.api")

    Acrobat 7 Pro has worked fine all week, and today - boom! Receiving the following error messages: 1st Error Window "There was an error while loading the plug-in "updated.api".  The plug-in failed to initialize. 2nd Error Window " The instruction at "

  • Compressing error

    Done project, rendered, saved. Want to compress to movie to external drive. There is message "File error: The specified file is locked" What's wrong?

  • Printer - sort by date

    Just noticed a strange thing. (Maybe it was posted before, couldn't tell easily.) In the printer window, when I do "Show completed jobs" I get a list. Great. When I sort that list by date, though, it does that sort strangely. Alphabetically. Like an

  • Compound clip with now sequence symbol

    I moved a fcp7 project to fcpx using 7 to X.   Nested sequences were created as compound clips in fcpx, but they looked a bit different from the compound clips, they had no sequence symbol next to the name.  Also, double clicking them did not open th