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

Similar Messages

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

  • 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

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

  • 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

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

  • Stop scroll bar in JScrollPane from updating viewport when dragging knob

    Hi,
    Does anyone know if it's possible to stop the JScrollPane from updating the viewport whilst dragging the knob of the scrollbar and only update once released.
    The problem I have is that the view of the scroll panes viewport is a JList that has an underlying model of a RandomAccessFile which can be very large. So when the user is dragging the scrollbars it will be accessing the file system to retrieve the relevant data for the JList.
    I've tried creating my own JScrollBar and adding a AdjustmentListener to ignore events whilst dragging:
    class MyAdjustmentListener implements AdjustmentListener {
    // This method is called whenever the value of a scrollbar is changed,
    // either by the user or programmatically.
    public void adjustmentValueChanged(AdjustmentEvent evt) {
    Adjustable source = evt.getAdjustable();
    // getValueIsAdjusting() returns true if the user is currently
    // dragging the scrollbar's knob and has not picked a final value
    if (evt.getValueIsAdjusting()) {
    // The user is dragging the knob
    return;
    Looking through the JScrollBar code it has a model that will fire adjustment events anyway, which I suppose are being picked up by the JScrollPane somewhere.
    I could use my own JScrollBar and not add it to the scroll pane and process the adjustment events myself and update the JList but I was wondering if there is a better way.
    Many Thanks,
    Martin.

    Two small changes seem to do the trick. You may want to test it thoroughly though ;)import javax.swing.BoundedRangeModel;
    import javax.swing.DefaultBoundedRangeModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class OneStepScroller {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new OneStepScroller().makeUI();
       public void makeUI() {
          Object[] data = new Object[200];
          for (int i = 0; i < data.length; i++) {
             data[i] = "Item Number " + i;
          JList list = new JList(data);
          JScrollPane scrollPane = new JScrollPane(list);
          BoundedRangeModel model = scrollPane.getVerticalScrollBar().getModel();
          final JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
          scrollBar.setModel(new DefaultBoundedRangeModel(model.getValue(),
                model.getExtent(), model.getMinimum(), model.getMaximum()) {
             int oldValue;
             @Override
             public int getValue() {
                // changed here
                if (!getValueIsAdjusting() && !(oldValue == super.getValue())) {
                   oldValue = super.getValue();
                   // added this
                   fireStateChanged();
                return oldValue;
          JFrame frame = new JFrame("");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400, 400);
          frame.setLocationRelativeTo(null);
          frame.add(scrollPane);
          frame.setVisible(true);
    }db

  • Problems to show a Vertical JScrollPane with JList

    I have a JList within a JScrollPane, and update the JList with the output from a process.
    This means that the JList is updated very quickly with a lot of data.
    The scrollpane policy is set using this :
    myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    The problem happens as the list is being updated - sometimes the slider on the scrollbar disappears. It can reappear again, but this behaviour seems completely random.
    This means that if the process completes and the JList stops being updated, the lack of a slider prevents me from reviewing the JList contents.
    Does anyone know why this happens and what I can do to prevent it?

    JList displays the contents of a Vector. The Java version is JDK 1.2.2. And I'm using Windows 2000.

  • JList data model, MVC, is there an example?

    I have a JList, constructed from an AbstractListModel based on an ArrayList, tucked into a JScrollPane. The data model changes frequently en masse, not element by element. I have studied the API documentation of ListModel, ListDataListener, and ListDataEvent. I want to update my Jlist without reconstructing the whole thing, JScrollPane and all, and adding that JScrollPane to a JFrame's content pane in a method called from a distant class. That approach is just not working in the details like screen redraws, no matter the combination of validate(),repaint(), and show() calls I make.
    The data in the ArrayList is there, I'm just trying to notify the AbstractListModel in the JList in the JScrollPane that the data has changed, so presumably it can take care of displaying those changes. The search function for similar posts on the forum is not working for me, and I am running out of resources to study on my own. A set of tutorials by by Dick Baldwin
    http://www.phrantic.com/scoop/onjava.html
    has been the most helpful by far in explaining MVC and its application to JList, but he says,
    "fortunately we can avoid having to deal with the complexity of creating and maintaining a list of registered listener objects, and invoking listener mithods on those objects, by extending AbstractListModel to create our alternative data model..." I don't want complexity either, but I do want to update a data model.
    I need an example of how to use these methods, like addListDataListener(ListDataListener l), fireContentsChanged(Object source,int index0, int index1),
    public ListDataEvent(Object source,int type, int index0, int index1)
    I can't believe that what I want to do is that uncommon or esoteric. Maybe it's just that I'm not seeing something obvious.
    Any pointers?

    Stated differently:
    Here's the API and my error message and my code: is there a way to have just working code and the API, without the compiler error? (recs in the code is my data model, allRecs is the ArrayLIst it's based on)
    API
    fireContentsChanged
    protected void fireContentsChanged(Object source,
    int index0,
    int index1)
    AbstractListModel subclasses must call this method after one or more elements of the list change. The changed elements are specified by a closed interval index0, index1, i.e. the range that includes both index0 and index1. Note that index0 need not be less than or equal to index1.
    Parameters:
    source - The ListModel that changed, typically "this".
    index0 - One end of the new interval.
    index1 - The other end of the new interval.
    See Also:
    EventListenerList, DefaultListModel
    error
    C:\My Documents\Java\CIS 290\hw2\ConnectionHandler.java:173: fireContentsChanged(java.lang.Object,int,int) has protected access in javax.swing.AbstractListModel
    recs.fireContentsChanged(recs,0,allRecs.size());
    codepublic void handleServerMessages(DataInput in)
        done=false;
        int command =0;
        try
            command = in.readInt();
          catch(IOException e)
            e.printStackTrace();
          switch(command)
            case FULLPACKET:{handleFullPacket(in);} break;
            case PARTIALPACKET:
              initializeAllRecs();
              handlePartialPacket(in);
            } break;
            case ALREADYEXISTS: {;} break;
            case DOESNTEXIST: {;} break;
            case BYE: {done = true;} break;
            default: {;}
          recs.fireContentsChanged(recs,0,allRecs.size());
      }

  • Help with display glith using JList

    Hi, first post so bit of background - I'm teaching Java at the moment, am fine with command line but am dabbling more with Swing, despite certain glitches I always get ( e.g. the 7-segment display last year) but anyway....
    I've been trying to develop a little app that picks random boxers for a computer game. My current problem is that i am trying to add custom boxers and then update the JList and repaint the frame. When I add a boxer i can see it adding to the list, however it is unreadable and displayed too small.
    Forgive any bad coding etiquettes - its very much a work in progress from a relatively poor programmer ;)
    theBoxers is a JPanel containing the JLists, aWindow is the JFrame, customButton is a button to add a custom fighter - this gets a name from a field, and a weight from a combo box, adds it to an array and then attempts to add it to an array, then re-generate the lists
    customButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                        addCustom(customCombo.getSelectedIndex(),addCustomName.getText());
                             System.out.println(customCombo.getSelectedIndex() + addCustomName.getText());
                             theBoxers.repaint();
                             aWindow.repaint();
    public void addCustom(int theWeight, String theName)
              switch(theWeight)
                   case 0:          featherCustoms[featherCustomsSize]=theName;
                                  featherFighters = new JList(featherCustoms);
                                  featherCustomsSize++;
                                  break;
                   case 1:          lightCustoms[lightCustomsSize]=theName;
                                  lightFighters = new JList(lightCustoms);
                                  lightCustomsSize++;
                                  break;
                   case 2:          welterCustoms[welterCustomsSize]=theName;
                                  welterFighters = new JList(welterCustoms);
                                  welterCustomsSize++;
                                  break;
                   case 3:          middleCustoms[middleCustomsSize]=theName;
                                  middleFighters = new JList(middleCustoms);
                                  middleCustomsSize++;
                                  break;
                   case 4:          lightHeavyCustoms[lightHeavyCustomsSize]=theName;
                                  lightHeavyFighters = new JList(lightHeavyCustoms);
                                  lightHeavyCustomsSize++;
                                  break;
                   case 5:          heavyCustoms[featherCustomsSize]=theName;
                                  heavyFighters = new JList(heavyCustoms);
                                  heavyCustomsSize++;
                                  break;
                   default:     System.out.println("Not Added");
                                  break;
         }

    Awww, its nice that DB has someone to comeback and carry on a discussion.....long after its over.
    The problem here seems to be your lack of understanding between what a teacher or what an 'instructor' is.
    From the way you speak, an instructor appears to be someone who is technically skilled in both coding and teaching Java as a programming language, designed for people who wish to code in Java.
    A Teacher is someone who must deliver a wide range of subject knowledge to a wide range of abilities, including those who were unable to pass High-School exams. They are responsible for pitching the subject at the correct level for the student, whilst also teaching towards passing the exam, and ultimately gaining a qualification.
    The computing course i am currently teaching does not require OOP, but as Java is the language i was taught at University, and is still often used in our University's, I chose it. I don't pretend to be the best programmer in the world. But I do know that I am teaching the pupils the correct basics, at a higher level than is probably required, to give them the right approach at university. also, this is whilst teaching a large amount of theory.
    Whether you agree, or disagree, matters not to me as I think you would be unfamilier with the specification I am currently teaching to, or what area's of study need to be taught. The exam board appears happy, as do past students who are now well into their university course, as did my marker when i achieved my degree.
    The code posted in the OP (as stated earlier) had nothing to do with displaying my coding abilities, nor did it display the technique's I use when teaching students. It was a small sample of a program which included a JList which was not displaying properly. I tried to include the whole code but it was too big, therefore it was cut down.
    It was a work in progress which i now have working. So now i can look at it again in terms of programming structure. It appears I have made a mistake asking for assistance on here, as instead I got a lecture, with very little insight on your part as to my situation or the nature of the problem/solution.
    At the end of the day, each to his/her own opinion. What I will say is that when someone requests help, positive feedback/criticism is well recieved along with instructions/guidance on how the problem can be solved. I feel that I received none of this on here, but this is what I will always provide to the students I teach.
    Not everyone is a full-time Java programmer or has the time to hit the highest expectations.

  • Update the tree

    Hi,
    I want to update the tree in the thread when I click the button. I tried it. But it is not updating the tree.
    I am putting my code beow, please correct me !!!
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class UserTree extends JFrame {
          DefaultMutableTreeNode root;
          JButton btn = new JButton("Click");
          Vector v ;
         public UserTree(){
               v = new Vector();
               v.add("A");
               v.add("B");
               root = new DefaultMutableTreeNode("Users" );
              for(int i = 0;i < v.size();i++){
                         root.add(new DefaultMutableTreeNode(v));
               JScrollPane js = new JScrollPane( new JTree( root ) );
               getContentPane().add( js );
               getContentPane().add(btn,BorderLayout.SOUTH);
               setSize(400,400);
               setDefaultCloseOperation(EXIT_ON_CLOSE);
              btn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                        new UpdateThread(v).start();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              UserTree ut = new UserTree();
              ut.setVisible(true);
         class UpdateThread extends Thread{
              Vector vector;
              public UpdateThread(Vector v){
                   this.vector = v;
         public void run() {
              // TODO Auto-generated method stub
              EventQueue.invokeLater(new Runnable(){
                   public void run() {                    
                        for(int i=0;i < 5;i++){                         
                             v.add(""+i);               
    }

    Hi corlettk.
    Nice to see u again....
    I can update the JList while I am using DefaultListModel, but I cant update the JTree when using the vector.
    Now whenI clicked the button it is getting hanged the window...
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    public class TableEx extends JFrame{
         JList list;
         JButton btn = new JButton("Click");
         DefaultListModel listModel ;
         public TableEx(){
              listModel = new DefaultListModel();
              list = new JList(listModel);
              JScrollPane sc = new JScrollPane(list);
              getContentPane().add(sc);
              getContentPane().add(btn,BorderLayout.SOUTH);
              btn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        System.out.println("hello");
                        new UpdateThread(listModel).start();
              setSize(300,200);
         public static void main(String arg[]){
              TableEx ex = new TableEx();
              ex.setVisible(true);
         class UpdateThread extends Thread{
              DefaultListModel listModel;
              UpdateThread(DefaultListModel list){
                   this.listModel = list;
              public void run(){
                   final Random random= new Random();
                   while(true){
                   EventQueue.invokeLater(new Runnable(){
                        public void run(){
                        int      i =random.nextInt();
                             if(listModel.contains(""+i)){
                                  listModel.removeElement(""+i);
                             }else{
                                  listModel.addElement(""+i);
         }Edited by: bhanu on Aug 26, 2008 12:21 PM

  • JList repaint()

    I can't post all my code because it is a very large jumble of crap...but here is the situation:
    -I have a "fillList()" method that returns a String [] of information retrieved from a SQL query. (the size can be different with a max size of 10 every time I call fillList())..this method works fine.
    -I have a frame that creates a window with some buttons a picture and a JList in the constructor by simple getContentPane().add(<component>); (I'll worry about layout later).
    -One of these buttons (next10) updates the JList. Here is the code in the event handler:
    resultList = new JList(fillList(data.query));
    resultScrollPane = new JScrollPane(resultList);
    resultsPanel = new JPanel();
    resultsPanel.add(resultScrollPane, "North");
    resultsPanel.add(prev10, "South");
    if(numResultsLeft > 0) 
      resultsPanel.add(next10, "South");
    getContentPane().add(resultsPanel, "North");
    repaint();oh, and the variables are the following types:
    -resultList is a JList
    -resultScrolPane is a JScrollPane
    -resultsPanel is a JPanel
    -(Am I being too obvious yet?)
    -next10 is a JButton
    -prev10 is a JButton
    Now I've tried this a bunch of different ways, and I can't seem to get the JList info to change. I know the data is passed correctly because when I click the JList...well, the right stuff happens at the right indexes...but the old information is still displayed.

    You the man! Sweet! Yeah, I'm using set functions for everything else that updates, but I didn't know JLists have one too. Super Sweet! Much Thanks!

  • Multiple apps using same files, how to lock them?

    Hi all,
    I have a unique situation (or so I think). We are running our apps in Citrix servers, such that many users log in to a single citrix server and run our java apps. The problem is, it will be possible that more than one user might use the same app and start to work with the same file.
    I have seen the new NIO package, read that it has better file locking and stuff. I guess what I am after is a way to graphically display the user using a given file, with some other features. Basically, if user 1 runs the app, and clicks on a file, they have sole access to it. Now, if user 2 runs the same app, what I would like to see if I can do is in user 2's view of the file system, they see somethine like:
    xxxx.txt
    yyyy.xml (user1)
    zzz.bat
    So, somehow, I want to update the JList view of each users view either every so often, or when they click on a file that is being used by another, to let them know that it is locked AND the user who has locked it. This way, they can at least ask that user if they can "unlock" their use of it.
    Ideally, if there is some way for two or more copies of the same program (running on the same or different citrix servers) could communicate with one another to constantly update each other of file lock status, that would be great. However, if this is more complex than a few hundred lines, it is a rare occassion that this will happen so it is not worth the effot. Mainly, I need to minimally make sure that if a file is locked by one user, when another user tries to use it they are notified that it is locked.
    Thanks.

    How about doing file maangement through your server? Keep a database of what files are checked out by whom

  • Multiple instances of the same program

    Well, I'm looking for some help with the following:
    I'm making an app that is suposed to have many instances running at the same time.
    (it's a Swing GUI app).
    I need to get these instances to "find each other", to reflect on all the instances every change made by any of the instances:
    If an user modifies the contents of a JList, then every user seeing that window should see the changes made on that JList. (This one is a particular case, actually, I have the method that updates the JList , so the point is how to fire that method on every instance)
    I'll really appreciate any advice.
    thanks in advance :)
    oh, and i'm sorry for my english :P

    Basically getting each instance to sync with each other is too difficult. To achieve a similar result, you have the following options:
    1) Store the contents of the list box in a database (or flat file - but controlling the locking will be slightly difficult) and have each instace of the application poll the table/file for updates.
    2) Have an RMI server that maintains a the contents of the list box. Each instance of the application registers a callback method with the RMI server. When the list is updated, the RMI server updates all the other clients using the callback method.

  • Help me with this timer stuff

    So here's my code first of all:
    private class TimerListener implements ActionListener{
              @Override
              public void actionPerformed(ActionEvent action) {
                   time--;
                   System.out.println(time);
                   int minute = time/60;
                   int seconds = time%60;
                   updateTime = minute + ":" + seconds;
                   if (time == 0) {
                        timer.stop();
                        if (que.size() != 0){
                             temp = que.remove();
                             time = temp.getPlaytime();
                             timer.start();
                             player.playSong(baseDir + temp.getAudioFileName());
         }this code is located at a class called SongQueue. I have another class called Jukebox which has a song player object in it. Song player has a method called playSong and it takes a string, which is the filename of the song.
    My problem here is that everytime the timer stops, it will search in the queue if there is another Song, if it has then it will start the timer again, until there has been no song in the queue (LinkedList). The main thing is, everytime a timer starts, a song has also to start. But how do I start the song to play then, from the Jukebox class if possible. Any idea??

    yes I do. it is the following:
    package songplayer;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.ListModel;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    public class Jukebox extends JFrame {
         public static void main(String[] args) {
              Jukebox jukebox = new Jukebox();
              jukebox.setVisible(true);
         private JukeboxAccountCollection account;
         private SongQueue queue;
         private JukeboxAccount currentAccount;
         private JTextField input;
         private JButton play;
         private JButton login;
         private JButton logout;
         private JLabel name;
         private JLabel timeRemaining;
         private JLabel playsRemaining;
         private JPanel panelRight;
         private JPanel panelQueue;
         private JPanel panelProperties;
         private JPanel panelLeft;
         private JPanel panelCenter;
         private JList view;
         private JList view1;
         private ListModel model1;
         private ListModel model;
         public static final String baseDir = System.getProperty("user.dir")
                   + "/songfiles/";
         public Jukebox() {
              this.setSize(600, 600);
              queue = new SongQueue();
              account = new JukeboxAccountCollection();
              play = new JButton("Play");
              login = new JButton("Log on");
              logout = new JButton("Log out");
              input = new JTextField("");
              name = new JLabel("Name: ");
              timeRemaining = new JLabel("Time Remaining: ");
              playsRemaining = new JLabel("Plays Remaining: ");
              model = new SongCollection();
              model1 = new SongQueue();
              ((SongCollection) model).addSong(new Song("Jamiroquai",
                        "7 Days In Sunny June", 242, "7 Days in Sunny June.mp3"));
              view = new JList(model);
              view.setSelectedIndex(0);
              view.setPreferredSize(new Dimension(250, 600));
              view.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              JScrollPane pane = new JScrollPane(view);
              pane.setPreferredSize(new Dimension(180, 600));
              view1 = new JList(model1);
              view1.setPreferredSize(new Dimension(200, 200));
              panelQueue = new JPanel();
              panelQueue.add(view1);
              panelProperties = new JPanel();
              panelProperties.setPreferredSize(new Dimension(200, 600));
              panelProperties.setLayout(new GridLayout(7, 1, 5, 5));
              panelProperties.add(input);
              panelProperties.add(name);
              panelProperties.add(timeRemaining);
              panelProperties.add(playsRemaining);
              panelProperties.add(login);
              panelProperties.add(logout);
              panelRight = new JPanel();
              panelRight.setLayout(new GridLayout(2, 1));
              panelRight.add(panelQueue);
              panelRight.add(panelProperties);
              panelCenter = new JPanel();
              panelCenter.setPreferredSize(new Dimension(100, 50));
              panelCenter.add(play);
              panelLeft = new JPanel();
              panelLeft.setPreferredSize(new Dimension(260, 600));
              panelLeft.add(view);
              Container cp = this.getContentPane();
              cp.add(panelRight, BorderLayout.EAST);
              cp.add(panelLeft, BorderLayout.WEST);
              cp.add(panelCenter, BorderLayout.SOUTH);
              LoginListener loginListener = new LoginListener();
              LogoutListener logoutListener = new LogoutListener();
              PlayListener playListener = new PlayListener();
              login.addActionListener(loginListener);
              input.addActionListener(loginListener);
              play.addActionListener(playListener);
              logout.addActionListener(logoutListener);
         private class LoginListener implements ActionListener {
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   if (account.find(input.getText())) {
                        currentAccount = account.getAccount(input.getText());
                        name.setText("Name: " + currentAccount.getID());
                        playsRemaining.setText("Plays Remaining: "
                                  + currentAccount.getPlayRemaining());
                        timeRemaining.setText("Time Remaining: "
                                  + currentAccount.getTimeRemaining() / 60 + ":"
                                  + currentAccount.getTimeRemaining() % 60);
                   } else
                        JOptionPane.showMessageDialog(null, JOptionPane.ERROR_MESSAGE);
         private class LogoutListener implements ActionListener {
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   currentAccount = null;
                   name.setText("Name: ");
                   playsRemaining.setText("Plays Remaining: ");
                   timeRemaining.setText("Time Remaining: ");
         private class PlayListener implements ActionListener {
              @Override
              public void actionPerformed(ActionEvent event) {
                   Song currentSong = (Song) view.getSelectedValue();
                   if (currentAccount == null)
                        JOptionPane.showMessageDialog(null, JOptionPane.ERROR_MESSAGE);
                   if (currentAccount.canPlaySong(currentSong.getPlaytime())
                             && currentSong.canPlayToday()) {
                        currentAccount.debit(currentSong.getPlaytime());
                        playsRemaining.setText("Plays Remaining: "
                                  + currentAccount.getPlayRemaining());
                        timeRemaining.setText("Time Remaining: "
                                  + currentAccount.getTimeRemaining() / 60 + ":"
                                  + currentAccount.getTimeRemaining() % 60);
                        queue.addSong(currentSong);
                        ((SongQueue) model1).addSong(currentSong);
                        view1.updateUI();
                        queue.execute();
                   } else
                        JOptionPane.showMessageDialog(null, JOptionPane.ERROR_MESSAGE);
    }I added the execute method in the songQueue class which is:
    public void execute() {
              if (timer.isRunning() == false) {
                   time = que.peek().getPlaytime();
                   player.playSong(baseDir + que.peek().getAudioFileName());
                   timer.start();
         }so therefore I only have one SongPlayer in my SongQueue. The problem now is how do I update the JList when a song has been finished played and I want to remove that song from the JList. ??

Maybe you are looking for

  • Quicktime movies do not work, please help me

    Hello friends. I have a problem that is absolutely driving me crazy. I belong to a popular pay site that has quicktime videos. I used to use the site and watched the videos, even though I have to use stupid dial-up because I live in the sticks, the v

  • Unable to access vpn box internal address after vpn

    Hi all. My office network is protected by asa5510 firewall with vpn configured. When i vpn into my office network i could not access the firewall via the firewall's internal address using telnet etc even though i have already enable telnet. The firew

  • Large file compression

    Hi there all, I have CS3 extended and have been compiling a series of high resolution photographs into one layer in photoshop.  I have copy and pasted each photo and then stitched them together resulting in a file that is 1.35Gb.  I want to compress

  • Confirmation Reversal and Deletion

    Hi All, Is there a configuration to disable "Delete" and "Return Delivery" buttons for all POs? We have a requirement to do not allow users to perform above actions. We are using SRM 5.0 SP13 Thanks, Nikhil

  • Installed os x 10.6.8 and office 2008 excel not enough memory on start

    I just installed OS 10.6.8 and when I try to run Office 2008 Excel I get a "Not Enough Memory" pop-up and it will not open any files.  Any ideas on how to resolve this?  If not how do I revert back to original operation system?