1

Is there a way to add all the Strings in an array to a JList? I am using the DefaultListModel and I have no idea how to use it. Isn't there a way to just use addElement then add the array? I tried but it does not work.

Here is my code:

package program;

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.DefaultListModel;
import javax.swing.JFrame; 
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

public class Main{
public static void main(String[] args){

    JFrame frame = new JFrame();
    JPanel pane = new JPanel();
    DefaultListModel model = new DefaultListModel();
    JList list = new JList(model);

    //JFrame, frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    //JPanel, panel
    pane.setLayout(new FlowLayout());
    frame.add(pane);

    //JList, list

    String[] lists = {"asjd.txt", "okay.ss", "jsjs.okay.txt"};

    model.addElement(lists);

    JScrollPane listScroller = new JScrollPane(list);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setLayoutOrientation(JList.VERTICAL);
    list.setVisibleRowCount(3);

    listScroller.setPreferredSize(new Dimension(250, 80));

    listScroller.setBounds(5, 5, 200, 300);
    pane.add(listScroller);




}
}

2 Answers 2

3

Create your own loop:

for (String item: lists)
    model.addElement( item );

Also, the frame should be made visible AFTER all the components have been added to the frame.

listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setBounds(5, 5, 200, 300);

Don't use setPreferredSize(). You already used setVisibleRowCount() to control the size of the JList.

Don't use setBounds(). That is the job of the layout manager.

Sign up to request clarification or add additional context in comments.

Comments

1

JList contains a constructor

JList(ListModel <E> dataModel)

which means you could create your own ListModel object which accepts your array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.