[英]Java - adding to an inherited JOptionPane
大家晚上好!
我認為對於繼承或JOptionPane我不了解,但基本上我想弄清楚如何在LuxuryCarRental子類中實際使用新的JOptionPane。
當前,如果選擇為“ l”,它將顯示2個對話框,父類中的一個對話框,而我在子類中添加的新對話框。 理想情況下,我只需要一個對話框。 我認為這是不用JOptionPane就能做到的,但我想嘗試使其盡可能與JOptionPane一起使用。
我的代碼:
CarRental.java(父類)
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, int rentalDays)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size.equals("e"))
{
dailyFee = 29.99;
}
else if (size.equals("m"))
{
dailyFee = 38.99;
}
else if (size.equals("f"))
{
dailyFee = 43.50;
}
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
}
public void display()
{
JOptionPane.showMessageDialog(null, "Car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include this in this post
LuxuryCarRental.java(子類)
import javax.swing.JOptionPane;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String name, String zipCode, String size, int rentalDays)
{
super(name, zipCode, size, rentalDays);
if (size.equals("l"))
{
this.setDailyFee(79.99);
String includeChauffeur;
includeChauffeur = JOptionPane.showInputDialog(null, "Include chauffeur? Y/N");
if (includeChauffeur.equals("Y") || includeChauffeur.equals("y"))
{
this.setDailyFee(279.99);
this.setTotalFee(this.getDailyFee()*this.getRentalDays());
JOptionPane.showMessageDialog(null, "Chauffeur @ $200/day = $" + 200 * this.getRentalDays());
}
}
}
}
UserCarRental.java(驅動程序類)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog("Enter name");
String zip = JOptionPane.showInputDialog("Enter zip code");
String size = JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury");
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent"));
CarRental userInfo = new LuxuryCarRental(name, zip, size, days);
userInfo.display();
}
}
任何幫助將不勝感激!
我認為這里的教訓是不要將UI代碼與模型代碼混合在一起。 了解您的CarRental類及其所有子類是邏輯或模型類,在這里可以將其視為對物理或邏輯現實進行建模的類。 應該以這種身份使用它們,並且應該編寫它們,以便可以將信息傳遞到它們中並從其中提取信息,但是它們不應與用戶直接交互。 相反,這是UI(用戶界面)類的職責,在這里,這非常簡單,並且只是您的主要方法。 因此,我建議您從CarRental和LuxeryCarRental中都獲得JOptionPane調用,並在從CarRental對象提取狀態后在主方法中顯示JOptionPane。
否則,如果您絕對必須讓模型類顯示其信息,則可以使用可以完全覆蓋的方法來進行處理。 實際上,您將讓您的子類重寫display()
方法,然后在此處打印出其數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.