How to load a JList in horizontal manner?

↘锁芯ラ 提交于 2020-01-04 14:09:19

问题


How to load a JList in horizontal fashion?? Here is my code,I am trying to display the JListsimilar to the screen shot provided.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.BorderLayout;
import java.io.File;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;

public class Test extends JFrame{

    private JList toolsList;
    private ArrayList<File> toolXmlList;

    public Test()
    {
    toolXmlList = new ArrayList<File>();
    toolXmlList = loadFiles();

    setVisible(true);
    setSize(300,300);
    setTitle("Test Jlist");
    createComponents();

    }

    public void createComponents()
    {
    toolsList = new JList();
    toolsList.setModel(displayDefaltTools());
    toolsList.setLayoutOrientation(javax.swing.JList.VERTICAL_WRAP);
    setLayout(new BorderLayout());
    add(toolsList,BorderLayout.CENTER);
    }

    /**
     * Creates a list model and add the tools to it
     *
     * @return DefaultListModel
     */
    public DefaultListModel displayDefaltTools() {
    DefaultListModel dlistModel = new DefaultListModel();
    String presentation = "";

    for (int i = 0; i < toolXmlList.size(); i++) {
        //System.out.println(idSet.get(i));
        presentation = presentation +  toolXmlList.get(i).getName() ;
        dlistModel.addElement(presentation);
        presentation = "";
    }
    return dlistModel;
    }

    public ArrayList loadFiles()
    {
    ArrayList<File> xmlFiles = new ArrayList<File>();
    File f = new File(".");
    File [] folList = f.listFiles();
    for(int i=0;i<folList.length;i++)
    {
        if(folList[i].getName().startsWith("Tool_Frag"))
        {
            File[] fileList=folList[i].listFiles();
            for(int j=0;j<fileList.length;j++)
            {
                System.out.println(fileList[j].getName());
                xmlFiles.add(fileList[j]);
            }
        }
    }
    return xmlFiles;
    }

    public static void main(String[] args)
    {
    new Test();
    }
}

I am trying to get a jlist in this manner,items displayed one next to another


回答1:


You will have to do two things:

  1. Set the LayoutOrientation to JList.HORIZONTAL_WRAP or JList.VERTICAL_WRAP as per the documentation.

  2. Make the list wide enough that it can display more than one element per row. Use setVisibleRowCount() for this.

    Calling setPreferredSize() also works but can cause trouble when you use layout managers.

Alternatively, consider using a JTable if you must make sure a certain number of rows/columns (like all elements in a single line).



来源:https://stackoverflow.com/questions/13967375/how-to-load-a-jlist-in-horizontal-manner

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!