【问题标题】:Creating JList from HashMap从 HashMap 创建 JList
【发布时间】:2018-12-28 21:09:32
【问题描述】:

我正在为一个假装的健身房构建一个预订系统,我有一个针对客户的课程,一个针对 Gym Sessions 的课程,以及一个将 Sessions 收集到一个 HashMap 中的 Session Manager。

每个会话都有一个哈希映射来收集预订的客户。我有一个带有 GUI 的大师班来执行各种功能。 I would like to be able to open a new JPanel/JFrame containing a Jlist, that when a particular session is selected, it displays the customers which are booked on to it, however I've been unable to find这样做的相关方法。

相关代码如下:

客户类别

public class Customer {

private final String name;
private final String payMethod;
public final UUID uniqueId;

/*
* Constructor for me.davehargest.weekendfitness.customer.struct.Customer
*
* @param String name    The customers name
* @param int id         The sequential ID Reference of the customer
*/
public Customer(String name, UUID uniqueId, String payMethod) {
    this.name = name;
            this.uniqueId = uniqueId;
    this.payMethod = payMethod;
}
}

会话类

public class Session {

private int sessionId;
private String sessionName;
    private double price; // Cost of the session per Person
    private double totalEarnings; // Total Earnings of the Session (Number of People * @price
    private Date sessionDate; //Date that the session takes place
    private int classNumber = 1;
/*
* Generates a HashMap of the Customers that will be booked onto a class    
*/   
public Map <Integer, Customer> customers = new HashMap <>();

 /**
 * Session Constructor
 * Creates a new instance of a session
 * 
 * @param sessionId - An identification ID for the Exercise Session
 * @param sessionName - A description of the actual exercise i.e. "Yoga"
 * @param price - The cost to attend the session per person
 * @param sessionDate
 */

public Session(int sessionId, String sessionName, double price, Date sessionDate) 
{
    this.sessionId = sessionId;
this.sessionName = sessionName;
    this.price = price;
    this.sessionDate = sessionDate;
    totalEarnings = 0;
}

/*
* Method addCustomer
* 
* @param Customer - Adds a new Customer to the Exercise Session 
*/

public void addCustomer (Customer customer)
{
    if (customers.size() >= 20){
        System.out.println("Class is full");
    } else {
            customers.put(classNumber, customer); // Adds in a new Customer to the session ArrayList
            totalEarnings += price; // Adds the per person cost to total fees
            classNumber++;
            System.out.println("Added: " + classNumber + customer);
    }
}

SessionManager 类

public class SessionManager {

    /*
    * A HashMap of all of the different Sessions that WeekEnd Fitness Offers
    */
    public Map<Integer, Session> sessions = new HashMap<>();

    private int sId = 1;

    public SessionManager() {}

    public void addSession(String sessionName, double price, String seshDate) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat ("dd-MM-yyyy HH:mm");
        sessionDate = format.parse(seshDate);
        this.sessions.put(this.sId, new Session(sId, sessionName, price, sessionDate));
        sId ++;
    }
 }

我确信这真的很简单,但目前似乎超出了我的理解范围,任何提示或指示将不胜感激,谢谢!

【问题讨论】:

标签: java swing hashmap jlist


【解决方案1】:

您可以从HashMap 创建一个JList,如下例所示。

import javax.swing.JFrame;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;

public class CustomerList {

  public static void main(String[] args) {
    // Sample data
    Map<Integer, Customer> customers = new HashMap<>();
    customers.put(1, new Customer("Kevin", UUID.randomUUID(), "Cash"));
    customers.put(2, new Customer("Sally", UUID.randomUUID(), "Credit card"));
    customers.put(3, new Customer("Kate", UUID.randomUUID(), "Cash"));

    Vector<ListItem> items = new Vector<>();
    for (Map.Entry<Integer, Customer> entry : customers.entrySet()) {
      items.add(new ListItem(entry.getKey(), entry.getValue()));
    }

    JList list = new JList(items);

    JFrame f = new JFrame("Customer List");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(list, BorderLayout.CENTER);
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

class ListItem {
  private int classNumber;
  private Customer customer;

  ListItem(int classNumber, Customer customer) {
    this.classNumber = classNumber;
    this.customer = customer;
  }

  @Override
  public String toString() {
    // You can change this to suite the presentation of a list item
    return classNumber + " - " + customer.name + " (" + customer.payMethod + ")";
  }
}

class Customer {

  final String name;
  final String payMethod;
  public final UUID uniqueId;

  public Customer(String name, UUID uniqueId, String payMethod) {
    this.name = name;
    this.uniqueId = uniqueId;
    this.payMethod = payMethod;
  }
}

【讨论】:

  • 谢谢!是的,这完全符合我的需要,非常感谢,几天来我一直在摸不着头脑,试图让它发挥作用。
  • 抱歉扩展到这个,我似乎无法让监听器事件为此工作,我认为它应该与这段代码的行一致:ListSelectionListener listSelectionListener = new ListSelectionListener() { public void valueChanged(ListSelectionEvent listSelectionEvent) { 会话会话 = 新会话(this.currentSessions.getSelectedValue());但它一直告诉我它找不到变量 currentSessions?
  • @2PintsofTea,在此代码段中,您正在编写ListSelectionListener 类型的匿名内部类。在该内部类中,this 表示该内部类实例。所以,也许你可以试试&lt;ParentClass&gt;.this.currentSessions 之类的东西(或者你也可以简单地使用currentSessions 而没有“this.”。)。
  • 抱歉最后一个查询,它正在将正确的信息提取到 System.out.println,现在我想获取列表中选择的对象,并将其添加到其他 Hashmap 等中。所以我有 Customer cust = (Customer) currentCustomers.getSelectedValue();据我所知,这应该可以工作,但是我收到了 ClassCast 错误,它说我的 List 不能是对象类的大小写,列表类是我用来根据您的第一个答案填充 JList 的.我是否必须进行某种形式的转换或检索所选的实际对象?等等?
  • 在我的回答中,我使用了ListItem 对象来创建JList。所以,如果我调用list.getSelectedValue(),它将返回一个ListItem 类型的对象。所以,我不能将它转换为 Customer 对象。 (由于我没有看到您的代码,因此我根据一些假设来回答。因此,如果这不起作用,您可以发布另一个问题,其中包含当前问题的详细信息和代码。)
猜你喜欢
  • 1970-01-01
  • 2019-09-30
  • 2013-12-19
  • 2014-06-05
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 2017-05-21
  • 2016-11-10
相关资源
最近更新 更多