Simple employee records java program GUI remove button - java

I have a program GUI that the user enters ID#, First Name, Last Name, Salary, Start Date. After the user enters this information into a text area for each information need, the users clicks the add button which stores the information into an arrayList. After clicking add, the user presses a "list" button to output all the information entered into a Panel.
Array list to store users data:
public class EmploymentRecords extends javax.swing.JFrame {
ArrayList <Data> Output = new ArrayList <Data>();
Remove Button code:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
boolean idCheck = Output.contains(id);
if (idCheck = true){
index = Output.indexOf(id);
Output.remove(index);
lblError.setText("Employee found and has been removed.");
}
else {
lblError.setText("Employee not found. Please try again.");
}
class Data:
class Data {
String id, firstName, lastName, salary, startDate;
Data (String _id, String _firstName, String _lastName, String _salary, String _startDate) {
id = _id;
firstName = _firstName;
lastName = _lastName;
salary = _salary;
startDate = _startDate;
Heres my problem: I want the user to be able to enter an id in the text area of the GUI where the program checks if that ID is entered before and totally removes all the data from the output screen and arraylist using just the ID. The code I entered above is not working for me and when I press the remove button nothing happens.
Please help as i would appreciate this... Thanks!

You are missing some code to share. But lets suppose your "add" functionality is working.
Lets also suppose that "String id = txtID.getText();" will be able to get the id for you as a string.
An obvious mistake is "if (idCheck = true)", as in java you compare with "=="
So maybe you can try to fix it that way and report the answer.

What you have done works alright for single entity objects within an ArrayList (like ArrayList<String> or ArrayList<Integer> for example) but not so good for multi-entity objects like what you have in your Data class. In other words, each element within your ArrayList is holding an instance of a class and all members related to it, not just a simple String or an Integer.
You will need to go a wee bit deeper in order to actually acquire the ID of any particular Data object instance for comparison to what someone has supplied within a GUI, for example:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
String id = txtID.getText();
boolean found = false;
for (Data data : Output) {
if (data.id.equals(id) {
found = true;
Output.remove(data);
clearFieldsInForm();
break;
}
}
if (found) {
lblError.setText("Employee was successfully removed.");
}
else {
lblError.setText("Invalid ID! Employee not found! Please try again.");
}
}
You will notice the clearFieldsInForm(); method use in the above code. This method would just set all pertinent form fields to Null String ("") which is essentially nothing:
private void clearFieldsInForm() {
txtID.setText("");
txtFirstName.setText("");
txtLastName.setText("");
txtsalary.setText("");
txtStartDate.setText("");
}

Related

Java/Android studio : For loop - Same data shows multiple times

So I am trying to create this page that compares a user's interest with other users and shows the list of all those users.. Now, with the for loop i created, one particular user's name repeats until the end of the loop. I only one one name per username to appear on the textfield.. However, I don't know how to do that.. Here's my code for showing users with common interests:
Realm realm= Realm.getDefaultInstance();
RealmResults<interests> result=realm.where(interests.class).findAll();
RealmResults<Users> user=realm.where(Users.class).findAll();
for(int i=0;i<result.size();i++)
{
for(int j=0;j<result.size();j++)
{
if(result.get(i).getId().equals(userid))
{
if(result.get(i).getInterest().equals(result.get(j).getInterest()))
{
if(!result.get(j).getId().equals(userid)) {
users = result.get(j).getId();
interestss.append("Interests :" + result.get(i).getInterest());
}
}
id.append("\n"+users);
}
}
}
for(int i=0;i<result.size();i++)
{
for(int j=0;j<result.size();j++)
{
if(result.get(i).getId().equals(userid))
{
if(result.get(i).getInterest().equals(result.get(j).getInterest()))
I'm almost 98% sure that you shouldn't even need to write this kind of code if you use Realm's query system and a link query, instead of looping and comparing things manually.
RealmResults<Interests> interests = realm.where(Interests.class)
.equalTo("user.userId", userId)
.findAll();
Which should be possible if you have a backlink from Interests to Users.
// in Interests class
#LinkingObjects("interest")
private final RealmResults<User> user = null;

Iterator over TreeSet causes infinite loop

For this assignment, I'm required to save instances of a custom data class (called User) each containing 2 strings into a TreeSet. I must then search the TreeSet I created for a string taken from each line of another file. The first file is a .csv file in which each line contains an email address and a name, the .txt file contains only addresses. I have to search for every line in the .txt file, and I also have to repeat the entire operation 4000 times.
I can't use .contains to search the TreeSet because I can't search by User, since the .txt file only contains one of the two pieces of information that User does. According to information I've found in various places, I can take the iterator from my TreeSet and use that to retrieve each User in it, and then get the User's username and compare that directly to the string from the second file. I wrote my code exactly as every site I found suggested, but my program still gets stuck at an infinite loop. Here's the search code I have so far:
for (int i = 0; i < 4000; i++)//repeats search operation 4000 times
{
try
{
BufferedReader fromPasswords = new BufferedReader(new FileReader("passwordInput.txt"));
while ((line = fromPasswords.readLine()) != null)
{
Iterator it = a.iterator();
while (it.hasNext())
{
//the infinite loop happens about here, if I put a println statement here it prints over and over
if(it.next().userName.compareTo(line) == 0)
matches++; //this is an int that is supposed to go up by 1 every time a match is found
}
}
}
catch (Exception e)
{
System.out.println("Error while searching TreeSet: " + e);
System.exit(0);
}
}
For some additional info, here's my User class.
class User implements Comparable<User>
{
String userName;
String password;
public User() { userName = "none"; password = "none"; }
public User(String un, String ps) { userName = un; password = ps; }
public int compareTo(User u)
{
return userName.compareToIgnoreCase(u.userName);
}
} //User
I've done everything seemingly correctly but it looks to me like iterator doesn't move its pointer even when I call next(). Does anyone see something I'm missing?
Edit: Thanks to KevinO for pointing this out- a is the name of the TreeSet.
Edit: Here's the declaration of TreeSet.
TreeSet<User> a = new TreeSet<User>();
Are you certain there's an infinite loop? You're opening a file 4000 times and iterating through a collection for every line in the file. Depending on size of the file and the collection this could take a very long time.
Some other things to be aware of:
Later versions of Java have a more succinct way of opening a file and iterating through all the lines: Files.lines
You don't need an Iterator to iterate through a collection. A normal for-each loop will do or convert it to a stream
If all you want to do is count the matches then a stream is just as good
Putting all that together:
Path path = Paths.get("passwordInput.txt");
Set<User> users = new TreeSet<>();
long matches = Paths.lines(path)
.mapToLong(l -> users.stream()
.map(User::getName).filter(l::equals).count())
.sum();

Adding objects to array list [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Hello i am trying to add my Class's objects into an ArrayList with the objects attributes but i keep getting null pointers
I am reading values from a txt file assigning them to the attributes and then put the object into the array list
here is my code
public class Users {
Scanner scan;
BufferedReader reader;
MainGui gui;
Login login;
String name;
String surname;
String dob;
String address;
String town;
String number;
String position;
ArrayList<Users> allUsers = new ArrayList<Users>();
public Users(Login login){
this.login = login;
open();
}
public void open(){
try {
URL path = Users.class.getResource("records.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
scan = new Scanner(reader);
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
public void readRecords(){
open();
while(scan.hasNext()){
Users user = new Users(login);
user.name = scan.next();
user.surname = scan.next();
user.dob = scan.next();
user.address = scan.next();
user.address = addSpace(user.address);
user.town = scan.next();
user.number = scan.next();
user.position = scan.next();
allUsers.add(user);
}
scan.close();
}
public void printUsers(){
readRecords();
for(Users user : allUsers){
System.out.println("" + user );
}
}
}
I have included all the methods playing part in this in order for you to help me better.
Change this part of code, you need to set the values in the user object you are creating.
Users user = new Users(login);
user.name = scan.next();
..
allUsers.add(user);
And it is better to create getter and setters for attributes.
And you don't need to set the values to null in constructor, java does that for you.
You're setting attributes in the instance that's executing the method, but you're adding the new (empty) object to your array list. Thus the list is full of empty Users instances.
This code is a bit of a mess - it's doing too much stuff in one class. You have a class called Users, which has a list of Users and the attributes of a user. Each of the users inside the list will also have a list of users.
It seems like you should have two classes, one called Users, and one called User (or similarly named classes)
The Users class has the list of s and is responsible for populating that list (by reading in the file). Then the User class just holds onto information for a particular user, and any operation pertaining to a single user.
Then, when you read in the records, you can get the scanner (as you currently are doing), pass it to the User, then that particular user object will populate it's own fields (similar to what awesome said)
First I suggest you to put "System.out.print" statements while creating the USERS instance in read function to check if you are reading those values properly from the file. Second, Override toString() in Users class to display the values i.e.
public String toString() {
System.out.println("Name: "+name+", surname: "+surname+", DOB: "+dob+", Address: "+address+", Town: "+town+", Number: "+number+", and Position: "+position);
}
Now your System.out.println("" + user );
should display values read from the file.

javafx choice box is empty on setValue()

In my project I have a table. When the user double clicks on the row, an editing dialog opens. On the opening this dialog I set values to fields, few of which are ChoiceBoxes. The type of ChoiceBox's field is a custom object, not a string.
The code that creates the ChoiceBox follows:
trade_point.setConverter(new TradePointConverter());
trade_point.setItems(FXCollections.observableArrayList(tradePointsService.getTradePoints()));
TradePoint currentTradePoint = tradePointsService.getTradePoint(typeOfPriceByTradePoint.getTradePoint());
trade_point.setValue(currentTradePoint);
Where trade_point is a choice box of TradePoint type. currentTradePoint is not null, when I look at trade_point's value equals currentTradePoint's value but in the dialog I see no value. Items are set correctly. in other case with same choice box filling everything is correct and here is not.
UPD: TradePointConverter class:
class TradePointConverter extends StringConverter<TradePoint>{
public TradePoint fromString(String name){
try {
List<TradePoint> tradePoints = tradePointsService.getTradePoints();
for (TradePoint tradePoint1: tradePoints){
if (tradePoint1.getName().equals(name)){
return tradePoint1;
}
}
}catch (SQLException e){
}
return null;
}
public String toString(TradePoint tradePoint1){
return tradePoint1.getName();
}
}
I am not sure if this converter is correct as far as converting from string by name is totally incorrect. I do not understand how to make it correctly visible to the user (to see the name of an object) and how to store its id to get the definite object at the same time. I can convert to string by getting an id but in this case user won't understand which object to choose.
trade_point is a ChoiceBox:
private ChoiceBox<TradePoint> trade_point = new ChoiceBox<TradePoint>();

Keep a reference of JOptionPane returning an specific class

I want to implement a Swing Input Dialog with different options shown in a combo box. My specific case is for Contact creation, the end user can choose between existing Contacts or create a new one himself.
So I've got this static method which basically returns a new instance of a JOptionPane, which has the available selection objects out of the box. Note this code creates, let's say the parent dialog, which offers selecting an existing contact or clicking on the button to create a new one:
/**
*
* #param message
* Here I've got a JPanel which allows the end user to show-hide
* the Contact creation dialog
* #param contacts
* Contact possibilities
* #return reference to the created JOptionPane
*/
public static JOptionPane newContactOptionPane(Object message,
Set<XmlContact> contacts) {
Object[] contactPossibilities = new Object[contacts.size()];
int index = 0;
for (XmlContact contct : contacts) {
contactPossibilities[index] = String.format("%s %s, %s",
contct.get_Surname1(), contct.get_Surname2(),
contct.get_Name());
index++;
}
JOptionPane optPane = new JOptionPane();
JOptionPane.showInputDialog(optPane, message, "Seleccionar Contacto",
JOptionPane.QUESTION_MESSAGE, null, contactPossibilities,
contactPossibilities[0]);
return optPane;
}
The invoker code would be something like:
JOptionPane contactSelectionPane =
ViewUtils.newContactOptionPane(createContactPanel, xmlContacts);
XmlContact selectedContact =
(XmlContact) contactSelectionPane.getValue();
Later on, I would like to recover the selected value using JOptionPane#getValue() method.
The desired behaviour is to show the form for Contact creation when clicking Crear nuevo contacto, so the previous JDialog will be hidden:
I've got two reasons for keeping the reference at the invoker code, the first one is because I would like to wrap the option pane to make it return an XmlContact object instead of an String and having to search it again the possible options once and again in my invoker code. The other one is because I want to keep a reference of contactSelectionPane for enabling a button into createContactPanel to show/hide it.
Now the contactSelectionPane.getValue() is obviously returning an String, which forces me to check the options again. How can I implement that?
Why don't you do something like this:
public class Option<X> {
private final X value;
private final String name;
public String toString() {
return name;
}
public X getValue() {
return value;
}
public Option(X value, String name) {
this.value=value;
this.name=name;
}
}
public static JOptionPane newContactOptionPane(Object message,
Set<XmlContact> contacts) {
Object[] contactPossibilities = new Object[contacts.size()];
int index = 0;
for (XmlContact contct : contacts) {
contactPossibilities[index] = new Option<XmlContact>(contct, String.format("%s %s, %s",
contct.get_Surname1(), contct.get_Surname2(),
contct.get_Name()));
index++;
}
JOptionPane optPane = new JOptionPane();
JOptionPane.showInputDialog(optPane, message, "Seleccionar Contacto",
JOptionPane.QUESTION_MESSAGE, null, contactPossibilities,
contactPossibilities[0]);
return optPane;
}
And later you do:
JOptionPane contactSelectionPane =
ViewUtils.newContactOptionPane(createContactPanel, xmlContacts);
XmlContact selectedContact =
((Option<XmlContact>) contactSelectionPane.getValue()).getValue();
Hope that helps.
EDIT:
as for creating a new XmlContact I'd simply add an additional Option to the list of available options similar to new Option<XmlContact>(new XmlContact(...), "Create new contact...");.
I would use a SelectionChangedListener in order to get the actual selected item from the JComboBox.
In order to get the new XmlContact if created I would use some kind of variable to remember the created XmlContact.
At last I would derive a new Class from JOptionPane in which I override the getValue method where I either get the new XmlContact or the selected one from the JComboBox. You then use this class rather than the pure JOptionPane.

Categories

Resources