JList update

Hi,
I have a JList, for which I have a set of data represented as a queue, now, everytime I change the queue I fire an event to tell the list to update itself.., but the list won't.
I have tried validate, revalidate and a few others, but so far the only way of doing this that I have been able to work with is:
     * This gets called when the queue is updated in order to update the display
     *@param ch The type of the change, one of CH_POP, CH_PUT or CH_PUSH
     *@param inx The index of the change
     *@param o The object put or removed to/from the queue
    private void change(int ch, int inx, Object o){
        queueList.setModel(new AbstractListModel() {
            public int getSize() {
                return qc.size();    // qc = the queue object
            public Object getElementAt(int i) {
                return qc.peek(i);
    }Anyone know a better way of doing this?
thanks,
david

Here is one way of doing it. You just need to substitute your Queue implementation for the ArrayList.
Or you could have your Queue extend AbstractListModel. Anyway...
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.ArrayList;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.awt.*;
import java.awt.event.*;
public class QueueList extends JFrame implements ActionListener
    Point point1 = new Point(10,10);
    Point point2 = new Point(10,10);
    Point point3 = new Point(10,10);
    Point point4 = new Point(10,10);
    JButton add, remove;
    ArrayListModel dataModel;
    int counter = 1;
    public QueueList()
        super( "Array*(Queue)  List Demo");
        setDefaultCloseOperation( EXIT_ON_CLOSE );
        Container content = getContentPane();
        ArrayList dataList = new ArrayList();
        for( int i = 0; i < 10; i++ )
            dataList.add( ""+counter++ );
        JList list = new JList( dataModel = new ArrayListModel( dataList ) );
        JPanel panel = new JPanel();
        panel.add( add = new JButton("Add") );
        add.addActionListener( this );
        panel.add( remove = new JButton("Remove") );
        remove.addActionListener( this );
        content.add( new JScrollPane( list ), BorderLayout.CENTER );
        content.add(panel, BorderLayout.SOUTH );
        pack();
        show();
    public static void main(String[] args)
        try
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch( Exception e )
        new QueueList();
     * Invoked when an action occurs.
    public void actionPerformed(ActionEvent e)
        if( e.getSource().equals( add ) )
            dataModel.add( ""+counter++);
        else if( e.getSource().equals( remove ) )
            dataModel.remove(0);
    public class ArrayListModel extends AbstractListModel
        ArrayList arrayList;
        public ArrayListModel( ArrayList arrayList )
            this.arrayList = arrayList;
        public int getSize()
            return( arrayList.size() );
         * Returns the value at the specified index.
         * @param index the requested index
         * @return the value at <code>index</code>
        public Object getElementAt(int index)
            return( arrayList.get(index) );
        public void add( Object obj )
            arrayList.add( obj );
            fireContentsChanged(this, this.getSize(),this.getSize());
        public void remove( int index )
            if( arrayList.size() > 0 )
                arrayList.remove(index);
                fireContentsChanged(this,0,0);
}

Similar Messages

  • JList update/paint problem

    I've got some problems with updating a JList. This code adds an element to the bottom of the list and makes it visible.
    Lines are added dynamicaly. It could be just 1 update a minute, but it could easely be 20 lines a split second...
    Sometimes the last line is not visible (shows line before lastline). And sometimes the list goes totaly blank, until the next repaint. I think it must be a syncro ploblem between various "repaint"-threads. I already made the add function syncronized, but that didn't help.
    Here's the code:
    //     DEFINITIONS
    JList list;
    DefaultListModel model;
    //     INITIALIZE
    model=new DefaultListModel();
    list=new JList(model);
    list.setDoubleBuffered(true);     //     same with or without dbfr
    add(new JScrollPane(list),BorderLayout.CENTER);
    //     ADD LINE
    public void add(Object obj){
         model.addElement(obj);
         list.ensureVisible(model.size()-1);
    }How to solve this?

    Just call ensureVisible(row) 2 timesThis may solve the problem, but it appears you still don't know the cause. Not sure, but this thread may help explain why you have the problem to begin with:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=437592

  • Why won't my JList update?

    My JList is first dimensioned to an array with 100 elements in it but then in a function i set it to null and then I set it to a different array with a smaller amount of elements. Then i call repaint() to refresh the pane but it still doesn't change anything. The JList on my pane still shows the items in the old array. How do i fix this?

    you need to reset the listModel
    search the swing forum for
    listModel DefaultListModel
    and you'll find plenty of working examples

  • Delays in JList updates

    I would like to let users know the application is still "working" when a JList is being populated.
    Typically, I set an hourglass cursor, do some work, fill in the list, then go back to the default cursor. If I used a progress monitor and a thread, I think I would have the same problems.
    1. Set cursor to wait
    2. Go get data from DB, add items to JList
    3. Set cursor to default.
    The problem is, the wait cursor goes away when I am done populating the JList, but there is a long delay before the data is actually displayed. This happens regardless of the data model I use, either adding items one at a time, or dumping a vector into the model.
    I would prefer the wait cursor to be displayed until the data is displayed, so the user knows things are still going on.
    Any ideas as to why this happens, or how to enhance it?
    thanks,

    In experimenting, I added a paintImmediately() call inbetween steps 2 and 3. This held the wait cursor on until the data was displayed.

  • Updating a JList

    I can seem to load data into my JList that i create. using the code with no pane make the JList update but when i use it with JPane it won't update. Any ideas?
    Here the source code with most of unneeded stuff taken out
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    import java.util.*;
    import java.io.*;
    public class JavaTest extends JPanel implements ActionListener {
        private LoadLog loadLogs = new LoadLog();
        private JList barcodeList;
        private  DefaultListModel barcodeModel;
        private JLabel barcodeLabel;
        private JFileChooser LogChoser;
        public JavaTest() {
            super(new BorderLayout(5, 5));
            barcodeLabel = new JLabel("Read Barcodes");
            barcodeModel = new DefaultListModel();
            barcodeList = new JList(barcodeModel);
            barcodeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            JScrollPane barcodeScrollPane = new JScrollPane(barcodeList);
            JPanel listPane = new JPanel(new BorderLayout());
            listPane.add(barcodeLabel, BorderLayout.NORTH);
            listPane.add(barcodeList, BorderLayout.CENTER);
            JPanel list_desPane = new JPanel(new BorderLayout(5,5));
            list_desPane.add(listPane, BorderLayout.WEST);
            add(list_desPane, BorderLayout.EAST);
        public JMenuBar createMenuBar() {
            JMenuBar menuBar;
            JMenu menu;
            JMenuItem menuItem;
            menuBar = new JMenuBar();
            menu = new JMenu("File");
            menu.getAccessibleContext().setAccessibleDescription(
                    "Menu to load log file");
            menuBar.add(menu);
            menuItem = new JMenuItem("Load Log File", KeyEvent.VK_O);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
            menuItem.addActionListener(this);
            menuItem.setActionCommand("load");
            menu.add(menuItem);
            menuItem = new JMenuItem("Exit",KeyEvent.VK_X);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
            menuItem.addActionListener(this);
            menuItem.setActionCommand("exit");
            menu.add(menuItem);
            return menuBar;
        private static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("Field report producer");
            JavaTest menuBar = new JavaTest();
            frame.setJMenuBar(menuBar.createMenuBar());
            frame.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE);
            JComponent newContentPane = new JavaTest();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent e){
                  int exit = JOptionPane.showConfirmDialog(null, "Do you want to exit?",
                                                                 "Quite Program?",
                                                                 JOptionPane.YES_NO_OPTION);
                  if (exit == JOptionPane.YES_OPTION)
                  System.exit(0);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
           //Handle open button action.
            if ("exit".equals(e.getActionCommand()))
              exit();
            else if("load".equals(e.getActionCommand())){
               LogChoser = new JFileChooser(CurrentDirectory());
               LogChoser.setFileFilter(new FileFilter() {
                  public boolean accept(File f) {
                     return f.getName().toLowerCase().endsWith(".txt")
                            || f.isDirectory();
                  public String getDescription() {
                     return "Log files (*.txt)";
               int returnVal = LogChoser.showOpenDialog(JavaTest.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = LogChoser.getSelectedFile();
                   ArrayList BarcodeLog = new ArrayList();
                   BarcodeLog = loadLogs.LoadLogFile(file.getAbsolutePath());
                   for (Iterator it = BarcodeLog.iterator(); it.hasNext(); ){
                      barcodeModel.addElement(it.next());
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        private void exit()
         int exit = JOptionPane.showConfirmDialog(null, "Do you want to exit?",
                                                           "Quite Program?",
                                                           JOptionPane.YES_NO_OPTION);
              if (exit == JOptionPane.YES_OPTION)
                 System.exit(0);
        private String CurrentDirectory(){
           String directory = "";
           File dir1 = new File (".");
           try {
            directory = dir1.getCanonicalPath();
         catch(Exception e) {
           e.printStackTrace();
           return directory;
    import java.io.*;
    import java.util.ArrayList;
    import javax.swing.*;
    public class LoadLog
      private ArrayList BarcodeLog;
      public LoadLog()
      public ArrayList LoadLogFile(String FileName)
        BarcodeLog = new ArrayList();
        try
          FileInputStream fstream = new FileInputStream(FileName);
          DataInputStream in = new DataInputStream(fstream);
          while (in.available() != 0) {
            BarcodeLog.add(in.readLine());
          in.close();
        catch (FileNotFoundException e)
           JOptionPane.showMessageDialog(null, "File not found.", "Error", JOptionPane.ERROR_MESSAGE);
        catch (IOException e)
           JOptionPane.showMessageDialog(null, "Error Loading File.", "Error", JOptionPane.ERROR_MESSAGE);
       return BarcodeLog;
    }

    - if you're goin to add a pane then change this:
      listPane.add(barcodeList, BorderLayout.CENTER);into this:
    // JScrollPane must be added here instead of a JList
           listPane.add(barcodeScrollPane, BorderLayout.CENTER);

  • JList and ListModel, can anyone explain the basics?

    Hi
    I have an object A containing a Vector X of objects. I want to display them in a JList. I could always use DefaultListModel and copy the items of the Vector X into the default list model using addElement. But that would create a copy of the information in vector X. That is exactly why one should use a custom list model to ensure that the data is in sync with the GUI .
    I want to add and remove items from the JList, and simultaious add and remove items from the Vector X. Can anyone proviede a samll example of how to do this.
    I have tryed myselfe, but I can not get the JList updated with the changes of the listmodel. I have read the documentation about ListDataListener, but I just don't get it. A small example would realy be appreciated!
    // Mattias

    Yse I have read the tutorial. But I don't understand it.
    Here is a small example program. Can anyone change the code so the list is updated with the canges that obviously take place (as one can see by pressing the "Dump button")
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    class ListTest extends JFrame implements ActionListener , ListDataListener {
        JList list;
        MyListModel myListModel;
        MyDataObject myDataObject;
        ListTest() {
            JPanel p = new JPanel();
            myDataObject = new MyDataObject();
            myListModel = new MyListModel(myDataObject.x);
            list = new JList(myListModel);
            myListModel.addListDataListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            listScrollPane.setPreferredSize(new Dimension(200, 100));
            p.add(listScrollPane);
            JButton b1 = new JButton("Add");
            b1.addActionListener(this);
            p.add(b1);
            JButton b2 = new JButton("Remove");
            b2.addActionListener(this);
            p.add(b2);
            JButton b3 = new JButton("Dump");
            b3.addActionListener(this);
            p.add(b3);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(p);
            pack();
            show();
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Add")) {
                myListModel.addElement(""+ (1+myListModel.getSize()) );
                System.out.println("Added a row to the list");
            if (e.getActionCommand().equals("Remove")) {
                if (myListModel.getSize()>0) {
                    myListModel.remove(myListModel.getSize()-1);
                    System.out.println("Removed last element from the list");
                else {
                    System.out.println("No more elements to remove");
            if (e.getActionCommand().equals("Dump")) {
                System.out.println("\n\nData in the list model:");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myListModel.getElementAt(i));
                System.out.println("That should be the same as the vector x in the object myDataObject  :");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myDataObject.x.get(i));
        public void contentsChanged(ListDataEvent e) {
            System.out.println("contentsChanged");
        public void intervalAdded(ListDataEvent e) {
            System.out.println("intervalAdded");
        public void intervalRemoved(ListDataEvent e) {
            System.out.println("intervalRemoved");
        public static void main(String args[]) {
            new ListTest();
    class MyDataObject {
        Vector x;
        MyDataObject() {
            x=new Vector();
            x.addElement("1");
            x.addElement("2");
    class MyListModel extends AbstractListModel {
        Vector v;
        MyListModel(Vector v) {
            this.v=v;
        public void addElement(Object o) {
            v.addElement(o);
        public Object remove(int index) {
            return v.remove(index);
        public Object getElementAt(int index) {
            return v.get(index);
        public int getSize() {
            return v.size();
    </pre>

  • Linking JList to Vector

    Whats the simplest way to link a JList with a Vector keeping the JList updated as the Vector changes

    Use a DefaultListModel. It acts like a Vector and will keep your JList updated provided you set it up to be the JList's ListModel.

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

  • Update JList from database table

    Hi! I have a JList that take some value from a mysql table. I want that the JList add or remove value when insert or delete row from db table.
    Can you help me?

    Well then you need to write the add/remove code of the JList yourself. So when ever you updated the database you update the ListModel as well.
    Read the JList API and follow the link to the Swing tutorial on "How to Use Lists" for a working example that dynamically updates a ListModel.

  • JList won't update.

    This may be simple to some of you guys but Java is making me maddd. I know its my stupidity but it still makes me mad.
    I'm writing a simple application, it has a list (JLIst) of entries, that I load from a database. The entries just have names of places. I wanted to be able to add new places to the list via a JTextField and a add button. Really simple stuff right?!?!
    Ok this is where my frustration comes in. When I update the String [] which holds the names of the places i call a function createNamesList() which returns a new JList with the updated string array. I tried to remove the old list from the content pane and added the new one, that doesn't work. All I see is the same list.
    I tried setting the originalList pointer to newList object, and not removing anything from the content pane, that didn't work either.
    I don't see any methods to add elements to JLIst after its already been created, is ther e anything I need to do, or not do? I'm lost. This was supposed to be an easy project. Now I'm stuck.

    Hello,
    You certainly don't need to create a new JList upon simple modifications. What you need to do is to work on the ListModel. The easiest is to use a DefaultListModel. If you add a value to this model, updates to the corresponding JList are automatic. You should start by reading about this in the following tutorial :
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

  • Runtime exception when continuously updating a JList

    Hello,
    my program has a JList to display some information and updates the content of this JList while the program is running. The JList is put in a JScrollPane and uses DefaultListModel to store its elements(the elements are all String objects).
    Initially the JList is empty. After the program starts, new elements will be continuously added into DefaultListModel with the addElement(Object obj) method. Once there are 50 elements in the JList, the program removes the first element (index=0) before adding a new element to the JList.
    The program seems to work fine, except it randomly generates ArrayIndexOutOfBoundsException at runtime, which is really annoying. Can someone help me to solve this problem? Many thanks.
    Part of the program is listed below:
    DefaultListModel tupleListModel=new DefaultListModel();
    JList tupleList=new JList(tupleListModel);
    JScrollPane sp1=new JScrollPane(tupleList);
    for(int i=0;i<50;i++)
            tupleListModel.addElement(op.nextTuple().toString());
    while(true){
             tupleListModel.remove(0);
             tupleListModel.addElement(op.nextTuple().toString());
    }One of the runtime error message is:
    java.lang.ArrayIndexOutOfBoundsException: 49 >= 49
    at java.util.Vector.elementAt(Vector.java:431)
    at javax.swing.DefaultListModel.getElementAt(DefaultListModel.java:70)
    at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1147)
    at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1098)
    at javax.swing.plaf.basic.BasicListUI.getPreferredSize(BasicListUI.java:281)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1275)
    at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769)
    at java.awt.Container.layout(Container.java:1020)
    at java.awt.Container.doLayout(Container.java:1010)
    at java.awt.Container.validateTree(Container.java:1092)
    at java.awt.Container.validate(Container.java:1067)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:353)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:116)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
    The other one is:
    java.lang.ArrayIndexOutOfBoundsException: 49
    at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1155)
    at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1098)
    at javax.swing.plaf.basic.BasicListUI.getPreferredSize(BasicListUI.java:281)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1275)
    at javax.swing.JList.getScrollableTracksViewportWidth(JList.java:2147)
    at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:786)
    at java.awt.Container.layout(Container.java:1020)
    at java.awt.Container.doLayout(Container.java:1010)
    at java.awt.Container.validateTree(Container.java:1092)
    at java.awt.Container.validate(Container.java:1067)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:353)

    It's removing an item in the middle of trying to figure out what the preferred size of the jlist is. I would be that BasicListUI.updateLayoutState() has code in it something like thisint numItems = model.getSize();
    for (int i=0; i<numItems; i++) {
    String text = model..getElementAt(i).toString();  // bad time for the size to change
    }If the size changes, the loop will still iterate to what used to be the size. Try using SwingUtilities.invokeLater() when to update the list so that the changes will happen on the event thread.

  • JList bug, not always updates its UI

    I am using JList with a vector containing the data. (have call setListData() for the vector). when i add an element in the vector and call updateUI() method of JList, it updates its UI but not always. 20% of the time it fails to do so. Any Solution?

    Yeah, I have called repaint(), but the result is the same.
    repaint() does not work either. I have tried so many methods.
    like show() hide() repaint() invalidate() etc. etc. and much more but no one is working.
    Asim...

  • Input thread not updating JList

    Im using a thread for getting input from the server, in the run method i call the method of the Applet class which takes the string and adds an element to the JList. The problem is that JList doesn't add any element, or doesn't get updated. The one class is the Applet class, and the other is the Thread class which calls the method of Applet class to update the JList. I hope you people can help me thanx.

    Without any coding, we can hardly help you!
    Sometimes it's ueseful to make a System.out.println of the elements within the JList.
    If the added item is in the list, you probably should do a repaint();

  • JScrollPane not updating when Jlist values are changed

    Hello,
    I have a utility where I have a JList with file names inside a JScrollpane. When a user changes directories, the file list changes to the fully qualified names of the files contained in the new directory. The idea is to have the file names show up in the viewport by scrolling the horizontal scroll bar all the way to the right.
    Here's a short break down of what my code. Sorry I can't provide a runnable snippet, I'm a lot crunched for time.
    Arrays.sort(fileArray);
    fileList.setListData(fileArray);
    hBar = FileScrollPane.getHorizontalScrollBar();
    hBar.setValue(hBar.getMaximum());
    The problem is that hbar.getMaximum() always seems to be a step behind. I always get the Maximum width from the last list of files. As I traverse down a directory tree this results in the knob always being not quit all the way to the right.
    I've tried running fileList.revalidate() after the setListData.
    I've tried calling FileScrollPane.setViewportView(fileList) after the setListData.
    I've tried setting the setViewPositon using getWidth from fileList.
    I've tried setting fileList.setPreferredSize(null) after the setListData, then setting the Viewport, then calling revalidate.
    Somehow the JScrollPane just isn't picking up that the jList has changed and updating it's scrollbars model accordingly until after I've run setValue.
    So my question summed up is:
    Is there someway to force JScrollPane to realize that the JList has changed and update it's components accordingly?

    I tried the revalidate and repaint and it didn't seem to work. I can't use threads for political reasons. so I wrote up the following code which demonstrates the problem. Notice that you have to click a button twice to get the correct values displayed in standard out. Any help would be greatly appreciated.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    public class TestJListScroll extends JFrame {
      JScrollPane jScrollPane1 = new JScrollPane();
      String[] listValues1 = {"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
                              "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
                              "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
                              "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"};
      String[] listValues2 = {"TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT",
                              "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT",
                              "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT",
                              "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"};
      String[] listValues3 = {"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"};
      BorderLayout borderLayout1 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      JList list = new JList();
      JButton button1 = new JButton();
      JButton button2 = new JButton();
      JButton button3 = new JButton();
      public TestJListScroll() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String[] args) {
        TestJListScroll testJListScroll1 = new TestJListScroll();
        testJListScroll1.setSize(150,300);
        testJListScroll1.setVisible(true);
      private void jbInit() throws Exception {
        jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        this.getContentPane().setLayout(borderLayout1);
        jPanel1.setMinimumSize(new Dimension(10, 75));
        jPanel1.setPreferredSize(new Dimension(10, 75));
        button1.setText("List 1");
        button1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            button1_actionPerformed(e);
        button2.setText("List 2");
        button2.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            button2_actionPerformed(e);
        button3.setText("List 3");
        button3.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            button3_actionPerformed(e);
        this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
        this.getContentPane().add(jPanel1, BorderLayout.SOUTH);
        jPanel1.add(button1, null);
        jPanel1.add(button2, null);
        jPanel1.add(button3, null);
        jScrollPane1.getViewport().add(list, null);
        list.addPropertyChangeListener("model", new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            list_ModelChanged(e);
      void button1_actionPerformed(ActionEvent e) {
        System.out.println("button 1 pressed");
        list.setListData(listValues1);
      void button2_actionPerformed(ActionEvent e) {
        System.out.println("button 2 pressed");
        list.setListData(listValues2);
      void button3_actionPerformed(ActionEvent e) {
        System.out.println("button 3 pressed");
        list.setListData(listValues3);
      private void list_ModelChanged(PropertyChangeEvent e) {
        list.revalidate();
        list.repaint();
        BoundedRangeModel model = jScrollPane1.getHorizontalScrollBar().getModel();
        System.out.println("   file list width = " + list.getWidth());
        System.out.println("   Maximum = " + model.getMaximum());
        System.out.println("   extent = " + model.getExtent());
        model.setValue(model.getMaximum() - model.getExtent());
        System.out.println("   value = " + model.getValue());
    }Thanks,
    Jason

  • Update chat client JList

    I have a client and server app and Want to update the JList evertime a client joins or leaves.
    I also want to implement private chat later on. I know i can send a vector with the names of the clients to each client and update the list, but if im gonna do private chat, how can I enable clients to click on the list and when they select a peer to chat with, thier able to make and i/o stream and that with that person.
    I was thinking that I can make and additional ObjectInputStream/ObjectOutputStream and send the entire client object from the server side. That object would be "SocketThread" which is a class i made to handle each multiple client connection. The server side has Server.java, SocketThread.java, ChatProtocol.java
    This is the Thread that represents each client on the server side.
    vsockets is a Vector that adds each client object to the vector so the server can echo each client message to every other client.
    public SocketThread(Socket socket) {
                this.socket = socket;
                start();
            public void run()
            try {
                socket.setSoTimeout(60*1000);   // Client sends "alive" message in keep alive thread every
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader( new InputStreamReader( socket.getInputStream()));
                ChatProtocol cp = new ChatProtocol();
                inputLine = in.readLine();
                UserID = cp.processInput(inputLine);
                out.println("Rabbit's Socket Server, NY!");    // Welcome Message
                System.out.println("* "+UserID + " joined the server!");
                for ( i=0;i<Server.vsockets.size();i++)
                    SocketThread temp  = (SocketThread)Server.vsockets.elementAt(i);
                    temp.out.println("* "+UserID + " joined the server!"); //no "\n" server tokenizer adds it already
                while ((inputLine = in.readLine()) != null)
                    if(!inputLine.equals("alive")){
                    outputLine = cp.processInput(inputLine);
                    for (i = 0; i< Server.vsockets.size(); i++)
                        SocketThread temp = (SocketThread)Server.vsockets.elementAt(i);
                        temp.out.println(outputLine);
            }How would I go about implementing private chat. I think it has something to do with object serialization. Not sure how to do it.
    thanx

    Hello Jino!
    I think u r working in the right direction.
    I think it is better to have a vector there at client to represent the current users and u fill its elements when u send the notification for newuser logged in and remove the entry when any user left notification is there.
    I hope u got the idea.
    Best of Luck.
    Ahmad Jamal.

Maybe you are looking for

  • Trying to access Lion server remote using multi-user access, but from a legacy Leopard system

    Just purchased a mini server running Lion, and got screen sharing working fine from my legacy system (32-bit so Leopard only). However, I would like to run in multi-user mode, so someone can use the Lion system and another person can access their own

  • Search Help default value

    Hi experts, I want to create a search help for the Material. In the search help I should set some default value like the language and the company. I know how can I set the default language, but how can I say that the default language could not be 'EN

  • Subscription error

    Been using my credit card to buy other merchant outlets don't know why Skype is complaining about my payments?

  • *mdb file not working in another system

    I have created a mdb (Ms Access) file in one system , But when I tried to execute the same mdb in another system it is giving me an error saying that "cannot find the mdb file (or one of its components...)"

  • Extension Builder 3 Custom Panels code snippets ?

    Hello there! I used to make custom Photoshop panels with Adobe Configurator 4 but since the last CC2014 updates the support for flash based panels stopped. Now i'm trying to make HTML5 based panels with Extension Builder 3 but it's very difficult to