简体   繁体   中英

Displaying multiple JList to JFrame

I am trying to put many JList in different scroll panes displaying only 2 names. I am storing mt lists in a vector of vectors this structure is representing the days of the week with multiple "shifts" in each day.

import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.*;

public class AutoScheduel extends JFrame{
private JList leftlist;
private JList leftlist1;
private JList tempList;
private int frameX = 50;
private int frameY = 50;
//private JList rightlist;
//private JButton movebutton;
static Employee Amanda = new Employee("Amanda",0,false); static Employee      Austin = new Employee("Austin",0,false); static Employee Conner = new Employee("Conner",0,false);
static Employee Faith = new Employee("Faith",0,false); static Employee Jospeh = new Employee("Jospeh",0,false); static Employee Lexi = new Employee("Lexi",0,false);
static Employee Matthew = new Employee("Matthew",0,false); static Employee     Samie = new Employee("Samie",0,false); static Employee Tanner = new     Employee("Tanner",0,false);
static Employee Valerie = new Employee("Valeire",0,false); static Employee     Will = new Employee("Will",0,false); static Employee Zack = new     Employee("Zack",0,false);
private static String[] employeesNames= {Amanda.getName(),Austin.getName(),Conner.getName(),Faith.getName(),Jospeh.getName(),
        Lexi.getName(),Matthew.getName(),Samie.getName(),Tanner.getName(),Valerie.getName(),Will.getName(),Zack.getName()};
private Vector<JList> weekday;
private Vector<JList> weekend;
private Vector<Vector<JList>> v;
public AutoScheduel(){
    super("Cambridge AutoSchedueler");
    setLayout(new FlowLayout());
    pack();
    setLocationRelativeTo(null);
    leftlist = new JList(employeesNames);
    leftlist.setVisibleRowCount(2);
    leftlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    //add(new JScrollPane(leftlist));

    leftlist1 = new JList(employeesNames);
    leftlist1.setVisibleRowCount(2);
    leftlist1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    //add(new JScrollPane(leftlist));

    v = new Vector<Vector<JList>>();
    weekday = new Vector<JList>();
    weekend = new Vector<JList>();
    for(int i=0;i<6;i++){
        weekday.addElement(leftlist);
    }
    for(int i=0;i<5;i++){
        weekend.add(leftlist1);
    }
    for(int i=0;i<5;i++){
        v.add(weekday);
    }
    v.add(weekend);
    v.add(weekend);

    tempList = new JList();
    leftlist.setPreferredSize(new Dimension(50,20));
    //leftlist.setLocation(50, 50);
    //add(new JScrollPane(leftlist));
    //add(new JScrollPane(v.get(1).get(3)));


    for(int i = 0; i<v.size();i++){
        for(int j = 0 ; i<v.get(i).size();i++){
            tempList = v.get(i).get(j);
            frameY += 40;
            tempList.setLocation(frameX,frameY);
            add(new JScrollPane(tempList));
        }
        frameX += 50;
    }




}
public static void main(String[] args){
   AutoScheduel go = new  AutoScheduel();
   go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   go.setSize(600, 600);

   go.setVisible(true);

}

}

Currently I get one list displayed with the correct list I want but there is just dots preceeeding that list saying there is a number of lists stacked on each other. I think this is because I'm using flow layout. When I try and use different lists and then add it to the Jframe it works but since I need like 34 lists I would like to just use a for loop to put them in my vector. If anyone could help with the formatting in the JFrame that would be awesome, I need it held within a data structure where I can still access the elements and set up to look like a week with selectable lists. Thanks in advance

You need to create a new JList and a new model for the JList for each JList that you wish to display. Your current code only creates 3 JLists and tries to place them repeatedly within the GUI, but that won't work.

For instance, say you wanted to display 5 JLists for the 5 work days of the week, one that shows employee names, you could create a collection of JLists and in a for loop create your 5 JLists, each with model. Also, don't extract the names from your Employee objects, but instead fill the JList with actual Employee objects and use a renderer to tell the JList to show only the employee name. For example:

在此处输入图片说明

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

@SuppressWarnings("serial")
public class Scheduler2 extends JPanel {
    private static final Employee2[] employees = { 
            new Employee2("Amanda", 0, false), 
            new Employee2("Austin", 0, false),
            new Employee2("Conner", 0, false), 
            new Employee2("Faith", 0, false), 
            new Employee2("Jospeh", 0, false),
            new Employee2("Lexi", 0, false), 
            new Employee2("Matthew", 0, false), 
            new Employee2("Samie", 0, false),
            new Employee2("Tanner", 0, false), 
            new Employee2("Valeire", 0, false), 
            new Employee2("Will", 0, false),
            new Employee2("Zack", 0, false) };
    private static final String[] WEEK_DAYS = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

    // associates each list with the day of the week
    private Map<String, JList<Employee2>> weekDayListMap = new HashMap<>();

    public Scheduler2() {
        // layout to hold 1 row, multiple columns
        setLayout(new GridLayout(1, 0));
        // renderer that shows employee names only
        EmployeeCellRenderer cellRenderer = new EmployeeCellRenderer();
        for (int i = 0; i < WEEK_DAYS.length; i++) {
            // new model for each week
            DefaultListModel<Employee2> listModel = new DefaultListModel<>();
            for (Employee2 employee : employees) {
                // fill the model
                listModel.addElement(employee);
            }
            // new list for each day of the week with model
            JList<Employee2> list = new JList<>(listModel);
            list.setVisibleRowCount(4);
            list.setCellRenderer(cellRenderer); // so shows name only
            String prototypeName = "aaaaaaaaaaaaaaaaaaa";
            list.setPrototypeCellValue(new Employee2(prototypeName, 0, false));
            weekDayListMap.put(WEEK_DAYS[i], list); // put in collection (if needed)
            JScrollPane scrollPane = new JScrollPane(list);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

            // if we want a border around the jscrollpane showing the day of the week
            JPanel container = new JPanel(new BorderLayout());
            container.add(scrollPane);
            container.setBorder(BorderFactory.createTitledBorder(WEEK_DAYS[i]));
            add(container);
        }
    }

    // JList renderer to display only names
    private class EmployeeCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            if (value == null) {
                value = "";
            } else {
                Employee2 empl = (Employee2) value;
                value = empl.getName();
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Scheduler2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new Scheduler2());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

// you never gave us the employee class, so I had to create one of my own
class Employee2 {
    private String name;
    private int value;
    private boolean bool;

    public Employee2(String name, int value, boolean bool) {
        this.name = name;
        this.value = value;
        this.bool = bool;
    }

    public String getName() {
        return name;
    }

    public int getValue() {
        return value;
    }

    public boolean isBool() {
        return bool;
    }
}

Regarding,

Can you expalin where do you actually add the list into the frame?

I add the JList to a JScrollPane. I can then add the JScrollPane to the main JPanel, the this as it were, but since I want to put a border around the JScrollPane with the day of the week, I create another JPanel, called container, give it a BorderLayout, add the JScrollPane to it, BorderLayout.CENTER (by default) and then give this outer "wrapper" JPanel a title border with the day of week String. I then add this to the main JPanel. It's all here:

// create JList w/ model
JList<Employee2> list = new JList<>(listModel);

// .....

// add JList to JScrollpane
JScrollPane scrollPane = new JScrollPane(list);


// .....

// create "wrapper" JPanel 
JPanel container = new JPanel(new BorderLayout());
container.add(scrollPane);  // and place JScrollPane into it
container.setBorder(BorderFactory.createTitledBorder(WEEK_DAYS[i]));

// add wrapper JPanel to the GUI
add(container);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM