Problems with JList

Hi all,
I'm trying to use a JList for a program that I'm making.
To initialize the JList, I use the following code:
public static JList menu;
public MadLibsManagerGui() {
menu = new JList(MadLibsGui.getComboInfo());
the getComboInfo() method returns an array of strings. This should work, no? But, it doesn't seem to be working! When i try printing the number of indices in the jlist, i get -1even though all of my strings (from the array) do get displayed in the JList. Any ideas? Thanks so much! any help is greatly appreciated.
PS. Does anyone know how to close a JFrame using the push of a button?

Even when i pass it an integer constant, i get the
exceptionA couple of things:
First of all, the remove(int) method defined in JList is inherited from java.awt.Container: it is used for removing a child Component with the given index from a Container. In other words, you cannot use it to remove items from the list.
In fact, there are no methods defined in the JList API for adding or removing items once the list is created. This is because the ListModel interface that defines the data that backs the JList is immutable.
It is still possible, of course, to add and remove items from a JList. The trick is to use a custom ListModel implementation, such as DefaultListModel, that allows such modifications. See the JList tutorial for examples of this.
Secondly, if something is selected in the list, getSelectedIndex() will not return -1. If the JList you see on your screen has something selected, but getSelectedIndex() returns -1 when called on a JList reference in your code, then chances are good that you have two different JList objects. The JList that you add to the UI is not the same JList instance you refer to when calling getSelectedIndex().

Similar Messages

  • Problems with JList & JTable in Netbeans 5.5

    Hi,
    Netbeans provides good GUI building provider.
    But when i am adding JList inside panel
    and trying to add elements its giving error.
    So how to modify read only code in netBeans 5.5 generated code. ??
    There is problem accessing JList variable to be modify.
    HOW TO ACHIEVE THIS ????
    because When you add JList in your GUI Part.
    Netbeans generates code automatically.
    we can't change it.
    HOW TO DO it... ???

    I have had similar trouble.
    In NetBeans Guieditor, JList and JTable are automatically created in a JScrollPanel. This is good as it saves you lots of formatting.
    PROBLEM: when you click/select the JTable or JList in the GUI Editor the Properties box (right hand side ) only shows properties for the JScrollPane.
    So you will only be able to edit Init code etc for the JScrollPane
    SOLUTION: The "Members View" is a list of members (Panels, Objects, etc) on the left hand side of the screen.
    The JScrollPane is listed there. You simply click on this to expand and select the JTable/JList that it contains.
    When you select the JTable/JList the Properites window (right side of screen) now shows the properties for the component you really want to deal with.
    The code options are very powerful.

  • Serious problems with JLists

    Could someone please look at my code and help me fix it. As you can see there are four JLists. I need to have the choice in list 1 generate the entries for list 2 and so on. I have four temporary methods to 'generateVectors' but I only want to generate the vector AFTER the previous choice has been made.
    Would appreciate any help
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    public class LoginApplet extends JApplet {
         private JList prods,tests,cards,users;
         private Container c;
         private JLabel prodChoice,testChoice,cardChoice,usr;
         private Vector v1,v2,v3,v4;
         private String colorNames[] =
         { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green",
         "Light Gray", "Magenta", "Orange", "Pink", "Red",
         "White", "Yellow" };
         private Color colors[] =
         { Color.black, Color.blue, Color.cyan, Color.darkGray,
         Color.gray, Color.green, Color.lightGray,
         Color.magenta, Color.orange, Color.pink, Color.red,
    Color.white, Color.yellow };
         //private Vector p,t,c,u;
         public void init() {
              c = getContentPane();
              c.setLayout( new FlowLayout() );
              prodChoice = new JLabel("Product: ");
              testChoice = new JLabel("Stage: ");
              cardChoice = new JLabel("Card: ");
              usr = new JLabel("User: ");
              prods = new JList(colorNames);
              prods.setVisibleRowCount( 5 );
              prods.setSelectionMode(
                   ListSelectionModel.SINGLE_SELECTION );
              c.add( new JScrollPane( prods ) );
              c.add(prodChoice);
              prods.addListSelectionListener(
                   new ListSelectionListener() {
                        public void valueChanged( ListSelectionEvent e )
    //this is where I want to generate the entries for the second list,
    //based on the selection in the first
              tests = new JList(getTestVector());
              tests.setVisibleRowCount( 5 );
              tests.setSelectionMode(
                   ListSelectionModel.SINGLE_SELECTION );
              c.add( new JScrollPane( tests ) );
              c.add(testChoice);
              tests.addListSelectionListener(
                   new ListSelectionListener() {
                        public void valueChanged( ListSelectionEvent e )
                             //do something
              cards = new JList(getCardVector());
              cards.setVisibleRowCount( 5 );
              cards.setSelectionMode(
                   ListSelectionModel.SINGLE_SELECTION );
              c.add( new JScrollPane( cards ) );
              c.add(cardChoice);
              cards.addListSelectionListener(
                   new ListSelectionListener() {
                        public void valueChanged( ListSelectionEvent e )
                             //do something
              users = new JList(getUserVector());
              users.setVisibleRowCount( 5 );
              users.setSelectionMode(
                   ListSelectionModel.SINGLE_SELECTION );
              c.add( new JScrollPane( users ) );
              c.add(usr);
              users.addListSelectionListener(
                   new ListSelectionListener() {
                        public void valueChanged( ListSelectionEvent e )
                             //do something
              setSize( 500 , 250 );
              setVisible( true );
         public Vector getProdVector() {
              Vector v1 = new Vector();
              v1.add("None");
              v1.add("APX");
              v1.add("Stinger");
              v1.add("TNT");
              v1.add("Max");
              return v1;
         public Vector getTestVector() {
              v2 = new Vector();
              for (int i=0;i<colorNames.length;i++){
              v2.add(colorNames);
              return v2;
         public Vector getCardVector() {
              v3 = new Vector();
              v3.add("None");
              v3.add("Card1");
              v3.add("Card2");
              v3.add("Card3");
              v3.add("Card4");
              return v3;
         public Vector getUserVector() {
              v4 = new Vector();
              v4.add("None");
              v4.add("user1");
              v4.add("user2");
              v4.add("user3");
              v4.add("user4");
              return v4;
    public static void main ( String args[] ){
    LoginApplet lApp = new LoginApplet();
    lApp.init();

    You should not call the constructor with the items for the other 3 lists if you want this lists empty initially
    users = new JList(); instead of
    users = new JList(getUserVector());
    and then call the method getUserVector() and add the items to the JList in the listener for the previous JList.

  • Problems with JList (multiple selection)

    hi!
    i have a simple question.. why does this construct not work? i recieve a Casting Exception!
    recList is a JList!
    if(source == send){
         String[] rec = (String[])recList.getSelectedValues();
         String message = messageArea.getText();
    thx,
    chris

    You can only cass an Object array to a String array if the array was created as a String array.
    Object[] o = new String[] { "string1", "string2" };
    String[] s = (String[])o; // this works fineIf it was created as an Object array, then you will get a ClassCastException:
    Object[] o = new Object[] { "string1", "string2" };
    String[] s = (String[])o; // throws ClassCastExceptionSo either you have to cast each Object element to a String, or copy all the elements to a String array like this:
    Object[] o = new Object[] { "string1", "string2" };
    String[] s = new String[o.length];
    System.arraycopy(o, 0, s, 0, o.length); // or copy them in a for-loop which may be faster for small arraysReturning you an Object array that was created as an Object array is the easiest way for the JList to return you the selected values. So that's why you can't just cast it to a String array even though YOU know they are all String objects.

  • Problem with a JList and JScrollpane

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

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

  • Problem with JPanel.updateUI()

    Hello,
    i have a problem with updateUI(), here's a simple example what's wrong. just compile and run the following piece of code and look what happens after 2 seconds: the left panel will be decrease its width after calling updateUI(), but why? is it a bug of updateUI() or is it my fault?
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JPanel
            private JList m_list;
            private DefaultListModel m_listModel;
            private JPanel m_buttons;
            public static GridBagConstraints creategbc (int x, int y, int w, int h, int wx, int wy, int f)
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridx = x;
                    gbc.gridy = y;
                    gbc.gridwidth = w;
                    gbc.gridheight = h;
                    gbc.weightx = wx;
                    gbc.weighty = wy;
                    gbc.fill = f;
                    gbc.insets = new Insets(5, 5, 5, 5); // kleinen Rahmen ziehen
                    return gbc;
            public Test ()
                    GridBagLayout gbl = new GridBagLayout();
                    setLayout(gbl);
                    GridBagConstraints gbc;
                    initButtons();
                    gbc = creategbc(0, 0, 1, 1, 20, 100, GridBagConstraints.NONE);
                    gbc.anchor = GridBagConstraints.NORTH;
                    gbl.setConstraints(m_buttons, gbc);
                    add(m_buttons);
                    initList();
                    JScrollPane sp = new JScrollPane(m_list);
                    gbc = creategbc(1, 0, 1, 1, 100, 100, GridBagConstraints.BOTH);
                    gbl.setConstraints(sp, gbc);
                    add(sp);
            public void addItem (String item)
                    m_listModel.addElement(item);
            public void initList ()
                    m_listModel = new DefaultListModel();
                    m_list = new JList(m_listModel);
            public void initButtons ()
                    m_buttons = new JPanel();
                    m_buttons.setLayout(new GridLayout(4, 1, 0, 20));
                    m_buttons.add(new JButton("Neu"));
                    m_buttons.add(new JButton("Bearbeiten"));
                    m_buttons.add(new JButton("L�schen"));
                    m_buttons.add(new JButton("Abfrage"));
            public static void main (String[] args)
                    JFrame f = new JFrame();
                    Test t = new Test();
                    f.setContentPane(t);
                    f.setSize(600, 450);
                    f.setVisible(true);
                    try
                            Thread.sleep(2000);
                    catch (Exception e)
                    t.addItem("Hallo");
                    t.updateUI();

    Hello,
    i have a problem with updateUI(), here's a simple
    example what's wrong. just compile and run the
    following piece of code and look what happens after 2
    seconds: the left panel will be decrease its width
    after calling updateUI(), but why? is it a bug of
    updateUI() or is it my fault?updateUI() its called when the L&F is changed, there is
    rarely a case when you need to call updateUI().
    Why do you call updateUI() if you remove the call to updateUI()
    everything will work OK.
    merry xmas

  • Problem with Drag and Drop (TransferHandler)

    I have a stern problem with the java.swing.TransferHandler. It shows a design weakness, and because of a tiny glitch I am currently not able to finish my task.
    The design weakness is that method importData(JComponent comp, Transferable t) does not pass the dropAction information in the parameter list. The application case in question is a transfer from a JTree to a JTree (might likewise be to/from a JList). The transfer semantics imply that partial success is possible (there are item identity and uniqueness considerations to handle). - I can deal with all detail demands except that I cannot discriminate between COPY and MOVE taking place in the transfer. Also I don't find any possibility to retrieve this information by subclassing TranferHandler or from any other element there.
    Is there any expert who knows a solution?

    I came up with two solutions. One is I modified my application requirements for the time being so the problem disappears. :)
    Second, I had the idea to create a subclass of javax.swing.TransferHandler and copy/override as many methods as necessary to allow for an extra method public boolean importData(JComponent comp, Transferable t, int action) and derive the extra value from a modified method DropHandler.drop(DropTargetDropEvent e) in a copy of the DropHandler.
    Whether this really works, I have not tested.
    As for your answer, Andre_Uhres, I don't find it elaborate enough that it leads to a solution, hence no stars rewarded. You leave it open how to get hold of the DropTarget events which are dealt with privately in javax.swing.TransferHandler.
    I consider the subject closed for my purposes. Thanks very much for your reply!

  • Problem with focus border and ListCellRenderer in custom listbox

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

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

  • Problem with file dialog (root frame)

    Hi guys
    I�m having a problem with open up a filedialog.
    I have a rendered jlist and the are some items inside. The user, can right click any item and choose from a list some commands (print, save, update etc)
    Everything works fine but when he clicks the SAVE option (again, right click and choose save)
    FileDialog fd = new FileDialog(new JFrame(),"Save PAX list",FileDialog.SAVE);
    I cannot use new JFrame() (as I did above) because it might block the application.
    For this I�m trying to get the root by:
    Component c = SwingUtilities.getRoot((Component)e.getSource());
    JFrame myFrame = (JFrame)c;
    And than:
    FileDialog fd = new FileDialog myFrame,"Save PAX list",FileDialog.SAVE);
    This get me a null frame :- (
    Anyone?

    The following worked on a "normal" menu item. I didn't test it on a "popup" menu item:
    JMenuItem mi = (JMenuItem)e.getSource();
    JPopupMenu popup = (JPopupMenu)mi.getParent();
    Component c = SwingUtilities.windowForComponent(popup.getInvoker());
    System.out.println(c);

  • Jpopupmenu visibility problem with JWindows

    Hello,
    BACKGROUND:
    I am attempting to implement a feature similar to one found in the netbeans IDE for a programming editor I am helping to write. The feature is an autocomplete/function suggestion based on the current word being typed, and an api popup for the selected function.
    Currently a JPopupMenu is used to provide a list of suggested functions based on the current word being typed. EG, when a user types 'array_s' a JPopupMenu pops up with array_search, array_shift, array_slice, etc.
    When the user selects one of these options (using the up/down arrow keys) a JWindow (with a jscrollpane embedded in it) is made visible which displays the api page for that particular function.
    PROBLEM:
    The problem is that when a user scrolls down the JWindow the JPopupmenu disappears so he user cannot select another function.
    I have added a ComponentListener to the JPopupMenu so that when componentHidden is called I can do checks to see if it should be visible and make visible if necessary. However, componentHidden is never called.
    I have added a focuslistener to the JPopupMenu so that when it loses focus I can do the same checks/make visible if necessary. This function is never called.
    I have added a popupMenuListener but this tells me when it is going to make something invisible, not actually when it's done it, so I can't call popup.setVisible(true) from popupMenuWillBecomeInvisible because at that point the menu is still visible.
    Does anyone have any suggestions about how I can scroll through a scrollpane in a JWindow whilst still keeping the focus on a separate JPopupMenu in a separate frame?
    Cheers

    The usual way to do popup windows (such as autocomplete as you're doing) is not to create a JPopupMenu, but rather an undecorated (J)Window. Stick a JList in the popup window for the user to select their choice from. The problem with using a JPopupMenu is just what you're experiencing - they're designed to disappear when they lose focus. Using an undecorated JWindow, you can control when it appears/disappears.
    See this thread for information on how to do this:
    http://forum.java.sun.com/thread.jspa?threadID=5261850&messageID=10090206#10090206
    It refers you to another thread describing how to create the "popup's" JWindow so that it doesn't steal input focus from the underlying text component. Then, further down, it describes how you can forward keyboard actions from the underlying text component to the JWindow's contents. This is needed, for example, so the user can keep typing when the autocomplete window is displayed, or press the up/down arrow keys to select different items in the autocomplete window.
    It sounds complicated, but it really isn't. :)

  • Problem with JSplitPane

    Hi!
    I have the following problem with JSplitPane: Whenever I add two components to the splitpane and then add the splitpane to a JPanel, the left component is minimized, i.e. not visible. I always have to manually readjust the splitter in order to see the left component. I also tried a bunch of combinations of setSize, etc. but nothing seems to help.
    Here's some code:
    public void setTables(Vector<DBTable> vec)
              _panel.setSize(650, 500);
              DefaultListModel m = new DefaultListModel();
              _tableList = new JList(m);
              // _tableList.setSize(new Dimension(300, 400));
              _infoArea = new JTextArea();
              _infoArea.setEditable(false);
              // _infoArea.setSize(new Dimension(250, 300));
              MetaDataListener listener = new MetaDataListener(_infoArea, _tableList);
              _tableList.addListSelectionListener(listener);
              for (DBTable table : vec)
                   m.addElement(table);
              JScrollPane scroll1 = new JScrollPane(_tableList);
              JScrollPane scroll2 = new JScrollPane(_infoArea);
              JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, scroll1, scroll2);
              split.setSize(new Dimension(600, 480));
              _panel.add(split, BorderLayout.CENTER);
              scroll1.setPreferredSize(new Dimension(300, 400));
              scroll1.setSize(new Dimension(300, 400));
              scroll2.setPreferredSize(new Dimension(300, 400));
              scroll2.setSize(new Dimension(300, 400));
              _panel.setVisible(true);
                                         //_frame referes to a JInternalFrame and _panel surprisingly to a JPanel
              _frame.getContentPane().add(_panel, BorderLayout.CENTER);
              _frame.setVisible(true);
              split.setDividerLocation(50.0);
         }Thanks!

    Nevermind I fixed it!

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

  • Problem with threads and camera.

    Hi everybody!
    I've a problem with taking snapshot.
    I would like to display a loading screen after it take snapshot ( sometimes i
    have to wait few seconds after i took snapshot. Propably photo is being taken in time where i have to wait).
    I was trying to use threads but i didn't succeed.
    I made this code:
    display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while((!performing.isShown()) && (backgroundCamera.isShown())){
                        Thread.yield();
                    notifyAll();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        this.wait();                   
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();This code is sometimes showing performing screen but sometimes no.
    I don't know why. In my opinion performing.isShown() method isn't working correctly.
    Does anyone have some idea how to use threads here?

    Hi,
    I've finally managed to work this fine.
    The code:
           Object o = new Object();
           display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while(!performing.isShown()){
                        Thread.yield();
                   synchronized(o) {
                      o.notify();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        synchronized(o) {
                           o.wait(1);
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();

Maybe you are looking for

  • Can no longer attach pdf files into email.

    I recently purchased a new computer with Windows 8.1 as the OS.  Seems that I am no longer able to attach PDF files into any email.  Any clues as to what has gone wrong?

  • AS3 loadMovieNum() ?

    Hi! How can I do this in AS3: loadMovieNum("test.swf", 2) ??? Why change Adobe the simple commands to complicated commands in AS3? Why wasn't good for example "on(release)"? It's simple, don't like this: mybutton.addEventListener(MouseEvent.MOUSE_DOW

  • Packages,patches,RPM required in Oracle Linux 6 for EBS R12 installation.

    Hello, I am a not a newbie and i am trying to do a vision installation of Oracle EBS R12 on my laptop. I have downloaded Oracle Enterprise Linux release 6 update 3 media pack from edelivery.com and installed Oracle Linux on Vmware workstaion. Now i w

  • 3D Shape taking forever to render

    Hello All, I have simple composition that animates a two shapes that I am using as a "screen" to show photos.  The shapes are 3D; the camera movement is minimal.  I have an Ambient light and two Spot lights.  I am on a one year old i7 processor with

  • When Cached Web Content reaches about 30-50 MB, webpages are loaded incomplete

    Webpages are incomplete: only headlines HTML style, no pictures, etc. After emptying the cached web content, page load fine. Until 30-50 MB is reached, etc.