Show an item in a JScrollPane - java

I store in an arraylist an object (contact) which has name,number,email.
Then i want to display lets say the name in ScrollPane but i get an error on retrieving it (from my other class).
What im doing wrong?
Heres this part of the code(i get the error in the last line using the ):
class GetUserInput implements ActionListener {
//It's the reactions to the buttons that are pressed
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Add Contact")) {
Agenda a = new Agenda();
System.out.println(event);
String inp = JOptionPane.showInputDialog("Enter your contact name");
a.setName(inp);
String inp1 = JOptionPane.showInputDialog("Enter your contact number");
a.setPhoneNumber(inp1);
String inp2 = JOptionPane.showInputDialog("Enter your contact email");
a.setEmail(inp2);
contacts.add(a);
} else if (event.getActionCommand().equals("Edit Contact")) {
String inp = JOptionPane.showInputDialog("Enter the name of the contact you wish to edit ");
} else if (event.getActionCommand().equals("Show All Contacts")) {
System.out.println(a.getName());

You can't run it, because a is created in another block. You can't access it in the last else if-block before creating and assigning a new Variable a.

Related

How to write a login for java GUI

so I know that there are many similar questions to mine but i do not really understand what they mean as i am not that great when it comes to coding.
my login screen in the GUI is this:
public void createLoginPanel()
{
loginPanel.setLayout(null);
loginLbl.setLocation(425,50);
loginLbl.setSize(500,50);
loginLbl.setText("Login");
loginPanel.add(loginLbl);
usernameLbl.setLocation(250,300);
usernameLbl.setSize(250,50);
usernameLbl.setText("Username: ");
loginPanel.add(usernameLbl);
usernameTxt.setLocation(350,300);
usernameTxt.setSize(250,50);
usernameTxt.setText("");
usernameTxt.setColumns(10);
loginPanel.add(usernameTxt);
passwordLbl.setLocation(250,400);
passwordLbl.setSize(250,50);
passwordLbl.setText("Password: ");
loginPanel.add(passwordLbl);
passwordTxt.setLocation(350,400);
passwordTxt.setSize(250,50);
passwordTxt.setText("");
passwordTxt.setColumns(10);
loginPanel.add(passwordTxt);
loginBtn.setLocation(675,400);
loginBtn.setSize(100,50);
loginBtn.addActionListener(this);
loginBtn.setText("Login");
loginPanel.add(loginBtn);
gotoWelcomeScreenBtn2.setLocation(100,600);
gotoWelcomeScreenBtn2.setSize(150,50);
gotoWelcomeScreenBtn2.addActionListener(this);
gotoWelcomeScreenBtn2.setText("Home");
loginPanel.add(gotoWelcomeScreenBtn2);
}
the login i currently have is this:
if(e.getSource() == loginBtn)
{
String pass;
String user;
user = usernameTxt.getText();
pass = passwordTxt.getText();
if(user.equals("username") && pass.equals("pass") )
{
JOptionPane.showMessageDialog(null,"Login successful");
allTheGUITabs.setSelectedIndex(7);
}
else
{
JOptionPane.showMessageDialog(null,"Please try again.");
}
System.out.println("Login Button pressed");
}
i want to login using existing info that i have stored in a text file called "employeelist.txt" and i am not sure how to do this.
edit: i have changed the login to user.equals and pass.equals but i am still unsure on how to login with anything other than what i've declared.
edit:
this is the contents of my text file. the second is the username and the third is the password. how will i scan this text file to ensure that the username and password match?
1,MSmith01,Pass123,Mark Smith,12 Yellow Lane,L34GF4,07837463
2,JSmith02,Pass456,Joan Smith,8 Green Road,L394RQ,08765456765
3,PSmith03,Pass678,Paul Smith,9 Orange Street,L435RE,07485747362
4,WSmith04,Pass910,Walter Smith,8 Green Road,L394RQ,08765456765
5,CSmith05,Pass149,Callum Smith,12 Yellow Lane,L34GF4,07485848373
6,MSmith06,Pass213,Mark Smith,32 Red Road,L384GT,07874636472
7,TMath07,Pass141,Terry Matthews,4 Peach Street,L219RB,07564737283
Let’s say you have next strings in your txt file
admin
qwerty12345
Use scanner and pass values for your variables reading them from txt
File employeelist;
Scanner scanner;
String login;
String password;
try
{
employeelist = new File("employeelist.txt"); // changed code
scanner = new Scanner(employeelist); //changed code
while(scanner.hasNextLine())
{
login = scanner.nextLine();
password = scanner.nextLine();
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
}
Then use it in your if statement.
if(user.equals(login) && pass.equals(password)
{
// your code here
}

Code after for loop does not execute (Java) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a small snippet of code that is supposed to check the inputted codename and password against what is stored in a text file. If there is a match, it will start the game and everything is fine. But if there is no match, a dialog is supposed to pop up asking the user if they want to try logging in again.
int input=0; //yes
do {
codename=JOptionPane.showInputDialog(null,"Enter Codename: ");
String password=JOptionPane.showInputDialog(null, "Enter Password: ");
for(int i=0;i<users.length;i++){
if((codename.equals(users[i].getCodeName())) && (password.equals(users[i].getPassword()))){
System.out.println("\n\nCorrect");
new Game();
} else {
System.out.println("\n\nIncorrect");
}
}
input = JOptionPane.showConfirmDialog(null, "Incorrect User name/Password\nWould you like to try again?");
} while(input==0); //run while input is yes
The problem: the code after the for loop does not execute. If I check the variables against users[i] the code after the for loop does not run, but if I check against users[2] for example, then it works fine.
Not sure if this matters but I always get this error:
Exception in thread "main" java.lang.NullPointerException
at com.ramtin.Game.logOn(Game.java:505)
at com.ramtin.Game.main(Game.java:397)
I get it even when the password and codename match and the program runs perfectly.
FULL CODE for the above code:
public static void logOn(){
//ASK FOR CODENAME & PASSWORD FROM TEXTFILE BEFORE GAME BEGINS
//read from text file
UserData[]users=new UserData[20];
int countU=0;
try{
BufferedReader readU = new BufferedReader(new FileReader("userdata.txt"));
String line;
while((line=readU.readLine())!=null){
String []parts=line.split("#");
String codeName = parts[0];
String password=parts[1];
// System.out.println(parts[0]);
// System.out.println(parts[1]);
users[countU]=new UserData(codeName, password);
countU++;
}
readU.close();
}
catch(FileNotFoundException e){
}
catch(IOException e){
}
//PASSWORD & CODENAME
int input=0; //yes
do{
codename=JOptionPane.showInputDialog(null,"Enter Codename: ");
String password=JOptionPane.showInputDialog(null, "Enter Password: ");
for(int i=0;i<users.length;i++){
if((codename.equals(users[i].getCodeName()))&&(password.equals(users[i].getPassword()))){
System.out.println("\n\nCorrect");
new Game();
}
else{
System.out.println("\n\nIncorrect");
}
}
input = JOptionPane.showConfirmDialog(null, "Incorrect Username/Password\nWould you like to try again?");
}
while(input==0); //run while input is yes
}
}
FULL CODE for UserData:
public class UserData {
private String codename;
private String password;
UserData (String codeName, String password)
{
this.codename = codeName;
this.password= password;
}
String getCodeName()
{
return codename;
}
String getPassword()
{
return password;
}
public String toString ()
{
String temp = "\nCode name: "+codename+"\nPassword: " + password;
return temp;
}
}
Don't do for(int i=0;i<users.length;i++){
Do do for(int i=0;i<countU;i++){
Every array element after countU will cause NPE when you call a method on a null element like users[i].getCodeName()
Instead of using an array with the length 20, you can use an ArrayList as it will expand dynamically:
List<UserData> users = new ArrayList<>();
Then add each userdata to the list
users.add(new UserData(codeName, password));
and iterate with
for(int i=0 ;i<users.size(); i++) {
This will prevent the NullPointer as you only have as many entries as you have users (and will also dynamically grow/shrink with the number of users you have).

Reading a special txt file in java

What I want to do is read a text file that has humans and animals. It will compile but has an error when I try to run it. I think I need a for loop to read the stringtokenizer to decipher between the human and animal in the txt file so far this is my driver class.
txt file:
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
Bubba,Bulldog,58,4-15-2010,6-14-2011
Lucy,Bulldog,49,4-15-2010,6-14-2011
Wilder,John,457 Somewhere Road,78214,3,124.53,1
Ralph,Cat,12,01-16-2011,04-21-2012
Miller,John,639 Green Glenn Drive,96258,5,0.00,3
Major,Lab,105,07-10-2012,06-13-2013
King,Collie,58,06-14-2012,10-05-2012
Pippy,cat,10,04-25-2015,04-25-2015
Jones,Sam,34 Franklin Apt B,47196,1,32.09,1
Gunther,Swiss Mountain Dog,125,10-10-2013,10-10-2013
Smith,Jack,935 Garrison Blvd,67125,4,364.00,4
Perry,Parrot,5,NA,3-13-2014
Jake,German Shepherd,86,11-14-2013,11-14-2013
Sweetie,tabby cat,15,12-15-2013,2-15-2015
Pete,boa,8,NA,3-15-2015
Source:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
import java.io.IOException;
/**
* This is my driver class that reads from a txt file to put into an array and uses the class refrences so it can use the menu and spit out
*
* #author ******
* #version 11/25/2015
*/
public class Driver
{
/**
* Constructor for objects of class Driver, what it does is read in the txt file gets the two class refrences and loops through to read through the whole file looking for string tokens to go to the next line
* and closes the file at the end also uses for loop to count number of string tokens to decipher between human and pets.
*/
public static void main(String[] args) throws IOException
{
Pet p;
Human h;
Scanner input;
char menu;
input = new Scanner(new File("clientdata.txt"));
int nBalance;
int id;
/**
* this while statement goes through each line looking for the string tokenizer ",". I want to count each "," to decipher between Human and Animal
*/
while(input.hasNext())
{
StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
h = new Human();
h.setLastName(st.nextToken());
h.setFirstName(st.nextToken());
h.setAddress(st.nextToken());
h.setCiD(Integer.parseInt(st.nextToken()));
h.setVisits(Integer.parseInt(st.nextToken()));
h.setBalance(Double.parseDouble(st.nextToken()));
p = new Pet(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(), st.nextToken());
}
/**
* this is my seond while statement that loops the case switch statements and asks the user for client ID
*/
menu = 'Y';
while(menu == 'y' || menu == 'Y') {
System.out.print("\nChose one:\n A- client names and outstanding balance \n B- client's pets, name, type and date of last visit\n C-change the client's outstanding balance: ");
menu = input.next().charAt(0);
System.out.print("Enter client ID: ");
id = input.nextInt();
h = new Human();
if(id == h.getCiD())//if the id entered up top is equal to one of the id's in the txt file then it continues to the menu
{
p = new Pet();
switch(menu)
{ case 'A':
System.out.println("client name: " + h.getFirstName() + "outstanding balance: " + h.getBalance());
break;
case 'B':
System.out.println("pet's name: " + p.getName() + "type of pet: " + p.getTanimal() + "date of last visit: " + p.getLastVisit());
break;
case 'C':
System.out.println("what do you want to change the clients balances to?");
input.close();
}
}
else// if not then it goes to this If statement saying that the Client does not exist
{
System.out.println("Client does not exist.");
}
}
}
}
You have a number of issues you need to overcome...
For each line, you need to determine the type of data the line represents
You need some way to keep track of the data you've loaded (of the clients and their pets)
You need some way to associate each pet with it's owner
The first could be done in a number of ways, assuming we can change the data. You could make the first token meaningful (human, pet); you could use JSON or XML instead. But lets assume for the moment, you can't change the format.
The key difference between the two types of data is the number of tokens they contain, 7 for people, 5 for pets.
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
// Parse owner
} else if (parts.length == 5) {
// Parse pet
} // else invalid data
For the second problem you could use arrays, but you would need to know in advance the number of elements you will need, the number of people and for each person, the number of pets
Oddly enough, I just noticed that the last element is an int and seems to represent the number of pets!!
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
------------^
But that doesn't help us for the owners.
For the owners, you could use a List of some kind and when ever you create a new Human, you would simply add them to the List, for example...
List<Human> humans = new ArrayList<>(25);
//...
if (parts.length == 7) {
// Parse the properties
human = new Human(...);
humans.add(human);
} else if (parts.length == 5) {
Thirdly, for the pets, each Pet should associated directly with the owner, for example:
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
//...
} else if (parts.length == 5) {
if (human != null) {
// Parse pet properties
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
Okay, so all this does, is each time we create a Human, we keep a reference to the "current" or "last" owner created. For each "pet" line we parse, we add it to the owner.
Now, the Human class could use either a array or List to manage the pets, either will work, as we know the expected number of pets. You would then provide getters in the Human class to get a reference to the pets.
Because out-of-context code can be hard to read, this is an example of what you might be able to do...
Scanner input = new Scanner(new File("data.txt"));
List<Human> humans = new ArrayList<>(25);
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
String firstName = parts[0];
String lastName = parts[1];
String address = parts[2];
int cid = Integer.parseInt(parts[3]);
int vists = Integer.parseInt(parts[4]);
double balance = Double.parseDouble(parts[5]);
int other = Integer.parseInt(parts[6]);
human = new Human(firstName, lastName, address, cid, vists, balance, other);
humans.add(human);
} else if (parts.length == 5) {
if (human != null) {
String name = parts[0];
String type = parts[1];
int age = Integer.parseInt(parts[2]);
String date1 = parts[3];
String date2 = parts[4];
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
}
What about using split() function instead of using StringTokenizer?
Say, You can change your first while loop like below:
while (input.hasNext()) {
// StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
String[] tokens = input.nextLine().split(",");
if (tokens.length == 7) {
h = new Human();
h.setLastName(tokens[0]);
h.setFirstName(tokens[1]);
h.setAddress(tokens[2]);
h.setCiD(Integer.parseInt(tokens[3]));
h.setVisits(Integer.parseInt(tokens[4]));
h.setBalance(Double.parseDouble(tokens[5]));
} else {
p = new Pet(tokens[0], tokens[1], Integer.parseInt(tokens[2]), tokens[3], tokens[4]);
}
}
And for keeping track of which pet belongs to which human, you can append an arrayList of type Pet in Human class like below:
ArrayList<Pet> pets = new ArrayList<>();
And say you have another ArrayList of type Human named humans in the main function. So, you could append in if block like:
humans.add(h);
and in the else section, you could append in else block:
humans.get(humans.size()-1).pets.add(p);
You can try something like this -
Populate a map and then using that you can assign values according to your requirement.
public void differentiate(){
try {
Scanner scan=new Scanner(new BufferedReader(new FileReader("//your filepath")));
Map<String,List<String>> map=new HashMap<String, List<String>>();
while(scan.hasNextLine()){
List<String> petList=new ArrayList<String>();
String s=scan.nextLine();
String str[]=s.split(",");
String name=str[1]+" "+str[0];
int petCount=Integer.parseInt(str[str.length-1]);
for(int i=1;i<=petCount;i++){
String petString=scan.nextLine();
petList.add(petString);
}
map.put(name, petList);
}
Set<String> set=map.keySet();
for(String str:set){
System.out.println(str+" has "+map.get(str)+" pets");
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}

How do I create a login form in Java using file stream?

Hello i am a new java student i have been working on a library system containing ( users - library workers and books ) so i am trying to create a log in form i already have an array list but i did a file stream ( to clarify i let the new user to register and his/her information will be saved to the file like this ID Name Password Age ) so i have tried to do something as this method in the library users class
private Scanner x;
private String user_name , password ;
public void openfile(){
try {x= new Scanner (new File ("E:\\javaapplication1
\\test\\professors.txt"));
}
catch(Exception e){
System.out.println("couldn't find file");
}
}
public void checklog ( String username , String password ){
String a , b ,c ,d ;
while(x.hasNext()){
a = x.next();
b = x.next();
c = x.next();
d = x.next();
if ( b == username ||c == password ){
System.out.println("Loggin successful ");
}
else
System.out.println("Loggin failed wrong id or password ");
break;
and then call it like this in the main with the full code
System.out.println ("Enter your name ");
check_name = reader.next();
System.out.println ("Enter your password ");
check_password =reader.next();
lib_us professor ;
professor = new lib_us();
professor.openfile();
professor.checklog(check_name, check_password);
i get all passwords wrong i save them like 4 id name password and age that's why i created a b c and d ...
i am still new in this kind of log in forms so please specify me a solution and if you need the whole code please ask for it :)
So in your checkLog() method you have the statement if(b == username || c == password) should be if(b.equals(username) && c.equals(password)) OR if(b.equalsIgnoreCase(username) && c.equalsIgnoreCase(password)) for case sensitive or not (use the equals() method for case sensitivity or the equalsIgnoreCase() method for non case sensitivity).
Understand why that is? Because in your original statement you are saying only one of them has to be true in order for it to be a successful login. With the revised one both of them must be true. Also you should not use the operator == to compare two strings to see if they are the same string. That will only compare their addresses.
EDIT:
If your file is kind of like what is shown below:
12 Name Pass 12
13 Namez Passz 13
14 Namezz Passzz 14
Try this code to read it in and compare:
private Scanner x;
private String user_name, password;
public void openFile()
{
try
{
x = new Scanner(new File("FILE PATH"));
}
catch(Exception e)
{System.out.println("Couldn't find file"); System.exit(0);}
}
public boolean checklog(String username, String password)
{
String temp;
String[] info;
while(x.hasNext())
{
temp = x.nextLine();
info = temp.split(" ");
//info[0] = id, info[1] = username, info[2] = password, info[3] = age;
//Right here that means the username and password is correct
if(info[1].equals(username) && info[2].equals(password))
{
System.out.println("Login Successful");
return true;
}
}
System.out.println("Login failed wrong id or password");
return false;
}

Is there way to keep queue data in memory in java GUI program

I'm writing a program to simulate a waiting queue for campus students this program users a linked list to do the queue and I used a button click event to execute the code.
It works only once every time add it only holds one student I think it because the list gets cleared after the button click event. I just want know is there a way to keep the list active till I terminate the main program.
My Code Below:
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
Queue stdQue = new LinkedList(); <-- Create the queue
String stName = addStdName.getText();
int sId;
int stdQuality;
if(!stName.isEmpty()){
// Generate a random number as Id
RanNum tempId = new RanNum();
sId = tempId.genNum();
// Generate a random number as a quality number to be matched later with the apartment
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
Object atTop = stdQue.element().toString();
if (!stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
if(!stdQue.isEmpty()){
for(Object name : stdQue){
lstQue.setText(name.toString());
}
}
}
The above code functions with out error I just want to find out to keep the queue live until the user terminate the main program.
I think this can be archived in a CLI program using a while loop but this is a GUI program I don;t know how to do that in a this format.
UPDATE
I made changes according to #learninloop when I do that I get an error "Cannot Find Symbol:method addStd1ActionPerformed(evt)". Also like to inform you that I'm using NetBeans 8.0.2 as my java IDE.
addStd1.setText("Add Student");
addStd1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {addStd1ActionPerformed(evt);}
And the changed main code is below:
class stdQueCls{
Queue stdQue;
public stdQueCls(){
stdQue = new LinkedList();
}
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
int sId;
int stdQuality;
RanNum tempId = new RanNum();
sId = tempId.genNum();
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
Object atTop = stdQue.element().toString();
if (!stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
if(!stdQue.isEmpty()){
for(Object name : stdQue){
lstQue.setText(name.toString());
}
}
}
}
UPDATE
I changed the code and put my linked list in to a class and moved it totally out of the button click event. So the new code as follows,
class stdQueCls{
Queue stdQue;
public stdQueCls(){
stdQue = new LinkedList();
if (!stdQue.isEmpty()){
for(Object all : stdQue){
lstQue.setText(all.toString());
}
}
}
}
public void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQueCls stdQue1 = new stdQueCls();
int sId;
int stdQuality;
RanNum tempId = new RanNum();
sId = tempId.genNum();
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
stdQue1.stdQue.add(sId);
stdQue1.stdQue.add(stdQuality);
stdQue1.stdQue.add(stName);
Object atTop = stdQue1.stdQue.element().toString();
if (!stdQue1.stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
}
Now as you see in my class I want to display what ever in the queue in a text area named queLst as you can see I have used a for loop to do it but my issue is it's not displaying the list in the text area and the other thing when it's placed inside the button click event it works but adds what ever I enter at that point can some show me a way or give an idea to how to archive this.
UPDATE
I did some changes to the above code now it working but I don't if I'm doing this wrong one things is when I retrieve the inserted data from the queue it not what I expect to see and I think still my queue linked list is not getting populated.
Can some one please have a look at my code and tell me what I'm doing is write or wrong.
class stdQueCls{
Queue<stdDetailGroup> stdQue;
public stdQueCls(){
stdQue = new LinkedList<stdDetailGroup>();
//lstQue.setText(stdQue.toString());
}
}
class stdDetailGroup{
String stdId;
String stQuality;
String stdName;
public stdDetailGroup(String a, String b, String c){
stdId = a;
stQuality = b;
stdName = c;
}
}
public void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQueCls stdQue1 = new stdQueCls();
int stdQualityInt;
int sIdInt;
String sId;
String stdQuality;
RanNum tempId = new RanNum();
sIdInt = tempId.genNum();
sId = Integer.toString(sIdInt);
RanNum tempQuality = new RanNum();
stdQualityInt = tempQuality.genNum();
stdQuality = Integer.toString(stdQualityInt);
stdDetailGroup stdDetailsAdd = new stdDetailGroup(sId, stdQuality, stName);
stdQue1.stdQue.add(stdDetailsAdd);
Object atTop = stdQue1.stdQue.toString();
if (!stdQue1.stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
}
private void shwQue1ActionPerformed(java.awt.event.ActionEvent evt) {
stdQueCls stdQue2 = new stdQueCls();
lstQue.setText(stdQue2.stdQue.toString());
}
As you are creating the linkedlist object stdQue inside the action performed event of button, the object is getting created and reinitialized every time the button is clicked. To make the data persistent, please take the object creation outside the button click event.
Assuming the class name as StudentManager, you can create the object inside the constructor:
class StudentManager {
Queue stdQue;
public StudentManager() {
stdQue = new LinkedList(); <-- Create the queue
}
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt)
{
.
.
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
.
.
}
}

Categories