adding item to store in swing java using submit button - java

I created a store that saves records of person instances.
when adding the employees from CLI it works and the store increments, when using swing and CLI for debug i can see the new record but the increment is not done !
submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Store recordStore;
recordStore = new Store(1);
// here add the submitting text
Employee em = new Employee("mn",'M', new Date(18,12,1991), "025", new Date(2,5,2009));
if (!Store.isFull())
{
recordStore.add(em);
recordStore.displayAll();
System.out.println("Current size of store is " + Store.getCount());
}
else
{ JOptionPane.showMessageDialog(null, "The store seems to be full, please save it, and create a new one!"); }
The store add function
public void add(Person p)
{
// person p is added to array
list[count++] = p;
}

I suspect that your problem is that you're creating a new Store instance each time the ActionListener code is run. Perhaps you want to create a Store instance once in the class and add to it in the ActionListener.

public void add(Person p)
{
// person p is added to array
list[count++] = p;
}
If above function is defined in the Store class then you are initializing a new instance
Store recordStore;
recordStore = new Store(1);
every time. So your list count will always be 1. So as Hovercraft Full Of Eels has suggested
move that outside the ActionListener class and change code accordingly.
Or else use a static count that stores the count of records of person instances that you have added.

Related

Finding duplicates in an ArrayList(JFrame)

I'm trying to do a swing application which adds names to an ArrayList and then displays it in Jcombobox.I already did the window and everything but I can't seem to get the hang off detecting duplicate names.
I tried
btnnext.addActionListener(new ActionListener() {
Override
public void actionPerformed(ActionEvent e) {
if(checkDuplicate(names)==true)
{
names.add(txtname.getText());
txtname.setText("");
}
else {
JOptionPane.showMessageDialog(null,"DUPLICATE! do not add");
}
}
});
public static boolean checkDuplicate(ArrayList<String> list) {
HashSet set = new HashSet();
for (int i = 0; i < list.size(); i++) {
boolean val = set.add(list.get(i));
if (val == false) {
return val;
}
}
return true;
}
It only says that I have duplicate when I already add it to the ArrayList and when I get the message I can't add anything else.
input example:
test
test
and then it stops accepting new Strings and only displays the message DUPLICATE! do not add
As I said in my comment:
This happens because you are basically creating a Set view of your ArrayList every time you call checkDuplicate rather than comparing the item you're trying to add with the existing list. In other words your checkDuplicate is written such that it only returns true when a duplicate already exists within the list. You need to compare the new item with the list instead. Step through your logic carefully either with a debugger or by manually writing down the values of your variables and you will see the problem.
You could simply change this line:
if(checkDuplicate(names)==true)
to this:
if(!names.contains(txtname.getText()))
You don't really need checkDuplicate since it's "reinventing the wheel" so to speak. ArrayList already provides a contains method that you can use to your advantage.

Updating Arraylist by reading from dat file

so part of my program does is to create a card with a name. ill then check if the name exists in my dat file.
first, what i do is i read in my dat file and stores into an arraylist. then i implement a method to check if name exists. if not, then go ahead with creation.
but the thing is, after creation, i need to update my existing arraylist as my dat file has been updated with the newly added name.
what im thinking now is to clear my existing arraylist and then reading+store it again.
but i keep running into exceptions when i introduce the clear method. Here are my tested codes:
private ArrayList<Cards> cardList;
public void readGameCards()
{
cardList = new ArrayList<Cards>();
//clearCards(this.cardList); -> not sure where to add this
try // get data from dat file and store it into arraylist
{
Scanner myScanner = new Scanner(new File("GameCards.dat"));
while (myScanner.hasNextLine())
{
//converting codes
Cards c = new Cards(//para);
cardList.add(c);
}
myScanner.close();
}
catch (FileNotFoundException fe)
{
System.out.println("...");
}
}
public void clearCards(ArrayList<Cards> cardList)
{
if (!cardList.isEmpty())
{
cardList.clear();
//cardList = new ArrayList<Cards>();
}
}
it works fine for the first run, but on second run, the newly added name is not reflected in the arraylist.

Loading information from file in different ways

My program currently has this working:
Bank bank = new Bank();
bank.openAccount(new CheckingAccount(10100, new Customer("First", "Last"),500.00,false));
bank.openAccount(new CheckingAccount(10101, new Customer("First", "Last"),2000.00,true));
bank.openAccount(new SavingsAccount(2010, new Customer("First", "Last"),5000.00,0.02));
Now I am trying to load this information from a file instead, but I ran into a bit of a wall. I want the new Customer information to include both the first and last name which are stored in separate index positions as separate variables, but while this will work:
new Customer[FIRST_INDEX],
I can't seem to get it to accept two index positions without creating a new Customer again. This is turn is causing issue with the method in Accounts where I'd like to keep the same format. How can I go about doing this?
public CheckingAccount(int accountNumber, Customer owner, double currentBalance, boolean freeChecks)
{
super(accountNumber, owner, currentBalance);
this.freeChecks = freeChecks;
}
Another problem I am running into is that the last index position can be one of two variables depending on if I am dealing with a checking account or a savings account:
private final static int FREE_CHECKS_INDEX = 4; // This loads a boolean
private final static int INTEREST_INDEX = 4; // This loads a double
Given this, I'm not entirely sure if my above approach would even work at all. The program is supposed to load either a Checking Account or Savings Account object, but since both types of accounts are stored in the same file I am wondering if I could read the last index position of each line of the text file before creating the object, but I'm not really sure how to go about doing that.
To be clear, I have this problem working perfectly without loading the data from the file, I am just unsure about the best approach for adapting it without having to rewrite all my other classes. Here's the new thing I am trying to do which I know isn't right:
protected static void loadAccountInformationFromFile() throws Exception
{
try ( Scanner fin = new Scanner(new File(INPUT_CUSTOMER_FILE)) )
{
String record;
String[] fields;
while ( fin.hasNext() )
{
record = fin.nextLine();
fields = record.split(",");
Bank bank = new Bank();
bank.openAccount
(
new CheckingAccount(Integer.parseInt(accountNumber[ACCOUNT_NUMBER_INDEX]),
new Customer[FIRST_INDEX, LAST_INDEX],
currentBalance[BALANCE_INDEX],
freeChecks[FREE_CHECKS_INDEX]
)
);
}
} catch (Exception e)
{
throw e;
} // end try
}

retrieve instantiated objects from hashmap

I really didn't want to resort to asking, however I'm at a dead end. I'm trying to build an array of objects stored within a hashmap into a single array. I'm building a minecraft plugin, and I need to be able to do this in order to reset all players to their natural state. However, for whatever reason, I can't seem to actually parse the Spectator[] array into individual pieces.
The goal is simply to allow more than 1 person to spectate. Here's my code:
public class EagleEye extends JavaPlugin implements Listener{
public HashMap<Spectatee, Spectator[]> spec = new HashMap(Spectatee, Spectator[]);
public HashMap<Spectatee, Spectator[]> orinven = new HashMap<Spectatee, Spectator[]>;
public HashMap<Spectatee, Spectator[]> eeinven = new HashMap<Spectatee, Spectator[]>;
#Override
public void onEnable()
{
//TODO:Who knows.
}
#Override
public void onDisable()
{
//TODO:Spec off any players being spectated and spectating.
Spectator[] frickinhell = spec.get(key));
//Creates a master list of all spectators by uuid
for(Spectator spec : spec.get(Spectator.class))
{
master.add(spec);
}
for(Object spec : master.toArray())
{
//Verify the player is online
if(Bukkit.getPlayer(master)
{
//Verify the player is still spectating
if(tators.get(uuid) == true)
{
//Stop spectating
tators.put(uuid, false);
}
}
}
}
I understand that much of this code is broken. However, my main concern is taking Spectator[] stored within all instances of Spectators[] stored within the hashmap and resetting their values to their defaults. Once I can access each individual instance of each object itself, I can reset their respective values using setters.
Cheers.
In spec.get(Spectator.class), Spectator.class doesn't match the type of your key, which is Spectatee. Therefore, it returns null.
You should pass an instance of Spectatee to spec.get() if you want to have a chance of getting a non-null value.
If you want to collect all the Spectators regardless of their key, you can iterate over the values of the Map :
for (Spectator[] value : spec.values())
for(Spectator spec : value)
{
master.add(spec);
}

Java - Updating JList after changing an object

I have a JList which uses a DefaultListModel.
I then add values to the model which then appear in the JList. I have created a MouseListener which (when double clicked) allows the user to edit the current user number of that person they have selected.
I have checked that the actual object of that record is being changed, and it is. The only issue I'm having is getting the actual Jlist to update to show the new values of that object.
Snippets of the current code I have are:
Creating the JList and DefaultTableModel:
m = new DefaultListModel();
m.addListDataListener(this);
jl = new JList(m);
jl.addMouseListener(this);
Updating the object:
String sEditedNumber = JOptionPane.showInputDialog(this, "Edit number for " + name, number);
if (sEditedNumber != null) {
directory.update (name, sEditedNumber);
}
And (when jl is the JList and m is the DefaultTableModel):
public void contentsChanged(ListDataEvent arg0) {
jl.setModel(m);
}
Instead of setModel(), update your existing model using one of the DefaultListModel methods such as setElementAt(), which will fireContentsChanged() for you.
You need to call fireContentsChanged() on the ListModel.
You need to call DefaultListModel.fireContentsChanged(). But since this method is protected (I really wonder why), you can't do that directly. Instead, make a small subclass:
class MinoListModel<T> extends DefaultListModel<T>
{
public void update(int index)
{
fireContentsChanged(this, index, index);
}
}
Use it as your list model:
m = new MinoListModel<>();
jl = new JList(m);
After updating a user number, update the corresponding entry: m.update(theIndex);
Alternatively, if you don't want a subclass, you can just replace the JList element after the user number changed: m.setElementAt(theSameElement, theIndex);. Though this is somewhat cumbersome and having a subclass seems the cleaner approach.

Categories

Resources