I'm writing a simple Java program.
First, the program asks user to input some info like name and id of the student and uses radio button for asking whether the student is present or absent. After finishing the inputs, then program validate whether predefined student names and inputs are match or not. And check id number again and spit out if input is over 4. Lastly check radio button is true or false. If one of the above two rules get error then program will quit without executing next method.
I have three .java files. One for UI. One for validation and one for storing data.
UI.java
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UI extends JFrame {
JTextField name = new JTextField("Name", 10);
JTextField id = new JTextField("Id", 10);
JRadioButton attendance = new JRadioButton("Present");
JButton JB = new JButton("Check");
public UI() {
super("Test");
JPanel JP = new JPanel();
JP.add(name);
JP.add(id);
JP.add(attendance);
JP.add(JB);
add(JP);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void buttonAction(){
UI UIbutton = new UI();
UIbutton.JB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == UIbutton.JB) {
String nameInput = UIbutton.name.getText();
int idInt = Integer.parseInt(UIbutton.id.getText());
boolean attInput = UIbutton.attendance.isSelected();
Validate.nameChk(nameInput);
Validate.idChk(idInt);
Validate.attChk(attInput);
Student studentObj = new Student(UIbutton.name.getText(), idInt, UIbutton.attendance.isSelected());
System.out.println(studentObj.name + "'s ID number is : " + studentObj.id + ".");
System.out.println(studentObj.name + " is present: " + studentObj.attendance);
System.exit(0);
}}});
}
public static void main(String[] args) {
buttonAction();
}
}
Validate.java
public class Validate {
public static void nameChk (String nameInput) {
String n1 = "Matthew";
String n2 = "John";
String n3 = "Mark";
String n4 = "Luke";
if ((nameInput.equalsIgnoreCase(n1))||
(nameInput.equalsIgnoreCase(n2))||
(nameInput.equalsIgnoreCase(n3))||
(nameInput.equalsIgnoreCase(n4))){
System.out.println("Your data is okay.");
}
else {
System.out.println("Error, wrong student name.");
System.exit(0);
}
}
public static void idChk (int idInt) {
if (idInt > 4) {
System.out.println("Your id is not correct.");
System.exit(0);
}
else {
System.out.println("Your id is correct.");
}
}
public static void attChk (boolean attInput) {
if (attInput) {
System.out.println("The student is present.");
} else {
System.out.println("The student is absent.");
}
}
}
Student.java
public class Student {
String name;
int id;
boolean attendance;
Student(String name, int id, boolean attendance) {
this.name = name;
this.id = id;
this.attendance = attendance;
}
}
What I want to know is how can I reuse output of that actionlister method somewhere else. Let say I would create foo.java class and use that studentObj variable to give grades like
System.out.println(studentObj.name+"has B+.");
Sort of.
How can I do that? How to turn that variable into global?
This can be achieved in different ways.
Quite simple, but not a good practice would be to create a Singleton. It would contain Students objects and you'll be able to access them from anywhere. Here is example with eager singleton, but you can implement much better versions (check about singleton implementations i.e. here https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples)
public class StudentsSingleton {
private Map<Integer, Student> students = new HashMap<>();
public Student getStudent(int id) { return students.get(id);}
public void addStudent(Student s) { students.put(s.id, s);}
private static final StudentsSingleton instance = new StudentsSingleton();
//private constructor to avoid client applications to use constructor
private StudentsSingleton(){}
public static StudentsSingleton getInstance(){
return instance;
}
}
In that case, you can access it from anywhere by getting the instance :
StudentsSingleton.getInstance().getStudent(id);
A much better solution and a good practice would be to use some Dependency Injection framework i.e. Spring. In that case, you would create a Bean and inject it whenever it is needed to use.
Related
i thinkj i have a type argument problem which im really confused about, Ive started with an Arraylist which, extends to the another class with my main methods. and i have a Events class, which i want to categorize from the txt file, the main problem i have is adding from my txt file which iread into an ArrayList, java pops up with this error message
incompatible types: java.lang.String cannot be converted to CSC8012.Events
But in my events it has String? Im really confused
This is my generic arraylist i think?
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable> extends
ArrayList<E> {
public void insert(E e) {
this.add(e);
int lastIndex = 0;
for( lastIndex = this.size() -1 ; lastIndex > 0 && this.get(lastIndex-1).compareTo(e) > 0 ; lastIndex--){
this.set(lastIndex, this.get(lastIndex-1));
}
this.set(lastIndex,e);
}
}
Heres my events class objects
public class Events implements Comparable<Events>{
//fields setting up the variables
String ticketsbought;
String eventname;
public Events(String ticketsbought, String eventname ){
this.ticketsbought = ticketsbought;
this.eventname = eventname;
}
#Override
public int compareTo (Events E){
return
ticketsbought.compareTo(E.getTicketsbought()) + eventname.compareTo(E.getEventname());
}
public String getTicketsbought() {
return ticketsbought;
}
public String getEventname() {
return eventname;
}
//setting it up for the main method from the constructor fields above
public void setTicketsbought(String ticketsbought) {
this.ticketsbought = ticketsbought;
}
public void setEventname(String eventname) {
this.eventname = eventname;
}
#Override
public String toString()
{
return "Tickets bought " + this.ticketsbought + "Event name " + this.eventname;
}
}
My main menu class
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Objects;
import java.util.ArrayList;
import java.util.Collections;
java.util.Scanner;
public class MainProgram extends SortedArrayList{
public static void main(String[] args) throws FileNotFoundException{
boolean bye = false;
String line;
String option;
Scanner sc = new Scanner(System.in); //tos take in our input
do{
System.out.println("Choose an option.."); // heres our options
System.out.println("e Information on all events");
System.out.println("c All information on clients");
System.out.println("f to quit");
System.out.println("b to update when tickets are bought by a registered Client");
System.out.println("r to update the stored data when a Client cancels a ticket");
option = sc.nextLine();
switch (option) { // these are splitting our inputs to these cases with different outcomes
case "e":
//System.out.println("information on events");
Scanner inFile = new Scanner(new FileReader("input.txt"));
// Other declarations// Reading and processing the input data// Printing out the results outFile.close();
ArrayList<Events> events = new ArrayList<>();
while(inFile.hasNextLine()) {
String data = inFile.next();
events.add(data);//error based on these? Event is based off of arraylist<E> and inherits from those whilst i have them as string?
You are seeing the exception because of Generics in Java.
Your ArrayList is declared to take Events objects.
ArrayList<Events> events = new ArrayList<>();
However, you are trying to add a String object to it.
String data = inFile.next();
events.add(data); //Cannot add a String object, only Events object allowed.
One way to fix this is to create an Events object using the String, and then add to the Arraylist. I am assuming each line has Event name and String in it, separated by a comma.
//Get your event name and tickets from the String data.
String tokens[] = data.split(",");
String eventName = tokens[0];
String ticketsBought = tokens[1];
//create an events object
Events eventObj = new Events(eventName, ticketsBought);
//Now add to your arraylist.
events.add(eventObj);
As an aside, you do not need to extend SortedArrayList in MainProgram. The main class is usually top level class in your project, and it will only contain objects (this is a common practice). If you want to use the new logic you have added in SortedArrayList, then instead of creating ArrayList<Events> events = new ArrayList<>();, you can create SortedArrayList<Events> events = new SortedArrayList<>();
I'm very new with Java and was introduced to it by creating Minecraft plugins. I am currently using Spigot and want a variable to be accessed through another class. In this plugin, I want players to be able to create a Hero that has certain abilities. The two classes that I use are below.
package me.placerwiz;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class Moba extends JavaPlugin {
StompCooldown a;
#Override
public void onEnable() {
getServer().getPluginManager().registerEvents(new MenuClick(this), this);
new PlayerListener(this);
new StompAbility(this);
getLogger().info("This plugin has been enabled!");
a = new StompCooldown(this);
a.runTaskTimer(this, 20, 20);
getCommand("pearl").setExecutor(new WarpAbility());
getCommand("menu").setExecutor(this);
}
#Override
public void onDisable() {
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("Menu") && sender instanceof Player) {
Player player = (Player) sender;
player.openInventory(Menu.getMenu());
return true;
}
return false;
}
public static void sircunningham1_1(String args[]) {
SirCunningham_1_1 getLoadout = new SirCunningham_1_1();
getLoadout.heroChosen();
}
public static void sircunningham2_1(String args[]) {
SirCunningham_2_1 getLoadout = new SirCunningham_2_1();
getLoadout.heroChosen();
}
public void gotHero(String heroChoice) {
if (heroChoice == "") {
}
}
public boolean heroTest(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("hero") && sender instanceof Player) {
Player player = (Player) sender;
player.openInventory(Menu.getMenu());
return true;
}
return false;
}}
The code above is my main class, Moba. In this code, a variable called heroChoice is received from the other class. The only problem from this is that I want the code to get what the player has selected as the hero. When it gets the hero, I want it to get the hero that the player has selected. Is there anyway I can get a variable sent to the Moba class after the player clicks on the final inventory item. It might need to use this class where the player selects the final ability for the hero "Sir Cunningham". (See code below)
package me.placerwiz;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class SirCunningham_2_1{
static String hero;
public static Inventory getMenu(){
Inventory inv = Bukkit.createInventory(null, 18, ChatColor.GREEN + ChatColor.BOLD.toString() + "Choose ultimate ability!");
ItemStack item = new ItemStack(Material.IRON_BOOTS);
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(" ");
lore.add(ChatColor.YELLOW + "Thoughts of glory inspire your team to");
lore.add(ChatColor.YELLOW + " win this battle! Everyone on your team");
lore.add(ChatColor.YELLOW + " gains a buff!");
meta.setLore(lore);
meta.setDisplayName(ChatColor.GOLD + ChatColor.BOLD.toString() + "Glory");
item.setItemMeta(meta);
inv.addItem(item);
return inv;
}
#EventHandler
public static void onClick(InventoryClickEvent event) {
if (!ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("Choose ultimate ability!"))
return;
Player player = (Player) event.getWhoClicked();
event.setCancelled(true);
if(event.getCurrentItem()==null || event.getCurrentItem().getType()==Material.AIR || !event.getCurrentItem().hasItemMeta()){
player.closeInventory();
return;
}
if(event.getCurrentItem().getType() == Material.IRON_BOOTS){
player.closeInventory();
String hero = "SirCunnigham_2_1";
player.openInventory(Customizer.getMenu());
}
else{
player.sendMessage(ChatColor.GREEN + "[" + ChatColor.YELLOW + "MOBA" + ChatColor.GREEN + "]" + ChatColor.GOLD + "-Under Construction-");
player.closeInventory();
}
}
public static void heroChosen(){
String heroChoice = hero;
Moba sendLoadout = new Moba();
sendLoadout.gotHero(heroChoice);
}
}
All I need to get this to work is to have the String hero (from the if event above) to equal the String heroChoice. Thanks for reading this far and I hope this will get solved. It means a lot to me!
Do not "hide" a variable! You have a static variable named "hero" of type String but you have created another one with the same type and the same name of the static one. So you want to get the name of the hero.
Declaring that variable static you make that variable equal to all of the instances of that class.
Keep reading if you want to know the real solution.
Note, using OOP (Object-Oriented Programming) is a more efficient way to do this.
From what I understood from the question, you want associate an hero name to a player.
You can simply do it with an HashMap.
public static HashMap<Player,String> playerHero = new HashMap<Player,String>();
or if you're using Java 8
public static HashMap<Player,String> playerHero = new HashMap<>();
To add a player AND a hero name do
MyClass.playerHero.put(player, heroName);
To get the heroName from the player:
MyClass.playerHero.get(player);
To get the players from the heroName:
You can make a method:
public static List<Player> getPlayers(String heroName){
List<Player> players = new ArrayList<Player>();
for(Map.Entry<Player,String> e : MyClass.playerHero.entrySet()){
if(e.getValue().equalsIgnoreCase(heroName)){
players.add(e.getKey());
}
}
return players;
}
All these variables are static, so we can access them with MyClass.variableName
All these methods are static, so we can access them with MyClass.method(parameters);
Hope this helped!
You could use the static modifier for heroChoice and all methods that work with your variable, but this is not best practice because in many cases you will not be able to use static and even for this case, you can't make the Bukkit API's EventHandlers static. So what do you do? Its simple.
Use OOP, pass instance of invoking object's variable through constructor
Every object can have constructors, the constructors contain code that will be run when an instance of that object is created. You can also pass paremters to a constructor just like you would a method. As a result, you can simply pass the variable you want from one class into the constructor of the other and store it. For example:
class Car { //my class Car
double topSpeedMPH; //when a Car is created, it needs to get a top speed
public Car(double topSpeedMPH) { //public constructor for Car, requires a double parameter
this.topSpeedMPH = topSpeedMPH; //set the class' topSpeedMPH variable to the local one
}
}
Then in the invoking code:
double speed = 10;
Car fordFusion = new Car(speed);
So for your code specifically:
class Moba {
String heroChoice; //Moba has heroChoice stored
public Moba(String choice) { //Moba constructor, requires a String (which is the choice)
this.heroChoice = choice; //stores the parameter String to use later
}
}
class SirCunningham_2_1 {
public void heroChosen(){
String heroChoice = hero;
Moba sendLoadout = new Moba(heroChoice);
sendLoadout.gotHero(heroChoice);
}
}
Another solution: Use OOP, pass instance of the entire invoking object through constructor using this keyword
The previous solution is great for just one variable, but what if I wanted to be able to access multiple variables from another object? It would be rather inconvenient to make each of them individual parameters. Luckily, there is a good way to do this. Simply pass the entire instance through. The following example (using Car again) shows it:
class Motor {
Car myCar;
double topSpeed;
double accel;
public Motor(Car c) { //require instance of car
this.myCar = c;
this.topSpeed = myCar.topSpeed; //get values from instance
this.accel = myCar.secondsTo60;
}
}
class Car {
Motor m;
double topSpeed = 108;
double secondsTo60 = 8;
int seats = 4;
public Car() {
m = new Motor(this); //use this keyword to pass entire instance
}
void startEngine() {
System.out.println("Vroom Vroom!");
}
}
A big advantage to this solution is that I could even use methods from the other class:
public Motor(Car c) { //require instance of car
this.myCar = c;
this.topSpeed = myCar.topSpeed; //get values from instance
this.accel = myCar.secondsTo60;
myCar.startEngine();
}
Currently I am teaching myself Java but I came across a simple problem but have no one to ask from. From one of the exercises, I wrote a class and write a driver class that instantiates and updates several objects. I am confused by "instantiates and updates several objects." Here is what I mean: So here is my class:
public class PP43Car {
private String make = "";
private String model = "";
private int year;
public PP43Car(String ma, String m, int y)
{
make = ma;
model = m;
year = y;
}
public void setMake(String ma)
{
make = ma;
}
public String getMake()
{
return make;
}
public void setModel(String m)
{
model = m;
}
public String getModel()
{
return model;
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
public String toString()
{
String result = "Make of the vehicle: " + make +
" Model of the vehicle " + model +
" Year of the vehicle: " + year;
return result;
}
}
Which instantiates make, model and year. Then once I was writing the driver class, the way I began was:
import java.util.Scanner;
public class PP43CarTest {
public static void main(String[] args) {
PP43Car car1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the model of the vehicle:");
car1.getModel();
}
}
But this class produces error and here is where I am stuck. Do I keep on going with this or is this what is meant by "instantiating and updating several objects?"
import java.util.Scanner;
public class PP43CarTest {
static PP43Car car1;
public static void main(String[] args) {
//Scanner scan = new Scanner(System.in);
car1 = new PP43Car("Millenia", "Mazda", 2011);
}
}
If the above code is correct, then can anyone show me how I can use the Scanner class to actually get the user input and update it that way because I would like to learn that as well?
Well, in your last fragment of code you are indeed instantiating an object, since you are doing:
car1 = new PP43Car("Millenia", "Mazda", 2011);
When you create a new object, you are creating a new instance of the class, so yes, you are instantiaing an object.
But you aren't updating it anywhere, because I think here updating means modifying the object, but you only create the object, not modify it...
Something like this would be an update:
car1.setYear(2013);
Since you are setting a different value for an attribute of the object, you are updating it...
EDIT: Try this code, it can't throw any exception, it's Java basics! I hope it clarifies your doubts...
public class PP43CarTest {
public static void main(String[] args) {
//Declaring objects
PP43Car car1;
PP43Car car2;
PP43Car car3;
//Instantiating objects
car1 = new PP43Car("Millenia", "Mazda", 2011);
car2 = new PP43Car("Aaaa", "Bbb", 2012);
car3 = new PP43Car("Ccc", "Ddd", 2012);
//Updating objects
car1.setMake("Xxx");
car1.setMake("Yyy");
car1.setYear(2013);
//Printing objects
System.out.println("CAR 1: " + car1.toString());
System.out.println("CAR 2: " + car2.toString());
System.out.println("CAR 3: " + car3.toString());
}
}
I've reached a brick wall in a Java sample project been working on. My goal with this project is to calculate interest using user input to determine what kind of account is being used, and calculating based on each specific account type.
Right now I have created a factory method "public Account createAccount". I need it to accept the string parameter from the user prompt. To tell me if it is Checking, Savings or CD. Now here is where I run into trouble. I have to pass the user value for the "accttype" to a new object specific for each account type. My problem is I just don't know how to do this. Do I have to implement in the factory method? How can I pass these values? Thanks in advance
Account.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Account implements ActionListener {
JButton calculate;
private int period;
private int balance;
private int fbalance;
private int rate;
private int monthlyFee;
private String printstring;
#Override
public String toString() {
return String.format("Period: " + period + ", Balance: " + balance);
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getFbalance() {
return fbalance;
}
public void setFbalance(int fbalance) {
this.fbalance = fbalance;
}
public String getPrintstring() {
return printstring;
}
public void setPrintString(String printstring) {
this.printstring = printstring;
}
public void calculate() {
for ( int i = 0; i<period; i++)
{
fbalance = balance + balance * rate - monthlyFee;
}
}
public void actionPerformed(ActionEvent e) {
calculate();
}
}
Banker.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Banker {
// Array for type of bank account
private static void createAndShowGUI() {
// Declare strings for period, balance, rate
String period;
String balance;
String rate;
// Prompt for account type
String[] accttype = { "Checking", "Savings", "CD" }; // Array of bank acct types
String input = (String) JOptionPane.showInputDialog(null, "Choose account...",
"Choose bank account type", JOptionPane.QUESTION_MESSAGE, null,
accttype, // Array of acct types
accttype[0]); // First choice
// Prompt user for input
period = JOptionPane.showInputDialog(null, "Number of periods (length):");
balance = JOptionPane.showInputDialog(null, "Beginning balance:");
rate = JOptionPane.showInputDialog(null, "Interest rate (use decimal, example: .05 = 5%):");
// Make Calculate button
JButton calculate = new JButton("Calculate");
// Make 2 Labels
JLabel blabel = new JLabel("Period: " + period);
JLabel plabel = new JLabel("Balance: " + balance);
// Setup window with flow layout and exit on close
JFrame frame = new JFrame("Interest Savings Calculator Plus");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add combo box, calc button and labels
frame.add(calculate);
frame.add(plabel);
frame.add(blabel);
frame.pack();
frame.setVisible(true);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
public Account createAccount(String type){
}
}
If you want to use the Account class for all three account types, I suggest adding a constructor to your Account class and a variable to hold the account type like so:
public class Account implements ActionListener {
...
private String accountType = null;
public Account(String accountType) {
this.accountType = accountType;
}
...
}
Then, you can create a new Account object in the createAccount() method and return it like so:
public Account createAccount(String type) {
Account account = new Account(type);
return account;
}
Then you can simply pass the account type in (which is what your "input" variable gets set to in the createAndShowGUI() method):
Account account = createAccount(input);
Otherwise, you could also simply add the accountType variable with getters and setters, and simply create a new Account and call a set method, but I recommend using a constructor that accepts those values as parameters.
Being that you probably also want the other variables to be set in your Account object, you could call the setters on the Account object you return, or you could modify your createAccount() method and the Account constructor to accept more parameters and pass them in when you create the new Account object.
I am designing a basic telephone directory for a project. It has three classes, Main (for the GUI), TelephoneDirectory (an object to store TelephoneRecords objects) and a TelephoneRecords class (where information for each record object is stored).
The requirements state: Extend your application by adding a list displaying the complete current contents of the telephone directory, ordered alphabetically by name. You will need to implement a ListModel. You may want to study class AbstractListModel before starting on your own implementation.
Only problem is, I have absolutely no idea how to extend my application to achieve this. I have searched online all night and haven't found a way to do this. I have tried storing the objects in an AbstractListModel rather than a HashMap but get errors. I don't exactly know what or why it is used and how I could use it. The next requirement (by the way) is to have the JList auto-update with new data when it's entered so I guess it has something to do with that?
Either way, if anyone could help it'd be great. My current working code for the previous that needs to be edited version is:
MAIN
public class Main extends JFrame implements ActionListener {
private static TelephoneDirectory directory = new TelephoneDirectory();
private JTextField nameField;
private JTextField numberField;
private JList contactList;
public Main() {
setTitle("Telephone Directory");
setLayout(new GridLayout(0,2));
JLabel nameLabel = new JLabel("Name of Contact:");
nameField = new JTextField(20);
add(nameLabel);
add(nameField);
JLabel numberLabel = new JLabel("Number of Contact:");
numberField = new JTextField(20);
add(numberLabel);
add(numberField);
JButton enterButton = new JButton("Enter");
JButton cancelButton = new JButton("Cancel");
enterButton.addActionListener(this);
cancelButton.addActionListener(this);
add(enterButton);
add(cancelButton);
JLabel contactsLabel = new JLabel("Current Contacts:");
contactList = new JList();
add(contactsLabel);
add(contactList);
setVisible(true);
pack();
}
public static void main(String[] args) {
new Main();
}
#Override
public void actionPerformed(ActionEvent arg0) {
JButton jb = (JButton) arg0.getSource();
if (jb.getText().equals("Cancel")) {
System.exit(0);
} else {
directory.addRecord(nameField.getText(), new TelephoneRecords(nameField.getText(), numberField.getText()));
System.out.println("Added record for " + nameField.getText() + ": number is " + numberField.getText() + ".");
}
}
}
TELEPHONEDIRECTORY
public class TelephoneDirectory implements Iterable<TelephoneRecords> {
private HashMap records;
public TelephoneDirectory() {
records = new HashMap<String, TelephoneRecords>();
}
public void addRecord(String name, TelephoneRecords newRecord) {
records.put(name, newRecord);
}
public TelephoneRecords getRecord(String name) {
return (TelephoneRecords) records.get(name);
}
public void getDirectory() {
System.out.println("Telephone Directory:");
records.values().iterator();
}
#Override
public Iterator<TelephoneRecords> iterator() {
return records.values().iterator();
}
}
TELEPHONERECORDS
public class TelephoneRecords {
private String name;
private String number;
public TelephoneRecords(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
#Override
public String toString() {
return "The phone number of " + name + " is " + number + ".";
}
}
You may be trying to do too much with inheritance. Rather than using an AbstractListModel in place of your HashMap, consider creating a class that extends AbstractListModel and that holds the TelephoneDirectory class with its HashMap as the nucleus of the AbstractListModel's data. This is called extending a class by composition rather than by inheritance.
Edit: Also consider using a TreeMap rather than a HashMap so as to be able to retrieve your names and telephone records in name order. You'll also need to give your TelephoneDirectory class a getElementAt(int index) and a getSize() method to allow it to be used within the AbstractListModel class.