Hello Guys.
I need a help here.
I am doing a system using Java with GUI.
SO im curious how to add a value that i have extracted from a JTextField and display it as a List in the Jlist.

Here is my coding

//function for collecting data from JTextField
private void GetBookDetails()
	{
	
		newBook.setTitle(txtBookName.getText());
		newBook.setAuthor(txtAuthor.getText());
		newBook.setISBN(Integer.parseInt(txtISBN.getText()));
		newBook.setPublishr(txtPublisher.getText());
		newBook.setIDNum(Integer.parseInt(txtBookIDShow.getText()));
		newBook.setBookStat(Integer.parseInt(txtStatus.getText()));
		newBook.setReturnDate(Integer.parseInt(txtReturnDate.getText()));
		newBook.setCatNumPublicationYr(Integer.parseInt(txtPublicationYr.getText()));
	}


//function to put the BookID in the JList
private void AddBookJButtonActionPerformed(ActionEvent event)
	{
		long IDNum = 0L;
		String Title="",Author="",Publishr=""; 
		int CatNumPublicationYr=0; 
		long returnDate=0L; 
		int BookStat=0; 
		long ISBN=0L;
		GetBookDetails();
		newBook = new Book (IDNum, Title,Author,Publishr,CatNumPublicationYr,returnDate,BookStat,ISBN);
		newBookArrayList.add(newBook);
		position = newBookArrayList.size() - 1;
		
		BookList.setListData(newBookArrayList.toArray());
		
	}

Hope to have an immediate response..thnk you

Recommended Answers

All 14 Replies

These lines are incorrect:

GetBookDetails();
newBook = new Book (IDNum, Title,Author,Publishr,CatNumPublicationYr,returnDate,BookStat,ISBN);

with the GetBookDetails you get all the date from the gui, but when you call the "new Book" you "erase" the previous object and replace it with the new one. At the next lines the newBook doesn't have any of the values read because you did newBook = new Book and you created a new one with the default values that are declared at the class.

I think that this is what you want:

newBook = new Book (IDNum, Title,Author,Publishr,CatNumPublicationYr,returnDate,BookStat,ISBN);

GetBookDetails();

Okie brother, I have changed the place ...i put the coding at the top and still im getting errors...

These are the errors that occured...

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "123456789123"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:459)
    at java.lang.Integer.parseInt(Integer.java:497)
    at LibraryGUI.GetBookDetails(LibraryGUI.java:686)
    at LibraryGUI.AddBookJButtonActionPerformed(LibraryGUI.java:672)
    at LibraryGUI.access$100(LibraryGUI.java:7)
    at LibraryGUI$2.actionPerformed(LibraryGUI.java:292)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6216)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
    at java.awt.Component.processEvent(Component.java:5981)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4583)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4413)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150)
    at java.awt.Container.dispatchEventImpl(Container.java:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4413)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Process completed.

This is another error that i get before the above errors

Note: C:\Documents and Settings\Thalabathy\Desktop\LibraryGUI\src\LibraryGUI.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

What Does This Errors Mean..???

Because this:
123456789123
is not an int, it's a long.

It is a classic mistake when you try to use a big number. If you check the API you will see how big an int can be.

What value does this represent? Because we use int or long when we intend to do calculations with the fields.
For example if you want to save a phone number make it as String not an int.
If it is some key or id then you can put it to be long.

I wanted to put long for ISBN number, Book ID Number and ReturnDate. Is it a good specification of data type or is there any modification i should do? Advice Please mr. javaaddict Thank you... =)

Okie Brother...I think i have solved the problem. But when i add the book and want them to appear in the JList. It doest appear...But the book id is not appearing instead of sumthing else.

Below is the Variable that I filled Up in JTextField
BOOkID: 12
Book Title: QWERTY
Author Name: aviki
Publication year: 2003
Publisher: wells
ISBN: 123456789
Book Return Date: 120309
BookStat: 3

and when i click add book button, it appears like dis

Book@b0f13d

dis is wad the book id...im not sure wads the problem...so wads wrong here... below is the coding for add button action event....

private void AddBookJButtonActionPerformed(ActionEvent event)
	{
		
		long IDNum=0L,ISBN=0L,returnDate=0L ;
		String Title=null,Author=null,Publishr=null; 
		int CatNumPublicationYr=0,BookStat=0; 
		
		newBook = new Book (IDNum,Title,Author,Publishr,CatNumPublicationYr,returnDate,BookStat,ISBN);
		
		GetBookDetails();
		
		newBookArrayList.add(newBook);
		position = newBookArrayList.size() - 1;
		
		BookList.setListData(newBookArrayList.toArray());
		
	}

Hope u can explain to me why my output is like dat...
Thanks bro...
And ignore the above post, I have already solved it.. Thank you...

I am not familiar with the classes of the javax.swing you are using but my experience tells me this:

Firstly, I assume that the method you use to add the book to the list takes as argument an Object class. That is OK because your Book extends the Object class and all of its methods.
But since it takes an Object as parameter it doesn't know the methods you have declared in your Book for displaying data.

But wait the Object class has a method that all classes inherit. That method is automatically called to display the data. But since you didn't override it, it returns what the original method returns: The name of the class followed by its hashCode value:
Book@b0f13d.

You know what is the method I am talking about don't you? It is the toString method.

Try this:
In a separate class create a Book instance in the main method, do this and execute that code:

public static void main(String [] args) {
   Book newBook = new Book (IDNum,Title,Author,Publishr,CatNumPublicationYr,returnDate,BookStat,ISBN);
  
  System.out.println(newBook);
}

Then go to the Book class and do this:

class Book {

   public String toString() {
      return "This book: " + title + " was written by "+ author;
   }
}

And execute the above code again and see what happens.


Also the same applies when you put objects inside a List (Vector, ArrayList) and you try to print that list. It prints the toString method of each of the elements in the list.

Vector v = new Vector();

v.add(new Book(....));
v.add(new Book(....));
v.add(new Book(....));

System.out.println(v); // when you put objects inside that method the toString method is automatically called
// it is like writing:
System.out.println(v.toString);

// the same happens here:
String s = "" + newBook;

// is like saying:
String s = newBook.toString();

Hello Brother.
I have follwed wad u advised me and i got the output that I want. Now i want to ask u... What should I do to combine 3 different classes which inherits from one sper class into an arraylist. Here i have a problem where there are 3 patron type so I have inherited this three patron type from the super class which is patron class. So i want to knoe...if im about to retrive the information from th choosen patron by the user either patron 1 or 2 or 3, how to i combine them as an object and display them on screen as a patron infrmation.

Below is my code which is similar to what i have posted on top

//this function is to get all the data from the textboxs. But here i have //only implemente the first four textbox from the super class only.
//If i enable the other textboxes as well, my program wont work //correctly.

private void GetPatronDetails()
	{
			newPatron.setName(txtPatronName.getText());
			newPatron.setAddress(txtPatronAdd.getText());
			newPatron.setPhoneNo(txtPatronTphone.getText());
			newPatron.setPatronID(txtPatronNum.getText());
			/*newUnderGradPatron.setProgram(txtUnderGradProg.getText());
			newUnderGradPatron.setCrdtHour(Integer.parseInt(txtUnderGradCredit.getText()));
			newGraduatePatron.setAdvisor(txtGradAdvisorName.getText());
			newGraduatePatron.setGradProgram(txtGraduateProg.getText());
			newFacultyPatron.setOfficeAdd(txtFacPatronOffAdd.getText());
			newFacultyPatron.setOfficeNum(txtFacPatronOffNum.getText());*/
		
	}
	

//this is the action performed when add button is clicked.
// all the information to the corresponding patron that the user choosed //must appear in the message box as information.

	private void AddPatronJButtonActionPerformed(ActionEvent event)
	{
		String Name="",Address="",phoneNo="",PatronID="",GradProgram="",Advisor="",Program="",officeAdd="",officeNum="";
		int crdtHour=0;
		
		newPatron = new Patron(PatronID);
		
		GetPatronDetails();
		
		newPatronArrayList.add(newPatron);
		position = newPatronArrayList.size() - 1;
		
		ShowPatronIDArrayList.add(String.valueOf(newPatron.getPatronID()));
		PatronList.setListData(ShowPatronIDArrayList.toArray());
	}

// P/S In patron type. I have used 3 radiobutton to make the user choose which patron type is their customer are. So when a radiobutton is clicked only the corresponding textfields will be enabled. For example, if patron graduate is clicked, only name, address, telephone number, advisor name, and graduate program textfields will be enalbed. other textfields will stay disabled. So how to extract the exact information from the exact patron type and display on the screen. Hope to have an immediate reply. Thank you

I didn't quite realize your problem but here are some suggestions.

You can have one class with all the info and you can have one field indicating what type it is. You can have if-statements that check that field (type of patron) and display the data you want.


If you want to put different objects that extend the same class in the same list then here is an example:

public class Father {
    public Father() {

    }
    public String nameOfTheClass() {
        return "[ Father ]";
    }
}

public class Child1 extends Father {
    public Child1() {

    }
    public String nameOfTheClass() {
        return "[ Child 1 ]";
    }
}

public class Child2 extends Father {
    public Child2() {

    }
    public String nameOfTheClass() {
        return "[ Child 2 ]";
    }
}

Then the following code has 2 versions depending if you are using version 1.4 or newer.

Father f = new Father();
        Child1 ch1 = new Child1();
        Child2 ch2 = new Child2();

        [B]// You can add them to vector because they are all of type "Father[/B]"
        Vector<Father> v2 = new Vector<Father>();
        v2.add(f);
        v2.add(ch1);
        v2.add(ch2);

        [B]// here you get them from the vector and put them into "Father" objects[/B]
        Father f1 = v2.get(0);
        Father f2 = v2.get(1);
        Father f3 = v2.get(2);

       [B]// But when you print them[/B]
        System.out.println(f1.nameOfTheClass());
        System.out.println(f2.nameOfTheClass());
        System.out.println(f3.nameOfTheClass());

        [B]// The f2,f3 are actually "Child1", "Child2". You have access to the data of the Child1, Child2 classes but of course you can call only the methods of the parent class[/B]

        //////////////////////////////////////
        System.out.println("----");
        //////////////////////////////////////
        Vector v = new Vector();

        v.add(f);
        v.add(ch1);
        v.add(ch2);

        Father f_1 = (Father)v.get(0);
        Father f_2 = (Father)v.get(1);
        Father f_3 = (Father)v.get(2);

        System.out.println(f_1.nameOfTheClass());
        System.out.println(f_2.nameOfTheClass());
        System.out.println(f_3.nameOfTheClass());

[B]// With that way you can cast each element from the vector to its own type[/B]
        if (f_2 instanceof Child1) {
            Child1 ch_1 = (Child1)f_2;
        }

        if (f_3 instanceof Child1) {
            Child2 ch_2 = (Child2)f_3;
        }
    }

The best way to utilize the above example is to have all classes to implement the toString method. Have each class return its own data. Then put all classes that extend the same class in a Vector, and get them as the super class like the example.
After you call the toString method, each element will return their own data; even though they are declared as the super class

Oke Bro...Im not having problem with the classes. Now Im realise that I have problem with the radiobutton. Well as i explained above, I have 3 radiobutton at the GUI. So the user has to choose ONE radiobutton to make some of the textfields enable. So if the user choosed patron type A, then only patron type A's textfield will be enabled. Other patron types textfield will stay disabed. So here im confused, becase i Have create 4 new object, one for the parent class, and three for the child classes. Here Im confused on how to extract the data enterd by user in the textfields dat was enabled and display them as the patron's information.

#
private void AddPatronJButtonActionPerformed(ActionEvent event)
#
{
#
String Name="",Address="",phoneNo="",PatronID="",GradProgram="",Advisor="",Program="",officeAdd="",officeNum="";
#
int crdtHour=0;
#
 
#
newPatron = new Patron(PatronID);
#
 
#
GetPatronDetails();
#
 
#
newPatronArrayList.add(newPatron);
#
position = newPatronArrayList.size() - 1;
#
 
#
ShowPatronIDArrayList.add(String.valueOf(newPatron.getPatronID()));
#
PatronList.setListData(ShowPatronIDArrayList.toArray());
#
}

//dis code above is showing that Im taking all the information entered in the textfield and store them in arraylist.  This function will help me to display the id number of the patron on the JList which I have already made it like dat to happen..i dun have problem in display the id.
#
private void GetPatronDetails()
#
{
#
newPatron.setName(txtPatronName.getText());
#
newPatron.setAddress(txtPatronAdd.getText());
#
newPatron.setPhoneNo(txtPatronTphone.getText());
#
newPatron.setPatronID(txtPatronNum.getText());
#
/*newUnderGradPatron.setProgram(txtUnderGradProg.getText());
#
newUnderGradPatron.setCrdtHour(Integer.parseInt(txtUnderGradCredit.getText()));
#
newGraduatePatron.setAdvisor(txtGradAdvisorName.getText());
#
newGraduatePatron.setGradProgram(txtGraduateProg.getText());
#
newFacultyPatron.setOfficeAdd(txtFacPatronOffAdd.getText());
#
newFacultyPatron.setOfficeNum(txtFacPatronOffNum.getText());*/
#
 
#
}

// above is the coding for me to extract the data from the textfield. as u can see I have only enabled the newPatron object's data only while other 3 child class patrons I didnt enable because it shows me error if i do so. So i wanna knoe is there any other way of enabling the other 3 classes and call them back in this particular function or i have to do seperately. And if i have to do seperately. How am i going to implement the radiobutton choosed by the user. Thats wad i wanted to knoe brother.

Inside the actionPerformed you can try this:

private void actionPerformed(ActionEvent event) {
  // assuming that you have a list globally of type Patron (the super class)

  if (radioButton1 is checked) {
     // get from the desired fields the data and create a new instance:
     [B]newUnderGradPatron[/B]= new [B]UnderGradPatron[/B]();
    // set the values from the fields
    // add to the same list

  } else if (radioButton2 is checked) {
     // get from the desired fields the data and create a new instance:
     [B]newGraduatePatron[/B]= new [B]GraduatePatron[/B]();
    // set the values from the fields
    // add to the same list

  } else if (radioButton3 is checked) {
     // get from the desired fields the data and create a new instance:
     [B]newFacultyPatron[/B]= new [B]FacultyPatron[/B]();
    // set the values from the fields
    // add to the same list
  }
}
//this coding i for me to get data from particular textfield if the corresponding JRadioButton is checked. Is this The right method to do it?

private void GetPatronDetails()
	{
		if(GradPatron.isSelected())
		{
			newPatron.setName(txtPatronName.getText());
			newPatron.setAddress(txtPatronAdd.getText());
			newPatron.setPhoneNo(txtPatronTphone.getText());
			newPatron.setPatronID(txtPatronNum.getText());
			newGraduatePatron.setAdvisor(txtGradAdvisorName.getText());
			newGraduatePatron.setGradProgram(txtGraduateProg.getText());
		}
		else
			if(UnderGradPatron.isSelected())
			{
				newPatron.setName(txtPatronName.getText());
			    newPatron.setAddress(txtPatronAdd.getText());
			    newPatron.setPhoneNo(txtPatronTphone.getText());
			    newPatron.setPatronID(txtPatronNum.getText());
				newUnderGradPatron.setProgram(txtUnderGradProg.getText());
			    newUnderGradPatron.setCrdtHour(Integer.parseInt(txtUnderGradCredit.getText()));
			}
			else
				if(FacPatron.isSelected())
			    {
				   newPatron.setName(txtPatronName.getText());
			       newPatron.setAddress(txtPatronAdd.getText());
			       newPatron.setPhoneNo(txtPatronTphone.getText());
			       newPatron.setPatronID(txtPatronNum.getText());
			   	   newFacultyPatron.setOfficeAdd(txtFacPatronOffAdd.getText());
			       newFacultyPatron.setOfficeNum(txtFacPatronOffNum.getText());
			    }	
	}

When I compile this coding...there is no problem. But when i enter the data and press the Add button, it doesnt appear in the JList and giving me NUll Pointer Exception. Is my method wrong or did I made mistake sumwhr else???

You don't need the newPatron object. In the if statements you will only have one instance. You will not have an instance of the super class. Only of child classes. The way you have it in the if statements, you put some data in:
newPatron: newPatron.setName(txtPatronName.getText()); and some in newGraduatePatron: newGraduatePatron.setAdvisor(txtGradAdvisorName.getText()); Then which one will you put in the list. Remember, the chilcd class have access to the super methods:

public class Father {
   public String name;
   public String getName() {
      return name;
   }
    public void setName(String name) {
        this.name = name;
    }
}

public class Child1 extends Father {
   public int age;
   public int getAge() {
      return age;
   }
    public void setAge(int age) {
        this.age = age;
    }
}

// SO:
{
    Child1 ch1 = new Child1();
     ch1.[B]setName[/B]("Name");
     ch1.[B]setAge[/B](11);
}

In your code you can have this:

private void GetPatronDetails()
	{
		if(GradPatron.isSelected())
		{
			newGraduatePatron.setName(txtPatronName.getText());
			newGraduatePatron.setAddress(txtPatronAdd.getText());
			newGraduatePatron.setPhoneNo(txtPatronTphone.getText());
			newGraduatePatron.setPatronID(txtPatronNum.getText());
			newGraduatePatron.setAdvisor(txtGradAdvisorName.getText());
			newGraduatePatron.setGradProgram(txtGraduateProg.getText());

[B]// add to list the newGraduatePatron[/B]
		}
		else
			if(UnderGradPatron.isSelected())
			{
......
[B]// add to list the newUnderGradPatron[/B]
			}
			else
				if(FacPatron.isSelected())
			    {
		
.....
[B]// add to list the newFacultyPatron[/B]
			    }	
	}

Or you can have the above method return the patron:

private Patron GetPatronDetails()
	{
		if(GradPatron.isSelected())
		{
			// get the data from the fields
    return newGraduatePatron;
		}
		else
			if(UnderGradPatron.isSelected())
			{
							// get the data from the fields
return newUnderGradPatron;
			}
			else
				if(FacPatron.isSelected())
			    {
						// get the data from the fields
return newFacultyPatron;
			    }	
	}

All right brother. I got wad r u trying to say. One more problem bro. How do you choose an element from the JList( single click ) and when i click a button called Loan, it will appear a jOptionPane tellin me if i want to borow the book.

All right brother. I got wad r u trying to say. One more problem bro. How do you choose an element from the JList( single click ) and when i click a button called Loan, it will appear a jOptionPane tellin me if i want to borow the book.

I would suggest, before asking such questions, first to check the java API:
java API
javax.swing
JList
getSelectedValue()

When you click the button, inside the actionPerformed, call that method (getSelectedValue) I assume that you have added "Patron" objects inside the list. If that method returns something other than null, means that you have selected something at the list. Then you can cast it to "Patron" and you are ready to do whatever you want.
Also if you need to cast it to some other of the "child" classes then I have showed you a way with the "instanceOf" keyword:

Patron patron = (Patron)list.getSelectedValue();

//either use the methods of the super class, or do some more casting:
if (patron instanceOf UnderGraduate) {
     UnderGraduate unGrad = (UnderGraduate)patron;
} else if (...) { ... }

I don't quite remember the "instanceOf " syntax so you might want to double check it by searching for it at the internet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.