Adding a JList to a JScrollPane

Searching through the archives, this appears to be a pretty frequent question, but so far, none of the answers have worked for me. Behold, what I have:
Filelist = new JList(Filelistmodel);
FilePane = new JScrollPane();
FilePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
FilePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
FilePane.setMaximumSize(new Dimension(650,150));
FilePane.setMinimumSize(new Dimension(650,150));
FilePane.setPreferredSize(new Dimension(650,150));
FilePane.setBounds(150, 0, 650, 150);
FilePane.setViewportView(Filelist);
panel.add(FilePane);     Message was edited by:
break_the_chain

Ok, here's the context. It's not exactly simple, but it should compile and the rest of the code is more or less outside of the problem.
package formshow;
//import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;
public class Sync extends JApplet
     JButton bttn1;
     JComboBox Cbox_drives, Cbox_folders;
     JPanel panel;
     JFrame aframe;
     JScrollPane FilePane;
     DefaultListModel Filelistmodel;
     JList Filelist;
     class OnlyPRE implements FilenameFilter
       Vector PRE;
       public OnlyPRE(Vector PRE)
       {this.PRE = PRE;}
       public boolean accept(File dir, String name)
                          boolean accept = false;
          for (int i=0; i<PRE.size(); i++)
          if (name.startsWith((String)PRE.get(i)))
          accept = true;
       return accept;
     public void init()
          //applet listener
          this.addFocusListener( new FocusListener()
            public void focusGained(FocusEvent evt)
                               getContentPane().invalidate();
               getContentPane().validate();
          public void focusLost(FocusEvent evt)
             getContentPane().invalidate();
             getContentPane().validate();
                         //this applet
          this.setSize(800,150);
          //jpanel
          panel = new JPanel(null);
          //Button init stuff
          bttn1 = new JButton("Get Files");
          bttn1.setSize(150,50);
          bttn1.setLocation(0,100);
          bttn1.addActionListener( new ActionListener()
             public void actionPerformed(ActionEvent evt)
             {PopList();}
          panel.add(bttn1);
          //Cbox_drives init stuff
          int offset = 'a';                    
          Cbox_drives = new JComboBox();
          for (int i=0; i<26; i++)
          Cbox_drives.addItem((char)(offset+i)+":\\");               
          Cbox_drives.setSize(150,50);
          Cbox_drives.setLocation(0,0);
                          Cbox_drives.addActionListener( new ActionListener()
            public void actionPerformed(ActionEvent evt)
               try                                  {
                getPatFolders();
              catch (Exception e)Cbox_drives.setBackground(Color.RED);}
          panel.add(Cbox_drives);
          //Cbox_folders init stuff
          Cbox_folders = new JComboBox();
          Cbox_folders.setLocation(0,50);
          Cbox_folders.setSize(150,50);
          Cbox_folders.addItem("Pick the drive letter you have mapped to 1416_a");
          panel.add(Cbox_folders);
          //Filelist init stuff
          Filelist = new JList();
          Filelist.setVisibleRowCount(5);
          //FilePane init stuff
          FilePane = new JScrollPane(Filelist);
          FilePane.setLocation(150,0);
          FilePane.setSize(650,150);
          panel.add(FilePane);
          getContentPane().add(panel);                              
          private int getPatFolders () throws Exception
               String drive = (String) Cbox_drives.getSelectedItem();
               String files[];
               Vector prelist = new Vector();
               prelist.addElement("PAT");
               prelist.addElement("REL");
               prelist.addElement("EME");
               FilenameFilter onlyget = new OnlyPRE(prelist);
               Cbox_folders.removeAllItems();
               try{
               File rootFolder = new File(drive);
               files = rootFolder.list();
               catch (Exception E)
               files = new String[]{"Error Here"};
               for (int i=0; i<files.length; i++)
                    Cbox_folders.addItem((String)files);               
               return (1);
          private int PopList()
               File StartFolder = new File(((String)Cbox_drives.getSelectedItem())+
(String)Cbox_folders.getSelectedItem()));
               PopList(getFiles(StartFolder));
               Filelist.removeAll();
               Filelist = new JList(Filelistmodel);
               FilePane = new JScrollPane();
               FilePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
               FilePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
               FilePane.setMaximumSize(new Dimension(650,150));
               FilePane.setMinimumSize(new Dimension(650,150));
               FilePane.setPreferredSize(new Dimension(650,150));
               FilePane.setBounds(150, 0, 650, 150);
               FilePane.setViewportView(Filelist);
               panel.add(FilePane);     
               getContentPane().invalidate();
               getContentPane().validate();
               return(1);
          private int PopList(Vector transmute)
               Filelistmodel = new DefaultListModel();
               for (int i=0; i<transmute.size(); i++)
                    Filelistmodel.addElement(transmute.elementAt(i));
               return(1);
          private Vector getFiles(File ThisPath)
               Vector ThisLevel = new Vector();               
               String FileList[] = ThisPath.list();
               for (int i=0; i<FileList.length; i++)
                         File afile = new File(ThisPath.getAbsolutePath()+"\\"+FileList[i]);
                         if (afile.isFile())
                              ThisLevel.addElement(afile.getAbsolutePath());
                         else
                              append(ThisLevel,getFiles(afile));                              
               return ThisLevel;
          private Vector append(Vector Left, Vector Right)
               for (int i=0; i<Right.size();i++)
                    Left.addElement(Right.get(i));
               return Left;
Ok, basically this is for windows users. Pick a drive letter, then pick a folder from the next combo box.
Hit the button and a list of all of the files in the folders and subfolders shows up in the JList on the right.
DO NOT try this when the second list box is pointing to something like windows or program files.
I'd recommend creating your own folder that goes maybe one or two levels deep with just a bunch of empty text files.
I will <3 anyone that can help me with this forever and bestow upon them rediculous numbers of dukestars.
Message was edited by:
break_the_chain

Similar Messages

  • JList(Vector) inside JScrollPane vanishes!

    Hi all, I have a problem thats driving me crazy, Im really stumped on this one;
    Im trying to update the GUI on a packet sniffer I wrote a while ago,
    I have a GUI class below as part of a larger program, this class containes a JList(Vector) inside a JScrollPane inside a JPanel inside a JFrame, I want this JList to be on the screen all the time, and grow dynamically as new elements are added to the Vector.
    Elements are added via an accessor method addPacket(Capture), you can assume the other classes in my program work fine.
    The problem is, the JFrame periodically goes blank, sometimes the scrollbars are present, sometimes not. After a while (sometimes) the JList reappears, containing the list of packets as it should, but it never lasts very long. Often it will disappear permanently.
    The class below is pretty short and simple, I really hope this is a simple and obvious mistake Ive made that someone can spot.
    Thanks,
    Soothsayer
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.InputStream;
    public class GUI extends JFrame
         Dimension screenResolution = Toolkit.getDefaultToolkit().getScreenSize();
         private InputStream fontStream = this.getClass().getResourceAsStream("console.ttf");
         Font outputFont;
         static final Color FIELD_COLOR = new Color(20, 20, 60);
         static final Color FONT_COLOR = new Color(150, 190, 255);
         private static JPanel superPanel = new JPanel();
         private static Vector<Capture> packetList = new Vector<Capture>(1000, 500);
         private static JList listObject = new JList(packetList);
         private static JScrollPane scrollPane = new JScrollPane(listObject);
         public GUI()
              super("LineLight v2.1 - Edd Burgess");
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocation(50, 10);
              try { outputFont = Font.createFont(Font.TRUETYPE_FONT, fontStream); }
              catch(Exception e) { System.err.println("Error Loading Font:\n" + e); }
              outputFont = outputFont.deriveFont((float)10);
              listObject.setFont(outputFont);
              superPanel.setPreferredSize(new Dimension(screenResolution.width - 100, screenResolution.height - 100));
              superPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
              scrollPane.setPreferredSize(new Dimension(screenResolution.width - 100, screenResolution.height - 100));
              scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollPane.setWheelScrollingEnabled(true);
              superPanel.add(scrollPane);
              this.add(superPanel);
              this.pack();
         public void addPacket(Capture c)
              this.packetList.add(c);
              this.listObject.setListData(packetList);
              this.superPanel.repaint();
    }

    I'm having basically the same problem, And how is your code different than the example in the tutorial???
    You can also read the tutorial section on "Concurrency".
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
    Start your own posting if you need further help.

  • How can I get the selected row's index of a Jlist wrapped with JScrollpane?

    the problem is that I can use getSelectedIndex() only if the JList is not wrapped in a JScrollPane.
    but in my program the JList IS wrapped in a JScrollPane.
    when I select one item of the jscrollpane I can't catch the event.
    please F1 me.
    Lior.

    What difference does it make if the list is inside a scroll pane or not? If you have a member varialbe that references the list you can call getSelectedIndex when ever you need.
        myList = new JList (...)
        someComponent.add (new JScrollPane (myList));
        //  Then later
        int sel = myList.getSelectedIndex ();And you can always be up on any selection chagnes in the list by supplying it with a ListSelecitonListener.

  • JList performance in JScrollPane

    Hi!
    I've got a really odd problem with JList handling inside a JScrollPane.
    What happens is that I populate the JList with elements from a vector, and it displays them allright, but when I add or remove any element after creating the jList for first time, the CPU usage goes crazy until I move the scrollbar knob of the ScrollPane it's in. After moving the knob, the elements display ok, and cpu usage goes down to normality.. I can reproduce this phenomenon every time.
    At first I thought it was a performance issue, but after implementing a custom minimal cell renderer (which I actually don't use anymore) and adjusting the prototypecell and fixed size properties, this kept happening... Any ideas are welcome!
    Thanks!
    P.S:The code is a little large, but I'll post it if it helps!

    Seems to work for meimport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Test2 extends JFrame {
      Vector data = new Vector(10000);
      DefaultListModel dlm = new DefaultListModel();
      JList jl = new JList();
      public Test2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        for (int i=0; i<10000; i++) dlm.addElement("Stuff-"+i);
        jl.setModel(dlm);
        JButton jb = new JButton("Remove");
        content.add(jb, BorderLayout.SOUTH);
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            int index = jl.getSelectedIndex();
            if (index>=0) dlm.remove(index);
        content.add(new JScrollPane(jl), BorderLayout.CENTER);
        setSize(300,300);
      public static void main(String[] args) { new Test2().setVisible(true); }
    }

  • Java Turduckin: JScrollPane in a JList in a JScrollPane

    Probably a quick answer for someone: I have a JScrollPane containing a JList. The JList has a custom renderer that returns a subclass of JScrollPane: the idea is a scrollable list of individual panels of scrollable text.
    Is this possible? When I run it, it looks ok (the inner scroll bar hilights correctly, etc), but, even after a fair amount of investigation, I can't get the inner scrollbar to respond to the mouse. Can I get JList to forward clicks?
    Many thanks,
    -bmeike

    Renderers return a picture, not something you can interact with.
    Try setting your inner JScrollPane as the editor.

  • Adding a JPanel to a JScrollPane?

    I have a JPanel which may hold a lot of components, this may run off the end of the window so I want to add the components to a JPanel and the JPanel to a JScrollPane to deal with this can anyone tell me why the below code won't do this?
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.ScrollPaneConstants;
    public class Test extends JScrollPane
         public JFrame testFrame;
         public JPanel testPanel;
         public JCheckBox checkBox;
         public static void main(String[] args)
              new Test();
         public Test()
              testFrame = new JFrame("test");
              //testFrame.getContentPane().setLayout(null);
              testPanel = new JPanel();          
              JScrollPane sp = new JScrollPane(testPanel);
              //add the panel to the scroll pane
              //sp.setViewportView(testPanel);
              //sp.getVerticalScrollBar();
              this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              testFrame.getContentPane().add(sp);
              //add the scroll pane to the frame
             JLabel lbl1 = new JLabel("blah");
             testPanel.add(lbl1);
            testFrame.getContentPane().add(testPanel);
             for(int i=0; i==20; i++)
                   checkBox = new JCheckBox(String.valueOf(i));
                  //checkBox.addItemListener(this);
                  JTextField txt1 = new JTextField(10);
                  txt1.setText("hello world");
                 testPanel.add(checkBox);
                testPanel.add(txt1);
            testPanel.validate();
            testPanel.setVisible(true);
            testFrame.pack();
            testFrame.setVisible(true);
            testFrame.setSize(100, 200);
            testFrame.show();
    }

    Actually not extending JScrollPane means that
    this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    raised compile errors so you've clearly not bothered to run it.
    Anyway, I figured out the solution, for anyone who may find it useful here it is:
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    public class Test
         public JFrame testFrame;
         public JPanel testPanel;
         public JCheckBox checkBox;
         public JButton btnDone;
         public static void main(String[] args)
              new Test();
         public Test()
              testFrame = new JFrame("test");
              testPanel = new JPanel();
              testPanel.setLayout(new GridBagLayout());
              JScrollPane sp = new JScrollPane();
              GridBagConstraints gridBagConstraints = new GridBagConstraints();
             JLabel lbl1 = new JLabel("blah");
             testPanel.add(lbl1);
             for(int i=0; i<20; i++)
                   checkBox = new JCheckBox(String.valueOf(i));
                  //checkBox.addItemListener(this);
                  JTextField txt1 = new JTextField(10);
                  txt1.setText("hello world");
                 gridBagConstraints.gridx = 0;
                 gridBagConstraints.gridy = i+1;
                 testPanel.add(checkBox, gridBagConstraints);
                 gridBagConstraints.gridx = 1;
                 gridBagConstraints.gridy = i+1;
                 testPanel.add(txt1, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = gridBagConstraints.gridy+1;
            testPanel.add(btnDone = new JButton("Done"), gridBagConstraints);
              sp.setViewportView(testPanel);
             testFrame.getContentPane().add(sp);
             //btnDone.addActionListener(this);
            testPanel.validate();
            testFrame.pack();
            testFrame.setVisible(true);
            testFrame.setSize(200, 300);
            testFrame.show();
    }

  • Adding to JList Issues

    I'm trying to make a class that will add objects to a JList by reading out of a text file at the punch of a button.
    This is what I came up with:
    public void importAction() {
            try {
                FileReader fileReader = new FileReader("children.txt");
                File file = new File("children.txt");
                BufferedReader buff = new BufferedReader(fileReader);
                int childrenInFile = Integer.parseInt(buff.readLine());
                    for (int childrenOnList = 1; childrenOnList < childrenInFile; childrenOnList++ ) {
                        jList1 = new JList(listmodel);
                        listmodel.addElement(buff.readLine());
            } catch (IOException ex) {
        }...but obviously that didn't work for me.
    It compiled correctly but when I pressed the import button in the applet, nothing happened.
    I have googled this issue thoroughly.

    Let's say you have 100 child elements. Then that one statement assigns a class variable called jList1 to 99 different JList objects (discarding them all) before settling down with the 100'th JList object. You then proceed to not actually do anything with this new JList component - like add it to a visible hierarchy. You can delete the statement all together.
    Assuming that listmodel is the actual model of the JList you are trying to change, and that JList is already visible, then what you have here
    listmodel.addElement(buff.readLine()); should be sufficient to see a some sort of change. Because you don't see any change, then the next question is what is "listmodel"? Is it the model of a JList in a visible hierarchy?

  • Having problems getting JListBox to show scrollbars`

    Hi Java Experts
    I'm having problmes getting JListBox to show scrollbars -- basically it is not.
    I'm using the gridbag layout.
    here's my code.
    CollectingList = new JList(data);
    CollectingList.setVisibleRowCount(30);
    JScrollPane scrollPane3 = new JScrollPane(CollectingList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
    then i add it like this
    add(CollectingList, constraints,     4, 3, 1, 1, p3);
         private void add(Component c, GridBagConstraints constraints, int y, int x, int w, int h, JPanel p2 )
              constraints.gridx = x;
              constraints.gridy = y;
              constraints.gridwidth = w;
              constraints.gridheight = h;
              p2.add(c,constraints);
    any ideas why my list box refuses to show scrollbars ?
    thanks
    stev     

    Unless it's somewhere else in your code and not posted....I don't see where you are adding your JList to your JScrollPane, then adding your scrollPane to your applet/application.
    Check out the JScrollPane in the tutorial.

  • Adding JScrollPane to a JList problems

    Hi,
    I am having problem in trying to add a JScrollPane to a JList, it doesnt appear i don't understand what i am doing wrong.
    private String [] mainMenu = {"Phonebook", "Messages", "User Options", "Phone Status"};
    private JList main = new JList(mainMenu);
    private JScrollPane scrolling = new JScrollPane(main);
    public Mobile()
             main.setLocation(60, 110);
             main.setSize(90, 50);
             add(scrolling);
             scrolling.setVisible(true);
    }

    The code to run the app is:
    import java.awt.*;
    import javax.swing.*;
    class MobileGUI {
         public static void main(String[] args) {
              JFrame frame = new JFrame("Mobile Phone Simulation");
              Container pane = frame.getContentPane();
              pane.add(new Mobile());
              frame.setSize(340, 625);
              frame.show();
    }The class that contains the components is:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    class Mobile extends JComponent {
    private String[] mainMenu = {"Phonebook", "Messages", "User Options", "Phone Status"};
    private JList main = new JList(mainMenu);
    private JScrollPane scrolling = new JScrollPane(main);
    public JTextArea display = new JTextArea(6, 30);
    public MobileGUI()
              //Displays
              setLayout(null);
              //Display for messages
              display.setLocation(120, 60);
              display.setSize(90, 50);
              add(display);
              display.setVisible(false);
              //MainMenu Jlist Display
              main.setLocation(120, 60);
              main.setSize(90, 50);
              add(scrolling);
              scrolling.setVisible(true);
         public void paint(Graphics g) {
         g.setColor(Color.gray.brighter());
         g.fillRoundRect(30, 30, 270, 530, 40, 20);
         g.setColor(Color.black);
         g.fillArc(30, 30, 270, 320, 0, 180);
        g.fillArc(30, -180, 270, 740, 180, 180);
         g.setColor(Color.gray);     
         super.paint(g);       
    }The JList does not appear neither does the JScrollPane

  • JScrollPane now showing up with JList using TableLayout

    Hi,
    I have JFrame using TableLayout. On this JFrame I have added a JPanel that uses TableLayout too. Now this panel is divided into 4 cells. One each cell I am adding a JList. ALl the lists show up fine on the appropriate cells on the panel, but they don't hav any scroll bars. Below is the code.
    Please help.
    Thx, Sid.
    DefaultListModel listModel = new DefaultListModel();
    JList list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    list.setVisibleRowCount(-1);
    listScroller = new JScrollPane(list);
    listScroller.setPreferredSize(new Dimension(250, 80));
    listScroller.setVerticalScrollBarPolicy(
         JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    listScroller.setHorizontalScrollBarPolicy
         (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    panel.add(list, new TableLayoutConstraints(2*itr1, 0, 2*itr1, 0, 
                        TableLayout.FULL, TableLayout.FULL));
    lg.getListModel().addElement("Element1");
    lg.getListModel().addElement("Element2);
    .

    Okay, I think I know what I am doing wrong. I need to add the JScrollPane to the panel and not the JList!

  • JLists in JScrollPane in JFrame

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

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

  • JList dynamically adding items

    I am inserting items into a Jlist dynamically by reading from a network port .The items get added but my problem is list box always shows the top portion of the list.
    Is there any way i can make the list to scroll down as and when i add items into it.
    Thanks

    No its still not working i am doing in an applet
    heres my code
    public class QueryResults extends JApplet implements Runnable{
            Thread resultReader =null;
            Socket sock =null;
            BufferedReader in =null;
            PrintWriter pw =null;
            JList resultList = new JList(new DefaultListModel());
            JScrollPane sp =new JScrollPane(resultList);
            public void init(){
                try{
                    sock= new Socket("localhost", 4444);
                    pw=new PrintWriter(sock.getOutputStream(), true);
                    in=new BufferedReader(new InputStreamReader( sock.getInputStream()));
                    resultList.ensureIndexIsVisible(resultList.getModel().getSize());
                    sp.setAutoscrolls(true);
                    Container contentpane=getContentPane();
                    contentpane.setLayout(new FlowLayout());
                    contentpane.add(sp);
                }catch(IOException e){
                    e.printStackTrace();
            public void start(){
                resultReader=new Thread(this);
                resultReader.start();
            public void run(){
                try{
                    String line;
                    while((line=in.readLine())!= null){
                        ((DefaultListModel)resultList.getModel()).addElement(line);
                        resultList.repaint();
                        SwingUtilities.invokeLater(new Runnable(){public void run()
                            sp.getVerticalScrollBar().getModel().setValue(sp.getVerticalScrollBar().getModel().getMaximum());
                            //spane.getVerticalScrollBar().setValue(spane.getVerticalScrollBar().getMaximum() );
                        //resultList.ensureIndexIsVisible(resultList.getModel().getSize());
                        //resultList.repaint();
                        //sp.getVerticalScrollBar().getModel().setValue(sp.getVerticalScrollBar().getModel().getMaximum());
                }catch(IOException e){
                    e.printStackTrace();
            public void stop(){
                try{
                    pw.close();
                    in.close();
                    sock.close();
                }catch(IOException e){
                    e.printStackTrace();
    }

  • 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 in JScrollPane never shows horizontal scroll bar

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

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

  • JScrollPane (added to a JPanel, which paints) is visible but does nothing

    Hi. I am writing a program that reads data from files and does paiting using the info. The top level window is a JFrame, which is divided into two parts - A Box which contains the buttons through which the user interacts and a JPanel on which the painting is done. I have added the JPanel to a JScrollPane, but have run into problems there. The JScrollPane is visible (both policies always visible) but it does nothing. I understand that when the drawing is fitting, the ScrollPane is not used. But even if I make the window small or draw something that is not visible in the normal are, the JScrollPane doesn't work. In fact, no knob is visible on either of the two scrollbars. I am pasting the relevant code below:
    //import
    public class MainWindow extends JFrame {
        public static void Main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel;   
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
    } I hope this helps you get an idea of what I am trying to do and what the problem might be. Any help would be really appreciated. I have spent hours on this and I have no idea why it doesn't work.
    The actual code is much bigger, so if you need any extra information, please tell me.

    HelloPanel should provide a "public Dimension getPreferredSize()" method.
    With your code you create a simple JPanel and want to draw outside of it, but you never tell the JScrollPane that your HelloPanel is actually bigger than it seems, that's why it does not feel the need to add scroll bars.
    Here's the working code:
    //import
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class MainWindow extends JFrame {
        public static void main(String[] args) {
            new MainWindow();
        //Declare all the variables here.
        private Box buttionBox;
        private JScrollPane scroller;
        private HelloPanel drawingPanel; 
        //other variables
        //The constructor for the class MainWindow.
        public MainWindow() {
           initComponents();
            this.setLayout(new BorderLayout());
            this.setPreferredSize(new Dimension(900,670));
            //buttonBox containts the buttons - not very relevant to this problem.
            //this.getContentPane().add(buttonBox, BorderLayout.WEST);
            //scroller is the JScrollPane
            this.getContentPane().add(scroller, BorderLayout.CENTER);       
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("My Title");       
            this.setVisible(true);
            this.pack();       
        public void initComponents() {
            //buttonBox = Box.createVerticalBox();
            //instantiate the buttons here and add them to the ButtonBox.
            //The event listeners instantiated. Not relevant.       
            //The various components are assigned their appropriate event listeners here.
             //Not relevant.
    //Now adding all the buttons to the box with proper spacing.
            //buttonBox.add(Box.createVerticalStrut(20));
            //This is the drawing panel on which the drawing will be done.
            drawingPanel = new HelloPanel();
            scroller = new JScrollPane(drawingPanel);
                    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scroller.getHorizontalScrollBar().setUnitIncrement(10);
            scroller.getVerticalScrollBar().setUnitIncrement(10);
        //This inner class is used to define and implement the event listener for handling the checkboxes.
        private class checkBoxListener implements ItemListener{
            public void itemStateChanged(ItemEvent e){
                 drawingPanel.repaint();
                    //Implement actions. Irrelevant
        //This private class is used to define and implement the event listener for the buttons.
        private class buttonListener implements ActionListener {
            //Do this when the button which has an instance of this class as its listener is clicked.       
            public void actionPerformed(ActionEvent e) {
                //if (e.getSource() == saveStructureButton){
                  //Implement action. Irrelvant.
        //The panel on which the drawings are done.
        private class HelloPanel extends JPanel {
            //This JPanel is used for drawing the image (for the purpose of saving to disk).
            JComponent c;    //For image. Irrelevant.
            public HelloPanel(){           
                c = this;   //This is necessary for drawing the image to be saved to disk.
                this.setBackground(Color.WHITE);
            //This is the method that actually paints all the drawings whenever a.
            //The shapes theselves can be defined somewhere else, but that paint method must be invoked from here.
            public void paintComponent(Graphics g){
                super.paintComponent(g);    //First of all, clear the panel.
                Graphics2D g2 = (Graphics2D) g;
                g2.fill(new Rectangle2D.Double(40,40,100,100));    //Just for this post.
                g2.drawString("Text", 750, 750);    //To test the scrollpane.
         public Dimension getPreferredSize()
         return new Dimension(750,750);
    }

Maybe you are looking for

  • How can I erase songs from my iPhone that I bought on iTunes Store but keep them on my Music Library?

    I'm having this problem, that I bought some songs from my iPhone in iTunes Store, but I don't want to have them in my iPhone anymore. I tried to erase the songs from my Music Library, but when I syncronize the iPhone automatically, these songs are co

  • IMac 24" monitor weird white light

    hello everybody, i do really need help for my iMac monitor , i have some weird white signs on the top left and top right side of the monitor , they look like a weird light but it's not, i can't better explain so i post two pics: http://gallery.me.com

  • Why is the CMD-TAB app switcher still unable to properly focus apps?

    On my MacBook Pro running OSX Lion 10.7.5, and on previous versions of OSX, I've noticed a very strange defect in the way the graphical environment switches applications. To reproduce the problem, I open three apps (it does not seem to matter what ap

  • Autosuggest - external .XML file

    Hello all, I'm hoping someone may be able to help me on this... I am trying to setup the AutoSuggest widget to access information from my database, but don't seem to be having any luck! I have created a script (fetch.asp) that pulls the information o

  • Using iTunes on new iMac

    Yesterday I received my new iMac, which replace a 2009 model.  The transfer of data and reinstalling my apps went flawlessly until I tried to synch my iPhone.  Before I tried to synch I deauthorized the old iMac and authorized the new one and I backe