我在GUI设计中声明了几个swing组件。我已成功将大多数组件转换为String格式,如下所示:
String NameOfCruise = Cruisename.getText().trim(); //JTextField
String startLValue = startL.getSelectedItem().toString(); //JComboBox
String endLValue = endL.getSelectedItem().toString(); // JComboBox
new SimpleDateFormat("dd/MM/yyyy").format(model1.getValue())); //JSpinner
String Shipname = ShipList.getSelectedValue().toString(); // JList
上述组件的目的是构建一个允许用户向系统添加新Cruise的表单。获得上面的所有表单输入后,我想将它存储到ArrayList中。
ArrayList Cruise = new ArrayList();
但是,我想以这种格式存储它:
Cruise Name: ________
Start Port: _________
End Port: _______
Start Date: _________
End Date: _______
Assigned to ship: ______
因此,如果我可以选择列出系统中的所有巡航,则会将其显示为一个对象。例如,如果我在ArrayList中有一个Cruise,它将显示分配给它的所有细节。
有办法做到这一点吗?
答案 0 :(得分:1)
您可能会将数据与其表示混淆。我想你将在你的ArrayList<Cruise>
中存储Cruise对象,所有这些都是纯数据,包括字符串,日期等,这应该是程序的 Model 的一部分。它的显示方式取决于您的GUI或 View 。如果你想以你提到的格式显示List<Cruise>
,你可以在JList中这样做,并让单元格渲染器返回一个JPanel,其中的相应字段用Cruise的各个属性填充。
答案 1 :(得分:0)
以下是如何使用正确数据表示的示例:
public static void main(String[] args) {
List<Cruise> cruiseList = new ArrayList<Cruise>();
cruiseList.add(new Cruise("Cruise 1", "Florida", "Puerto Rico", new Date(), new Date(), "Captain X"));
System.out.println(cruiseList.get(0));
}
private static class Cruise {
private String name;
private String startPort;
private String endPort;
private Date startDate;
private Date endDate;
private String assignedToShip;
public Cruise(String name, String startPort, String endPort, Date startDate, Date endDate, String assignedToShip) {
super();
this.name = name;
this.startPort = startPort;
this.endPort = endPort;
this.startDate = startDate;
this.endDate = endDate;
this.assignedToShip = assignedToShip;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Cruise Name: ").append(name).append("\n");
sb.append("Start Port: ").append(startPort).append("\n");
sb.append("End Port: ").append(endPort).append("\n");
sb.append("Start Date: ").append(startDate).append("\n");
sb.append("End Date: ").append(endDate).append("\n");
sb.append("Assigned to ship: ").append(assignedToShip).append("\n");
return sb.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartPort() {
return startPort;
}
public void setStartPort(String startPort) {
this.startPort = startPort;
}
public String getEndPort() {
return endPort;
}
public void setEndPort(String endPort) {
this.endPort = endPort;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getAssignedToShip() {
return assignedToShip;
}
public void setAssignedToShip(String assignedToShip) {
this.assignedToShip = assignedToShip;
}
}