Adding text to jlist

how do i add text to a jlist and make it visible?

an example please
j_baxter99Asked:
Who is Participating?
 
ovidiucraciunConnect With a Mentor Commented:
package noel.tests;

import javax.swing.*;
import java.awt.*;
import java.io.*;

public class JListExample extends JPanel
{
    private JList       list;
    private JScrollPane jsp;
   
    public JListExample()
    {
        super();
        InitComponents();
    }
    public static void main(String s[])
    {
        JListExample listPanel = new JListExample();
        JFrame fr = new JFrame("String to JList example");
        fr.setContentPane( listPanel );
        fr.setBounds( 300, 300, 300, 300 );
        fr.setVisible( true );
    }
    private void InitComponents( )
    {
        setLayout( new BorderLayout() );
        list = new JList();
        list.setModel(new DefaultListModel());
        for ( int k = 0; k < 25; k ++ )
        {
            addStringToList( "Element nomber " + k );
        }
        jsp = new JScrollPane( list );
        add( jsp, BorderLayout.CENTER );
        //File f = new File(".");
        //System.out.println(f. getAbsolutePath());
    }
    private void addStringToList( String str )
    {
        if ( list != null )
        {
            ((DefaultListModel)list.getModel()).addElement( str );
        }
    }
}
0
 
expertmbCommented:
hi,
 try this
 String [] str = {"aa","bb"};
 JList list = new JList(str);
 
mb...
0
 
j_baxter99Author Commented:
Yep i can do that but i want to add to how do i add contents to it dynamically.
e.g

String [] str = {"aa","bb"};
 JList list = new JList(str);

and now i want to add "cc" to my list

how do i do it?
cheers
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
j_baxter99Author Commented:
also how do i update it when it is added, i.e refresh the list.
0
 
j_baxter99Author Commented:
ok i have it but how do i get it to scroll
0
 
muraliramCommented:
Dear j_baxter99,

JList list = new JList(str);
list.addItem("How are you?");

It will get automatically scrolled when the list is growing.

Bye

Murali
0
 
j_baxter99Author Commented:
thats is only for a awt.List it doesnt work that way for JList`s muralirm
0
 
expertmbCommented:
hi,
 inorder to get scrollbar add the Jlist to JScrollPane u will get the scroll bar.

mb...
0
 
j_baxter99Author Commented:
cant get the scroll pane to become visible ???
0
 
expertmbCommented:
 jscrollpane.getViewport().add(list, null).
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.