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.

Similar Messages

  • JList in JScrollPane never shows horizontal scroll bar

    I have a JList inside a JScrollPane. When I add a lot of cells to the list, the vertical scroll bar appears as expected. However, if I add a cell that would require lots of horizontal space in which to render, the horizontal scroll bar never appears.
    Is there a way to make the JList take on the width of the widest rendered cell?
    Josh

    Here's some code that will demonstrate the problem. Run the code, then resize the window so that the horizontal scroll bar should appear.
    Code for jds.toys.Main:
    package jds.toys;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class Main extends JFrame {
         protected DefaultListModel model;
         public Main()
              super("JList in JScrollPane");
              model = new DefaultListModel();
              model.addElement("A very very very very very very long String");
              model.addElement("A very very very very very very very long String");
              model.addElement("A very very very very very very very very long String");
              model.addElement("A very very very very very very very very very long String");
              model.addElement("A very very very very very very very very very very long String");
              model.addElement("A very very very very very very very very very very very long String");
                      JList list = new JList(model);
                      list.setSize(300,300);
                      list.setFixedCellHeight(30);
                      list.setCellRenderer(new MyCellRenderer());
                      JScrollPane scrollPane = new JScrollPane(list);
                      add(scrollPane);
                      setSize(400,400);
        public static void main(String[] args) throws InterruptedException {
             final Main m = new Main();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                     m.setVisible(true);
    Code for jds.toys.MyCellRenderer:
    package jds.toys;
    import java.awt.Component;
    import java.awt.Graphics;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.ListCellRenderer;
    public class MyCellRenderer extends JPanel implements ListCellRenderer
         private Object currentValue;
         private JList currentList;
         public MyCellRenderer()
         public Component getListCellRendererComponent(     JList list,
                                             Object value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus)
              currentValue = value;
              currentList = list;
              return this;
         public void paintComponent(Graphics g)
              int stringLen = g.getFontMetrics().stringWidth(currentValue.toString());
              int ht = currentList.getFixedCellHeight();
              g.setColor(getBackground());
              g.fillRect(0,0,stringLen,ht);
              g.setColor(getForeground());
              g.drawString(currentValue.toString(),0,ht/2);
    }

  • Problem with a JList and JScrollpane

    Hi,
    Im having a problem with horizontal scrolling in that I have a simple JList inside a panel and a text box below where the user enters text. Now the text box has a width of 15, but the user can type as many characters as they want..Now the Jlist only displays 15 characters, but the horizontal scroller does not come up, instead just displays for example abcdefghijkl... (the three dots in the end)..
    Isnt my scroller supposed to be automatically scrolling when there is more on the line then the screen displays?? I already have this so far..
    scroller = new JScrollPane(dataList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);thanks!

    Try the following code:
    package sample;
    import java.awt.*;
    import javax.swing.*;
    public class MyDialog extends JDialog {
      public static void main( String[] args) {
        new MyDialog().setVisible(true);
      JPanel contentPanel = new JPanel();
      JScrollPane scrollPane = new JScrollPane();
      JList list = new JList( new Object[] {"abcdefghijklmnopqrstuvwxyz", "123456789012345678901234567890"});
      public MyDialog() {
        contentPanel.setLayout(new BorderLayout());
        getContentPane().add(contentPanel);
        contentPanel.add(scrollPane, BorderLayout.CENTER);
        scrollPane.getViewport().add(list, null);   
        setSize( 100,100);
        setLocation( 100,100);
    }Michael

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

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

  • JLists in JScrollPane in JFrame

    im writing a form class it extends JFrame has a number of jtextfields and labels
    im trying to add a JList in a JScrollPane
    the list works alone
    everytime i try adding it to a scrollpane it just doesnt show
    im not getting any errors either
    any ideas
    jstfsklh211

    import java.awt.*;
    import java.sql.*;
    import java.lang.Object;
    import javax.swing.*;
    import java.util.*;
    public class addevent extends JFrame{
         //input fields with options
         JComboBox eventType, salesman;
         JCheckBox flrplan;
         //textfields for input
         JTextField date, location, count, ctlstart, cerstart,
              dinstart, valnum, valstart, npkn, kipot, textbox,
              custinfoID;
         JList ctllist,dinlist, buflist;
         JButton Add, menu;
         //labels for customer info
         JLabel custinfof, custinfol, custinfop, custinfoc;
         //connection variables
         startup bridge = new startup();
         Connection con = null;
         Statement stmt = null;
         ResultSet rs = null;
         Vector vector1 = null;
         private String custID, query;
         int j;
         public addevent(String title){
              this.setTitle(title);
              //header
              JLabel line = new JLabel();
              line.setLocation(0,30);
              line.setSize(900,1);
              line.setBorder(BorderFactory.createMatteBorder(0,0,1,0,Color.black));
              //lists
              itemlist("query");
              ctllist = new JList(vector1);
              ctllist.setSize(200, 250);
              ctllist.setLocation(50, 160);
              itemlist("query");
              dinlist = new JList(vector1);
              dinlist.setSize(200, 250);
              dinlist.setLocation(350, 160);
              itemlist("query");
              buflist = new JList(vector1);
              buflist.setSize(200, 250);
              buflist.setLocation(650, 160);
              textbox = new JTextField();
              textbox.setVisible(false);
              Container contentPane = this.getContentPane();
              JScrollPane ctlpane = new JScrollPane(ctllist);
              JScrollPane dinpane = new JScrollPane(dinlist);
              JScrollPane bufpane = new JScrollPane(buflist);
              contentPane.add(ctlpane);
              contentPane.add(dinpane);
              contentPane.add(bufpane);
              contentPane.add(textbox);
              this.pack();
              this.setSize(900,550);
              this.setLocationRelativeTo(null);
              this.setVisible(true);
              catlist list = new catlist();
         public void salesman(){
              try {
                     query = "select * from salesman;";
                     con = bridge.getConnection();
                     stmt = con.createStatement();
                     rs = stmt.executeQuery(query);
                     while(rs.next())
                          salesman.addItem(rs.getString(1));
              catch(Exception ex){ex.printStackTrace();}
              finally {
                   try {
                        if (rs != null)
                             rs.close();
                   catch(Exception ex) {ex.printStackTrace();}
                   try {
                        if (stmt != null)
                             stmt.close();
                   catch(Exception ex) {ex.printStackTrace();}
         public void eventType(){
              try {
                     query = "select * from eventType;";
                     con = bridge.getConnection();
                     stmt = con.createStatement();
                     rs = stmt.executeQuery(query);
                     while(rs.next())
                          eventType.addItem(rs.getString(1));
              catch(Exception ex){ex.printStackTrace();}
              finally {
                   try {
                        if (rs != null)
                             rs.close();
                   catch(Exception ex) {ex.printStackTrace();}
                   try {
                        if (stmt != null)
                             stmt.close();
                   catch(Exception ex) {ex.printStackTrace();}
         public void itemlist(String query){
              try {
                   vector1 = new Vector();
                   con = bridge.getConnection();
                   stmt = con.createStatement();
                   query = "select distinct type from food;";
                   rs = stmt.executeQuery(query);
                   while(rs.next()) vector1.add(rs.getObject(1));
              catch(Exception ex){ex.printStackTrace();}
              finally {
                   try {
                        if (rs != null)
                             rs.close();
                   catch(Exception ex) {ex.printStackTrace();}
                   try {
                        if (stmt != null)
                             stmt.close();
                   catch(Exception ex) {ex.printStackTrace();}
    }//end classi pulled out about 20 buttons, lables, and textfields
    and mutiple get and sets for the text fields
    Message was edited by:
    jstfsklh211
    Message was edited by:
    jstfsklh211

  • Proper procedure listen mouse JList in JScrollPane

    I have a public class that extends JDialog. On a panel in that frame, I have a Jlist embedded in a JScrollPane. I do have a List Model defined as
    private DefaultListModel listModel;I just cant seem to find the right "trick" to grab an entry in the list when I 'click' the mouse on an item in the list.
    Any pointers ??

    The answer was not easy, so I'll display it for anyone else that runs into the same problem.
    private DefaultListModel listModel = new DefaultListModel();
    final JList jList1 = new JList(listModel);
      MouseListener mouseListener = new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
             if (e.getClickCount() == 2) {
                 int index = jList1.locationToIndex(e.getPoint());
                 System.out.println("Double clicked on Item " + index);
    };in jbInit()
    jList1.addMouseListener (mouseListener);The trickiest part of this was that the event creator in JBuilder, did NOT use the above procedure to listen to the mouse event and the procedure used by JBuilder would only see mouse events when the JList was empty. Once data was placed in the table, the mouse events were blocked. I'm not sure why, but that was the problem I was having. ALL FIXED with the above code.

  • JLists in JScrollPane with DefaultListModels

    Why doesn't this work? When I compile there isn't any scroll pane around the JList. I tried it with an Array of strings instead of a DefautListModel and it worked. I don't know why. If you can't do it with a DefaultListModel, how can I get this 'add(String s)' method without the DefaultListModel?
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.util.ArrayList;
    import javax.swing.*;
    import java.awt.*;
    public class MessageHolder extends JFrame
         private DefaultListModel messages;
         public MessageHolder()
              this.setSize(400, 400);
              messages = new DefaultListModel();
              JList list = new JList(messages);
              list.setPreferredSize(new Dimension(250, 100));
              JScrollPane pane = new JScrollPane(list);
             getContentPane().add(pane, BorderLayout.CENTER);
              add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");
              add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");
              add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");add("HEY");
              this.setVisible(true);
         public void add(String s)
              messages.addElement(s);
    }

    when a component is within a JScrollPane, the scroll bars do not show automatically, only when necessary. You can Manipulate your JScrollPane easily enough through the JScrollPane api...found here http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JScrollPane.html ... the methods you want are the set policy ones, there's one for the vertical and one for the horizontal scroll bar...pass constants from JScrollPane into these methods to force scroll bars to appear as you wish.

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

  • JScrollPane not showing in JList

    listModel = new DefaultListModel();
            jList2 = new JList(listModel);
            scrollPane = new JScrollPane(jList2, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); The above still doesn't show the scrollPane. Any suggestions why?

    works OK in this, using a null layout
    import javax.swing.*;
    import java.awt.*;
    class Testing
      public void buildGUI()
        DefaultListModel lm = new DefaultListModel();
        final JList list = new JList(lm);
        JScrollPane sp = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        for(int x = 0; x < 100; x++) lm.addElement(""+x);
        sp.setBounds(0,0,392,366);
        JFrame f = new JFrame();
        f.getContentPane().setLayout(null);
        f.getContentPane().add(sp);
        f.setSize(400,400);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • JScrollPane, JList, Resizing - How does it work?

    Hello NG,
    I have the following situation:
    3 JScrollpanes with 3 JLists to display. 2 Scrollpanes (on the right, 2. and 3.) are in a JPanel with GridBagLayout. This JPanel and the 3rd JScrollpane (on the left, 1.) are in another JPanel also with GridBagLayout. All components have a gridBagConstraints.fill = BOTH setting for resizing. The JLists will be filled from another Thread different from the EventDispatcherThread.
    The Problem:
    The JFrame with the components above will be displayed on the screen. Then the other thread fills the JList of JScrollpane(1), then the two other JScrollpanes (2 and 3). After that, a resizing occurs according to the gridBagConstraints.fill constraint to fill the space between the components. So, the 3 JScrollpanes change their size, it seem to the observer that this resizing occurs without intention.
    Is there a way to prevent this risizing? How does this resizing mechanism exactly works? Who fires which event? Does anybody knows where to find a good description of it?
    So far, I know it starts with the revalidate()-method in the JLists after changing the content of the lists. revalidate() adds the component to the RepaintManger invalidation queue for repainting. But who calls revalidate()? What will happen if the revalidate()-method will be overwritten to do nothing?
    Bye
    Raoul

    You gotta throw use a bone here... How does what work? More info please.

  • Problem with focus border and ListCellRenderer in custom listbox

    I have a bug in some code that I adapted from another posting on this board -- basically what I've done is I have a class that implements a custom "key/value" mapping listbox in which each list item/cell is actually a JPanel consisting of 3 JLabels: the first label is the "key", the second is a fixed "==>" mapping string, and the 3rd is the value to which "key" is mapped.
    The code works fine as long as the list cell doesn't have the focus. When it does, it draws a border rectangle to indicate focus, but if the listbox needs to scroll horizontally to display all the text, part of the text gets cut off (i.e. "sometex..." where "sometext" should be displayed).
    The ListCellRenderer creates a Gridlayout to lay out the 3 labels in the cell's JPanel.
    What can I do to remedy this situation? I'm not sure what I'd need to do in terms of setting the size of the panel so that all the text gets displayed OK within the listbox. Or if there's something else I can do to fix this. The code and a main() to run the code are provided below. To reproduce the problem, click the Add Left and Add Right buttons to add a "mapping" -- when it doesn't have focus, everything displays fine, but when you give it focus, note the text on the right label gets cut off.
    //======================================================================
    // Begin Source Listing
    //======================================================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Vector;
    import java.util.Enumeration;
    public class TwoColumnListbox extends JPanel
    private JList m_list;
    private JScrollPane m_Pane;
    public TwoColumnListbox(Collection c)
         DataMapListModel model = new DataMapListModel();
         if (c != null)
         Iterator it = c.iterator();
         while (it.hasNext())
         model.addElement(it.next());
         m_list = new JList(model);
         ListBoxRenderer renderer= new ListBoxRenderer();
              m_list.setCellRenderer(renderer);
              setLayout(new BorderLayout());
              m_list.setVisibleRowCount(4);
              m_Pane = new JScrollPane(m_list);
              add(m_Pane, BorderLayout.NORTH);
    public JList getList()
    return m_list;
    public JScrollPane getScrollPane()
    return m_Pane;
    public static void main(String s[])
              JFrame frame = new JFrame("TwoColumnListbox");
              frame.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {System.exit(0);}
    final DataMappings dm = new DataMappings();
    final TwoColumnListbox lb = new TwoColumnListbox(dm.getMappings());
              final DataMap map = new DataMap();
              JButton leftAddBtn = new JButton("Add Left");
              leftAddBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setSource("JButton1");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton leftRemoveBtn = new JButton("Remove Left");
              leftRemoveBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setSource("");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton rightAddBtn = new JButton("Add Right");
    rightAddBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setDestination("/getQuote/symbol[]");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JButton rightRemoveBtn = new JButton("Remove Right");
    rightRemoveBtn.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
              map.setDestination("");
              DefaultListModel model = new DefaultListModel();
              model.addElement(map);
              lb.getList().setModel(model);
              JPanel leftPanel = new JPanel(new BorderLayout());
              leftPanel.add(leftAddBtn, BorderLayout.NORTH);
              leftPanel.add(leftRemoveBtn, BorderLayout.SOUTH);
    JPanel rightPanel = new JPanel(new BorderLayout());
              rightPanel.add(rightAddBtn, BorderLayout.NORTH);
              rightPanel.add(rightRemoveBtn, BorderLayout.SOUTH);
    frame.getContentPane().add(leftPanel, BorderLayout.WEST);
              frame.getContentPane().add(lb,BorderLayout.CENTER);
    frame.getContentPane().add(rightPanel, BorderLayout.EAST);
              frame.pack();
              frame.setVisible(true);
         class ListBoxRenderer extends JPanel implements ListCellRenderer
              private JLabel left;
              private JLabel arrow;
              private JLabel right;
              private Color clrForeground = UIManager.getColor("List.foreground");
    private Color clrBackground = UIManager.getColor("List.background");
    private Color clrSelectionForeground = UIManager.getColor("List.selectionForeground");
    private Color clrSelectionBackground = UIManager.getColor("List.selection.Background");
              public ListBoxRenderer()
                   setLayout(new GridLayout(1, 2, 10, 0));
                   //setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
                   left = new JLabel("");
                   left.setForeground(clrForeground);               
                   arrow = new JLabel("");
                   arrow.setHorizontalAlignment(SwingConstants.CENTER);
                   arrow.setForeground(clrForeground);
                   right = new JLabel("");
                   right.setHorizontalAlignment(SwingConstants.RIGHT);
                   right.setForeground(clrForeground);
                   add(left);
                   add(arrow);
                   add(right);
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus)
                   if (isSelected)
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                        left.setForeground(clrSelectionForeground);
                        arrow.setForeground(clrSelectionForeground);
                        right.setForeground(clrSelectionForeground);
                   else
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   left.setForeground(clrForeground);
                        arrow.setForeground(clrForeground);
                        right.setForeground(clrForeground);               
                   // draw focus rectangle if control has focus. Problem with focus
    // and cut off text!!
                   if (cellHasFocus)
                   // FIXME: for Windows LAF I'm not getting the correct thing here for some reason.
                   // Looks OK on Metal though.
                   setBorder(BorderFactory.createLineBorder(UIManager.getColor("focusCellHighlightBorder")));
                   else
                   setBorder(BorderFactory.createEmptyBorder());               
    DataMap map = (DataMap) value;
                   String displaySource = map.getSource();
                   String displayDest = map.getDestination();
                   left.setText(displaySource);
                   arrow.setText("=>to<=");
                   right.setText(displayDest);
                   return this;
    /** Interface for macro editor UI
    * @version 1.0
    class DataMappings
    private Collection mappings;
    public DataMappings()
    setMappings(new Vector(0));
    public DataMappings(Collection maps)
    setMappings(maps);
    /** gets mapping value of a specified source object
    * @param src -- the "key" or source object, what is mapped.
    * @return what the source object is mapped to
    * @version 1.0
    public Object getValue(String src)
    if (src != null)
    Iterator it = mappings.iterator();
    while (it.hasNext());
    DataMap thisMap = (DataMap) it.next();
    if (thisMap.getSource().equals(src))
    return thisMap.getDestination();
    return null;
    /** sets mapping value of a specified source object
    * @param src -- the "key" or source object, what is mapped.
    * @param what the source object is to be mapped to
    * @version 1.0
    public void setValue(String src, String dest)
    if (src != null)
    // see if the value is in there first.
    Iterator it = mappings.iterator();
    while (it.hasNext())
    DataMap thisMap = (DataMap) it.next();
    if (thisMap.getSource().equals(src))
    thisMap.setDestination(dest);
    return;
    // not in the collection, add it
    mappings.add(new DataMap(src, dest));
    /** gets collection of mappings
    * @return a collection of all mappings in this object.
    * @version 1.0
    public Collection getMappings()
    return mappings;
    /** sets collection of mappings
    * @param maps a collection of src to destination mappings.
    * @version 1.0
    public void setMappings(Collection maps)
    mappings = maps;
    /** adds a DataMap
    * @param map a DataMap to add to the mappings
    * @version 1.0
    public void add(DataMap map)
    if (map != null)
    mappings.add(map);
    class DataMap
    public DataMap() {}
    public DataMap(String source, String destination)
    m_source = source;
    m_destination = destination;
    public String getSource()
    return m_source;
    public void setSource(String s)
    m_source = s;
    public String getDestination()
    return m_destination;
    public void setDestination(String s)
    m_destination = s;
    protected String m_source = null;
    protected String m_destination = null;
    /** list model for datamaps that provides ways
    * to determine whether a source is already mapped or
    * a destination is already mapped.
    class DataMapListModel extends DefaultListModel
    public DataMapListModel()
    super();          
    /** determines whether a source is already mapped
    * @param src -- the source property of a datamapping
    * @return true if the source is in the list, false if not
    public boolean containsSource(Object src)
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    if (dm.getSource().equals(src))
    return true;
    return false;
    /** determines whether a destination is already mapped
    * @param dest -- the destination property of a datamapping
    * @return true if the destination is in the list, false if not
    public boolean containsDest(Object dest)
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    if (dm.getDestination().equals(dest))
    return true;
    return false;
    public DataMappings getDataMaps()
    DataMappings maps = new DataMappings();
    // add all the datamaps in the model
    Enumeration enum = elements();
    while (enum.hasMoreElements())
    DataMap dm = (DataMap) enum.nextElement();
    maps.add(dm);
    return maps;
    //======================================================================
    // End of Source Listing
    //======================================================================

    I did not read the program, but the chopping looks like a layout problem.
    I think it's heavy to use a panel + 3 components in a gridlayout for each cell. look at this sample where i draw the Cell myself,
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Jlist3 extends JFrame 
         Vector      v  = new Vector();
         JList       jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public Jlist3()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j*1000+"a  d"+j);
           setBounds(1,1,400,310);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(230,259));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         String  txt;
         int     idx;
         boolean sel;
    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
         idx = index;
         txt = value.toString();
         sel = isSelected;
         setText(txt);
         return(this);
    public void paintComponent(Graphics g)
         if (idx%2 == 1) g.setColor(Color.white);
              else        g.setColor(Color.lightGray);
         if (sel)        g.setColor(Color.blue);
         g.fillRect(0,0,getWidth(),getHeight());
         StringTokenizer st = new StringTokenizer(txt.trim()," ");
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),1,14);
         g.setColor(Color.red);
         g.drawString("===>",70,14);
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),110,14);
    public static void main (String[] args) 
         new Jlist3();
    Noah
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Jlist3 extends JFrame
         Vector v = new Vector();
         JList jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public Jlist3()
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j*1000+"a d"+j);
         setBounds(1,1,400,310);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(230,259));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         String txt;
         int idx;
         boolean sel;
    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
         idx = index;
         txt = value.toString();
         sel = isSelected;
         setText(txt);
         return(this);
    public void paintComponent(Graphics g)
         if (idx%2 == 1) g.setColor(Color.white);
              else g.setColor(Color.lightGray);
         if (sel) g.setColor(Color.blue);
         g.fillRect(0,0,getWidth(),getHeight());
         StringTokenizer st = new StringTokenizer(txt.trim()," ");
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),1,14);
         g.setColor(Color.red);
         g.drawString("===>",70,14);
         g.setColor(Color.black);
         if (st.hasMoreTokens())     g.drawString(st.nextToken(),110,14);
    public static void main (String[] args)
         new Jlist3();
    }

  • Picture in JList!

    hi,
    i want to add a picture in the JList in such a way that it comes befor any string in a jlist
    please help me in this regard
    thanks,

    Try this: don't forget to change this 2 lines
    ImageIcon i1 = new ImageIcon("im1.gif");
    ImageIcon i2 = new ImageIcon("im2.gif");
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class JlistR extends JFrame 
         Vector      v  = new Vector();
         JList       jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public JlistR()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j+"a  d"+j*120);
           setBounds(1,1,500,300);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(200,199));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         ImageIcon i1 = new ImageIcon("im1.gif");
         ImageIcon i2 = new ImageIcon("im2.gif");
    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
         setOpaque(true);
         if (index%2 == 1) setBackground(Color.white);
              else          setBackground(Color.lightGray);
         if (isSelected)
              setBackground(Color.gray);
              setIcon(i1);
         else
              setIcon(i2);
           setForeground(Color.black);
         setText(value.toString());
         return(this);
    public static void main (String[] args) 
         new JlistR();
    Noah
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class JlistR extends JFrame
         Vector v = new Vector();
         JList jc = new JList(v);
         JScrollPane js = new JScrollPane(jc);
    public JlistR()
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         for (int j=0; j < 70; j++)     v.add(""+j+"a d"+j*120);
         setBounds(1,1,500,300);
         getContentPane().add(js);
         js.setPreferredSize(new Dimension(200,199));
         jc.setSelectedIndex(1);
         jc.setCellRenderer(new MyCellRenderer());
         getContentPane().setLayout(new FlowLayout());
         setVisible(true);
    public class MyCellRenderer extends JLabel implements ListCellRenderer
         ImageIcon i1 = new ImageIcon("im1.gif");
         ImageIcon i2 = new ImageIcon("im2.gif");
    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
         setOpaque(true);
         if (index%2 == 1) setBackground(Color.white);
              else setBackground(Color.lightGray);
         if (isSelected)
              setBackground(Color.gray);
              setIcon(i1);
         else
              setIcon(i2);
         setForeground(Color.black);
         setText(value.toString());
         return(this);
    public static void main (String[] args)
         new JlistR();

  • Need help in storing data from JList into a vector

    need help in doing the following.-
    alright i click a skill on industryskills Jlist and press the add button and it'll be added to the applicantskills Jlist. how do i further store this data that i added onto the applicantskills JList into a vector.
    here are the codes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
    import java.util.Vector;
    import javax.swing.JScrollPane.*;
    //import javax.swing.event.ListSelectionListener;
    public class Employment extends JFrame
            //declare class variables
            private JPanel jpApplicant, jpEverything,jpWEST, jpCENTRE, jpEAST, jpAddEditDelete,
                                       jpCentreTOP, jpCentreBOT, jpEastTOP, jpEastCENTRE, jpEastBOT,
                                       jpBlank1, panel1, panel2, panel3, panel4,jpBottomArea,
                                       jpEmptyPanelForDisplayPurposes;
            private JLabel jlblApplicantForm, jlblAppList, jlblName, jlblPhone,
                                       jlblCurrentSalary, jlblPassword, jlblDesiredSalary,
                                       jlblNotes, jlblApplicantSkills, jlblIndustrySkills,
                                       jlblBlank1, jlblBlank2, ApplicantListLabel,
                                       NotesListLabel, ApplicantSkillsLabel,
                                       IndustrySkillsLabel,jlblEmptyLabelForDisplayPurposes;  
            private JButton jbtnAdd1, jbtnEdit, jbtnDelete, jbtnSave, jbtnCancel,
                                            jbtnAdd2, jbtnRemove;
            private JTextField jtfName, jtfPhone, jtfCurrentSalary, jtfPassword,
                                               jtfDesiredSalary;
              private JTabbedPane tabbedPane;
            private DefaultListModel /*listModel,*/listModel2;
              String name,password,phone,currentsalary,desiredsalary,textareastuff,NotesText;
              String selectedname;
            final JTextArea Noteslist= new JTextArea();;
            DefaultListModel listModel = new DefaultListModel();
            JList ApplicantSkillsList = new JList(listModel);
           private ListSelectionModel listSelectionModel;
            JList ApplicantList, /*ApplicantSkillsList,*/ IndustrySkillsList;
            //protected JTextArea NotesList;    
                    //Vector details = new Vector();
                  Vector<StoringData> details = new Vector<StoringData>();             
                public static void main(String []args)
                    Employment f = new Employment();
                    f.setVisible(true);
                    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    f.setResizable(false);
                }//end of main
                    public Employment()
                            setSize(800,470);
                            setTitle("E-commerce Placement Agency");
                                  Font listfonts = new Font("TimesRoman", Font.BOLD, 12);
                            JPanel topPanel = new JPanel();
                            topPanel.setLayout( new BorderLayout() );
                            getContentPane().add( topPanel );
                            createPage1();
                            createPage2();
                            createPage3();
                            createPage4();
                            tabbedPane = new JTabbedPane();
                            tabbedPane.addTab( "Applicant", panel1 );
                            tabbedPane.addTab( "Job Order", panel2 );
                            tabbedPane.addTab( "Skill", panel3 );
                            tabbedPane.addTab( "Company", panel4 );
                            topPanel.add( tabbedPane, BorderLayout.CENTER );
            public void createPage1()//PAGE 1
                 /*******************TOP PART********************/
                            panel1 = new JPanel();
                            panel1.setLayout( new BorderLayout());
                                  jpBottomArea = new JPanel();
                                  jpBottomArea.setLayout(new BorderLayout());
                            jpApplicant= new JPanel();
                            jpApplicant.setLayout(new BorderLayout());
                            Font bigFont = new Font("TimesRoman", Font.BOLD,24);
                            jpApplicant.setBackground(Color.lightGray);
                            jlblApplicantForm = new JLabel("\t\t\t\tAPPLICANT FORM  ");
                            jlblApplicantForm.setFont(bigFont);
                            jpApplicant.add(jlblApplicantForm,BorderLayout.EAST);
                            panel1.add(jpApplicant,BorderLayout.NORTH);
                            panel1.add(jpBottomArea,BorderLayout.CENTER);
           /********************************EMPTY PANEL FOR DISPLAY PURPOSES*************************/
                               jpEmptyPanelForDisplayPurposes = new JPanel();
                               jlblEmptyLabelForDisplayPurposes = new JLabel(" ");
                               jpEmptyPanelForDisplayPurposes.add(jlblEmptyLabelForDisplayPurposes);
                               jpBottomArea.add(jpEmptyPanelForDisplayPurposes,BorderLayout.NORTH);
           /*****************************************WEST*********************************/             
                            jpWEST = new JPanel();                 
                            jpWEST.setLayout( new BorderLayout());
                            //Applicant List
                                  listModel2=new DefaultListModel();
                                  ApplicantList = new JList(listModel2);
                                listSelectionModel = ApplicantList.getSelectionModel();
                                listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
                                JScrollPane scrollPane3 = new JScrollPane(ApplicantList);
                                  ApplicantList.setPreferredSize(new Dimension(20,40));
                                 scrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);                                             
                                scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            ApplicantListLabel = new JLabel( "Applicant List:");
                            jpWEST.add(ApplicantListLabel,"North"); 
                            jpWEST.add(scrollPane3,"Center");
                            jpBottomArea.add(jpWEST,BorderLayout.WEST);
                            /*********CENTRE*********/
                            jpCENTRE = new JPanel();
                            jpCENTRE.setLayout(new GridLayout(2,1));
                            jpCentreTOP = new JPanel();
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            jpCENTRE.add(jpCentreTOP);
                            jpCentreTOP.setLayout(new GridLayout(6,2));
                              //Creating labels and textfields
                            jlblName = new JLabel( "Name:");
                            jlblBlank1 = new JLabel ("");
                            jtfName = new JTextField(18);
                            jlblBlank2 = new JLabel("");
                            jlblPhone = new JLabel("Phone:");
                            jlblCurrentSalary = new JLabel("Current Salary:");
                            jtfPhone = new JTextField(13);
                            jtfCurrentSalary = new JTextField(7);
                            jlblPassword = new JLabel("Password:");
                            jlblDesiredSalary = new JLabel("Desired Salary:");
                            jtfPassword = new JTextField(13);
                            jtfDesiredSalary = new JTextField(6);
                              //Add labels and textfields to panel
                            jpCentreTOP.add(jlblName);
                            jpCentreTOP.add(jlblBlank1);
                            jpCentreTOP.add(jtfName);
                            jpCentreTOP.add(jlblBlank2);
                            jpCentreTOP.add(jlblPhone);
                            jpCentreTOP.add(jlblCurrentSalary);
                            jpCentreTOP.add(jtfPhone);
                            jpCentreTOP.add(jtfCurrentSalary);
                            jpCentreTOP.add(jlblPassword);
                            jpCentreTOP.add(jlblDesiredSalary);
                            jpCentreTOP.add(jtfPassword);
                            jpCentreTOP.add(jtfDesiredSalary);
                            //Noteslist
                            jpCentreBOT = new JPanel();
                            jpCentreBOT.setLayout( new BorderLayout());
                            jpCENTRE.add(jpCentreBOT);
                            jpBlank1 = new JPanel();
                             //     Noteslist = new JTextArea(/*Document doc*/);
                            JScrollPane scroll3=new JScrollPane(Noteslist);
                                scroll3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                                scroll3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            NotesListLabel = new JLabel( "Notes:");
                            jpCentreBOT.add(NotesListLabel,"North"); 
                            jpCentreBOT.add(scroll3,"Center");
                            jpCentreBOT.add(jpBlank1,"South");
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            /**********EAST**********/
                            //Applicant Skills Panel
                            //EAST ==> TOP
                            jpEAST = new JPanel();
                            jpEAST.setLayout( new BorderLayout());
                            jpEastTOP = new JPanel();
                            jpEastTOP.setLayout( new BorderLayout());
                            ApplicantSkillsLabel = new JLabel( "Applicant Skills");
                            JScrollPane scrollPane1 = new JScrollPane(ApplicantSkillsList);
                               scrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                              scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);                                             
                            ApplicantSkillsList.setVisibleRowCount(6);
                            jpEastTOP.add(ApplicantSkillsLabel,"North"); 
                            jpEastTOP.add(scrollPane1,"Center");
                            jpEAST.add(jpEastTOP,BorderLayout.NORTH);
                            jpBottomArea.add(jpEAST,BorderLayout.EAST);
                            //Add & Remove Buttons
                            //EAST ==> CENTRE
                            jpEastCENTRE = new JPanel();
                            jpEAST.add(jpEastCENTRE,BorderLayout.CENTER);
                            jbtnAdd2 = new JButton("Add");
                            jbtnRemove = new JButton("Remove");
                            //add buttons to panel
                            jpEastCENTRE.add(jbtnAdd2);
                            jpEastCENTRE.add(jbtnRemove);
                            //add listener to button
                           jbtnAdd2.addActionListener(new Add2Listener());
                           jbtnRemove.addActionListener(new RemoveListener());
                            //Industry Skills Panel
                            //EAST ==> BOTTOM
                            jpEastBOT = new JPanel();
                            jpEastBOT.setLayout( new BorderLayout());
                           String[] data = {"Access97", "Basic Programming",
                           "C++ Programming", "COBOL Programming",
                           "DB Design", "Fortran programming"};
                           IndustrySkillsList = new JList(data);
                           JScrollPane scrollPane = new JScrollPane(IndustrySkillsList);
                           scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                           scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                           IndustrySkillsLabel = new JLabel( "Industry Skills:");
                           jpEastBOT.add(IndustrySkillsLabel,"North"); 
                           jpEastBOT.add(scrollPane,"Center");
                           jpEAST.add(jpEastBOT,BorderLayout.SOUTH);
                            //BOTTOM
                            jpAddEditDelete= new JPanel();
                            jbtnAdd1=       new JButton("Add");
                            jbtnEdit=       new JButton("Edit");
                            jbtnDelete=     new JButton("Delete");
                            jbtnSave=       new JButton("Save");
                            jbtnCancel=     new JButton("Cancel");
                            jpAddEditDelete.add(jbtnAdd1);
                            jpAddEditDelete.add(jbtnEdit);
                            jpAddEditDelete.add(jbtnDelete);
                            jpAddEditDelete.add(jbtnSave);
                            jpAddEditDelete.add(jbtnCancel);
                               jbtnEdit.addActionListener(new EditListener());
                               jbtnDelete.addActionListener(new DeleteListener());
                                jbtnEdit.addActionListener(new EditListener());
                            jbtnAdd1.addActionListener(new Add1Listener());
                            jbtnCancel.addActionListener(new CancelListener());
                            jpBottomArea.add(jpAddEditDelete,BorderLayout.SOUTH);
            public void createPage2()//PAGE 2
                    panel2 = new JPanel();
                    panel2.setLayout( new GridLayout(1,1) );
                    panel2.add( new JLabel( "Sorry,under construction" ) );
            public void createPage3()//PAGE 3
                    panel3 = new JPanel();
                    panel3.setLayout( new GridLayout( 1, 1 ) );
                    panel3.add( new JLabel( "Sorry,under construction" ) );
            public void createPage4()//PAGE 4
                    panel4 = new JPanel();
                    panel4.setLayout( new GridLayout( 1, 1 ) );
                    panel4.add( new JLabel( "Sorry,under construction" ) );
            public class Add1Listener implements ActionListener
            public void actionPerformed(ActionEvent e)
                    name = jtfName.getText();
                    password = jtfPassword.getText();
                    phone = jtfPhone.getText();
                    currentsalary = jtfCurrentSalary.getText();
                    int i= Integer.parseInt(currentsalary);
                    desiredsalary = jtfDesiredSalary.getText();
                    int j= Integer.parseInt(desiredsalary);
                       StoringData person = new StoringData(name,password,phone,i,j);
                   //     StoringData AppSkillsList = new StoringData(listModel);
                    details.add(person);
                 //     details.add(AppSkillsList);
                  listModel2.addElement(name);
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");
    //                NotesList.setText("");
            public class Add2Listener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                           String temp1;
                           temp1 = (String)IndustrySkillsList.getSelectedValue();
                           listModel.addElement(temp1);
            public class RemoveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            int index = ApplicantSkillsList.getSelectedIndex();
                                listModel.remove(index);
            public class EditListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            jtfName.setEditable(true);
                            jtfPassword.setEditable(true);
                            jtfPhone.setEditable(true);
                            jtfCurrentSalary.setEditable(true);
                            jtfDesiredSalary.setEditable(true);
                            Noteslist.setEditable(true);
                            jbtnAdd2.setEnabled(true);               
                            jbtnRemove.setEnabled(true);
                            jbtnSave.setEnabled(true);
                            jbtnCancel.setEnabled(true);                     
            public class DeleteListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                        int index1 = ApplicantList.getSelectedIndex();
                            listModel2.remove(index1);
            public class SaveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
            public class CancelListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");                         
            public class SharedListSelectionHandler implements ListSelectionListener
            public void valueChanged(ListSelectionEvent e)
             selectedname =ApplicantList.getSelectedValue().toString();
             StoringData selectedPerson = null;
             jtfName.setEditable(false);
             jtfPassword.setEditable(false);
             jtfPhone.setEditable(false);
             jtfCurrentSalary.setEditable(false);
             jtfDesiredSalary.setEditable(false);                                 
             Noteslist.setEditable(false);
             jbtnAdd2.setEnabled(false);               
             jbtnRemove.setEnabled(false);
             jbtnSave.setEnabled(false);
             jbtnCancel.setEnabled(false);
                   for (StoringData person : details)
                          if (person.getName1().equals(selectedname))
                                 selectedPerson = person;
                                 jtfName.setText(person.getName1());
                                 jtfPassword.setText(person.getPassword1());
                              jtfPhone.setText(person.getPhone1());
                              //String sal1 = Integer.parseString(currentsalary);
                             // String sal2 = Integer.parseString(desiredsalary);
                             // jtfCurrentSalary.setText(sal1);
                             // jtfDesiredSalary.setText(sal2);
                                 break;
                   //     if (selectedPerson != null)
    }

    Quit posting 300 line programs to ask a question. We don't care about your entire application. We only care about code that demonstrates your current problem. We don't want to read through 300 lines to try and find the line of code that is causing the problem.
    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.
    Here is a simple SSCCE. Now make your changes and if you still have problems you have something simple to post. If it works then you add it to your real application.
    Learn to simplify your problem by simplifying the code.
    import java.awt.*;
    import javax.swing.*;
    public class ListTest2 extends JFrame
         JList list;
         public ListTest2()
              String[] numbers = { "one", "two", "three", "four", "five", "six", "seven" };
              list = new JList( numbers );
              JScrollPane scrollPane = new JScrollPane( list );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              ListTest2 frame = new ListTest2();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(200, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
    }

  • My jList won't show up on the frame

    My problem is that I can't see the JList in the scrollPane. I am able to run and compile this frame through JBuilder, however I get this error message:
    java.lang.NullPointerException new JList(helpTopics)
    If I remove the jpanel from the frame and just drop in the scrollPane with the nested jlist on the frame I am then able to see the list and the items in the list. But I'd like to have it on a panel.
    BTW I am calling this frame from another class that contains the main function. Here is my code:
    import java.awt.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class NewFrame extends JFrame{
    private final String[] helpTopics = {"Load Cells", "Strain Gages",
    "Op Amps", "RTD", "Wheatstone Bridge"};
    JPanel jPanel1 = new JPanel();
    JList lstTopics = new JList(helpTopics);
    JScrollPane jScrollPane1 = new JScrollPane();
    public NewFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.add(lstTopics, null);
    Any help with my problem would greatly reduce my stress factor.
    Thanks.

    You haven't added the panel to the frame from the code you have just posted.

Maybe you are looking for