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);
}
}
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.
JList contains a constructor
JList(ListModel <E> dataModel)
which means you could create your own ListModel object which accepts your array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.