Add Row to JTable and File - java

I use this method to add a new row to my jtable and file too.
But when i clicked to add button, That new record added to jtable, but when i see the text file, I found something like this:
myproject.Library.BookInformation#9899472
where is my mistake?
My code:
public class MainS extends JFrame{
final AllBooks allBooks=new AllBooks();
final JTable Btable=new JTable(allBooks);
public MainS(){
JButton AddBookButton=new JButton("Add New Book");
AddBookButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
AddDialogS adddialog=new AddDialogS(MainS.this);
adddialog.setVisible(true);
BookInformation B_info=adddialog.getBookInfos();
if(B_info != null){
allBooks.AddRow(B_info);
}
}
});
JPanel Bpanel=new JPanel();
Bpanel.setLayout(new FlowLayout());
JScrollPane sp=new JScrollPane(Btable);
Bpanel.add(sp);
Bpanel.add(AddBookButton);
this.add(Bpanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(300, 60, 550, 550);
this.setVisible(true);
}
public static void main(String[] args){
new MainS();
}
}
second class for add new record:
public class AddDialogS extends JDialog{
BookInformation bookinform=new BookInformation();
public AddDialogS(JFrame owner){
super(owner,"Add New Book!", true);
JButton OkButton=new JButton("Ok");
final JTextField nameTF=new JTextField(10);
JLabel namelbl=new JLabel("bookname");
final JTextField dateTF=new JTextField(10);
JLabel datelbl=new JLabel("bookDate");
final JTextField idTF=new JTextField(10);
JLabel IDlbl=new JLabel("bookId");
OkButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bookinform.setBookName(nameTF.getText().trim());
bookinform.setBookDate(String.valueOf(dateTF.getText().trim()));
bookinform.setBookID(String.valueOf(idTF.getText().trim()));
AddDialogS.this.dispose();
}
});
JPanel panel=new JPanel(new FlowLayout());
panel.add(OkButton);
panel.add(nameTF);
panel.add(dateTF);
panel.add(idTF);
panel.add(namelbl);
panel.add(datelbl);
panel.add(IDlbl);
this.add(panel);
this.setBounds(10, 30, 400, 500);
}
public BookInformation getBookInfos(){
return bookinform;
}
}
My table model Class:
public class AllBooks extends AbstractTableModel{
BookInformation Binfos1=new BookInformation();
String[] Bcol=new String[]{"Name","Date","Id"};
List<BookInformation> Bdata=new ArrayList<BookInformation>();
public AllBooks(){
try{
FileReader fr=new FileReader("AllBookRecords.txt");
BufferedReader br=new BufferedReader(fr);
String line;
while( (line=br.readLine()) !=null){
Bdata.add(initializeBookInfos(line));
}
br.close();
}
catch(IOException ioe){
}
}
public static BookInformation initializeBookInfos(String str){
BookInformation Binit=new BookInformation();
String[] bookCellArray=str.split(" ");
Binit.setBookName(bookCellArray[0]);
Binit.setBookDate(bookCellArray[1]);
Binit.setBookID(bookCellArray[2]);
return Binit;
}
public void AddRow(BookInformation bookinfo){
if(AddToFile(bookinfo)){
Bdata.add(bookinfo);
fireTableRowsInserted(Bdata.size()-1, Bdata.size()-1);
}
else{
JOptionPane.showMessageDialog(null, "Unable Add To File"+bookinfo.getBookName());
}
}
public boolean AddToFile(String bookinfos){
try{
PrintWriter Bpw=new PrintWriter(new FileOutputStream("AllBookRecords.txt",true));
Bpw.println(bookinfos);
return true;
}
catch(IOException ioe){
return false;
}
}
#Override
public String getColumnName(int col){
return Bcol[col];
}
#Override
public int getRowCount() {
if(Bdata !=null){
return Bdata.size();
}
else{
return 0;
}
}
#Override
public int getColumnCount() {
return Bcol.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
BookInformation binfo=Bdata.get(rowIndex);
Object value;
switch(columnIndex){
case 0:
value=binfo.getBookName();
break;
case 1:
value=binfo.getBookDate();
break;
case 2:
value=binfo.getBookID();
break;
default :
value="...";
}
return value;
}
}
My BookInformation Class:
public class BookInformation {
private String BookName;
private String BookDate;
private String BookID;
public String getBookName() {
return BookName;
}
public void setBookName(String book_name) {
this.BookName = book_name;
}
public String getBookDate() {
return BookDate;
}
public void setBookDate(String book_date) {
this.BookDate = book_date;
}
public String getBookID() {
return BookID;
}
public void setBookID(String Book_id) {
this.BookID = Book_id;
}
}
Thanks for help.

Looks like what you get in the file is a result of method toString() invocation on an object of this class: myproject.Library.BookInformation.
So the quickest fix in your case would be to override toString() method for BookInformation to return what you need.
public String toString() {
return getBookName(); // Or whatever you see fit.
}
Even if later you'll change your code not to rely on toString() a meaningful implementation is not going to hurt.
Unlike in another answer you do NOT have to change code for AddToFile if you override toString(). However, if you don't modify code for BookingInformation, then you would have to craft string value when you call AddToFile similar to what was suggested:
AddToFile(bookinfo.getBookName()) // Or whatever you see fit.
Another even better way would be to modify AddToFile method to accept BookingInformation as a parameter.
public boolean AddToFile(BookingInformation bookinfos){
try{
PrintWriter Bpw=new PrintWriter(new FileOutputStream("AllBookRecords.txt",true));
Bpw.println(bookinfos.getBookName()); // Or whatever you see fit.
return true;
}
catch(IOException ioe){
return false;
}
}

In your BookInformation class add a toString method like this
public String toString(){
return BookID + " " + BookDate + " " + BookName;
}
and then call AddToFile() like this
AddToFile(bookinfo.toString())
from AddRow method.

There are any number solutions you could try.
You could modify your AddToFile method to write to format the properties of the object as you need it.
This ensures that the format that the model writes the file in is what the model expects when it reads it back it.
public boolean AddToFile(BookInformation bookinfos){
try{
PrintWriter Bpw=new PrintWriter(new FileOutputStream("AllBookRecords.txt",true));
StringBuilder sb = new StringBuilder(64);
sb.append(bookinfos.getBookID()).append(";");
sb.append(bookinfos.getBookName()).append(";");
sb.append(bookinfos.getBookID()).append(";");
Bpw.println(sb.toString());
return true;
}
catch(IOException ioe){
return false;
}
}
You can of course define your own format and delimiters. This has the benefit of allowing the model to control it's own format and does not effect any other part of the program, like using toString() would.
Alternativly, you could write a read/write method in the BookInformation class, passing in the PrintWriter and allowing the BookInformation to determine the format that the data should be maintained in.
This has the benefit of allowing other parts of the program to save the object in a uniform manner and if the format ever changes (ie you add new fields), it changes in one location

Related

Storing input from TextFields and ComboBox in JavaFX?

I'm making a basic Movie Rental simulator application, and I am currently having a problem storing the input from my TextFields and my ComboBox into variables. I managed to convert most of my variables to Strings, however when I try and print the output to test it, it always returns "null."
I need to essentially figure out how to GET the selection the user has made in the combo box and store it as a string, and I need to figure out how to properly store the results from my methods. I have never ran into this problem before, so I am not really sure how to tackle it. My code is as follows:
public class RentGameDialogController extends RentalStoreGUIController implements Initializable{
/** TextField Objects **/
#FXML private TextField nameField, rentedOnField, dueBackField;
/** String for NameField **/
String name, rentedOn, dueBack;
/** Game ComboBox ID's **/
#FXML private ObservableList<GameType> cbGameOptions;
#FXML private ComboBox<GameType> cbGame;
/** Console ComboBox ID's **/
#FXML private ObservableList<PlayerType> cbConsoleOptions;
#FXML private ComboBox<PlayerType> cbConsole;
/** GameType object **/
private GameType game;
/** PlayerType Object **/
private PlayerType console;
/** Button ID's **/
#FXML Button cancel, addToCart;
/** Counter for calculating total **/
int gameCounter;
/** Stage for closing GUI **/
private Stage currentStage;
#Override
public void initialize(URL location, ResourceBundle resources) {
/** Select Console **/
cbConsoleOptions = FXCollections.observableArrayList();
for (PlayerType p : PlayerType.values()) { cbConsoleOptions.addAll(p); }
cbConsole.getItems().addAll(cbConsoleOptions);
/** Select Game **/
cbGameOptions = FXCollections.observableArrayList();
for (GameType g : GameType.values()){ cbGameOptions.addAll(g); }
cbGame.getItems().addAll(cbGameOptions);
}
public String getName(){
name = nameField.getText();
try {
String[] firstLast = name.split(" ");
String firstName = firstLast[0];
String lastName = firstLast[1];
} catch (Exception e){
e.printStackTrace();
}
return name;
}
public void getGame() {
GameType gameChoice = cbGame.getSelectionModel().getSelectedItem();
}
public void getConsole() {
PlayerType player = cbConsole.getSelectionModel().getSelectedItem();
}
public String getRentedOn() throws ParseException {
rentedOn = rentedOnField.getText();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date rentedOnDate = format.parse(rentedOn);
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(rentedOnDate);
try {
cal.getTime();
} catch (Exception e) {
System.exit(0);
}
return rentedOn;
}
public String getDueBack() throws ParseException {
dueBack = dueBackField.getText();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date dueBackDate = format.parse(dueBack);
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(dueBackDate);
try {
cal.getTime();
} catch (Exception e) {
System.exit(0);
}
return dueBack;
}
/*************************************
* This is the method to call the other
* String methods so their output can be
* put into my main GUI
*
* Current problem: game.toString() and console.toString() throw an InvocationTargetException
* #return
* #throws ParseException
*************************************/
public String storePurchaseData() throws ParseException {
gameCounter++; //Problem //Problem
String toList = getName() + " " + game.toString() + " " + console.toString() + " " +
getRentedOn() + " " + getDueBack();
return toList; //Returns "null null null"
}
#FXML
public void handleCancelButtonAction (ActionEvent event) {
currentStage = (Stage) cancel.getScene().getWindow();
currentStage.close();
}
#FXML
public void addToCartButton (ActionEvent event) throws ParseException {
System.out.println(storePurchaseData());
currentStage = (Stage) cancel.getScene().getWindow();
currentStage.close();
}}
Enum Classes for GameType and PlayerType(Console selection):
public enum PlayerType {
Xbox360("Xbox 360"),
PS4("Playstation 4"),
XBoxOne("Xbox One"),
WiiU("Wii - U"),
PS3("Playstation 3"),
Wii("Nintendo Wii");
private String console;
PlayerType(String console) { this.console = console; }
public String PlayerType() { return console; }
#Override public String toString() { return console; }}
GameType:
public enum GameType {
THE_WITCHER("The Witcher 3"),
CALL_OF_DUTY_AW("Call of Duty: Advanced Warfare"),
CALL_DUTY_BLOP3("Call of Duty: Black Ops 3"),
CALL_OF_DUTY_IW("Call of Duty: Infinite Warfare"),
THE_ELDER_SCROLLS("The Elder Scrolls IV: Skyrim");
private String game;
GameType(String game) {
this.game = game;
}
public String GameType() { return game; }
#Override public String toString() { return game; }}
The only method that will return the selected value is getName()
The rest of the methods you are using don't return anything
public void getGame() //Void return type
{
GameType gameChoice = cbGame.getSelectionModel().getSelectedItem();
}
All this does is create a GameType object that is accessible only inside of that method.
Instead it should be
public GameType getGame() //Instead of void, the type you are trying to get
{
return cbGame.getSelectionModel().getSelectedItem();
}
That way, you can then access the result by
GameType selectedGame = getGame();
If you want it as a String use
public String getGame()
{
return cbGame.getSelectionModel().getSelectedItem().toString();
}

Storing String with name from file or text

In the image, Its not "store a string",Its "make a string".
My question is , I want to make a string with name and text according to what value we give(much more understood by the image).
Hope you understand the ques.
I have given no code as i don't no how to procced.
you could use as like this thinking more OOP
class CMD{
private String VarName;
private String Value;
public String getType() {
return Type;
}
public void setVarName(String varName) {
VarName= varName;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
}
and the main code
public static void main(String[] args) {
//cmd mystring = "this is string"
String cmd="MyString=\"this is string\"";
String[] str=cmd.split("=");
Vector<CMD> myCMD=new Vector<CMD>();
CMD c = null;
c.setVarName(str[0]);
c.setValue(str[1]);
myCMD.add(c);
}
a way to start is to use jtextfield and addActionListener()
String CMDline=null;
Action action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e)
{
CMDline=textField.getText();
doSomething(CMDline);
textField.setText(">");
} };
JTextField textField = new JTextField(10);
textField.addActionListener( action );
textField.setText(">");
doSomething() where you need to split the String and get the name, type of variable & value.

Sorting of ArrayList<Track>

I want to sort ArrayList according to artist's name I have used comparator interface but I'm not able to sort the list. So kindly help me to solve the problem. The track data will be read from a file Trackdump. The file would contain one track data per line in the format TITLE/ARTIST/RATING/BPM
Here is the code:
import java.io.*;
import java.util.*;
public class MusicLibrary {
ArrayList<Track> songList = new ArrayList<Track>();
public static void main(String args[]) {
new MusicLibrary().go();
}
public void go() {
System.out.println("go");
getTracks();
System.out.println("Before Sorting:");
System.out.println(songList);
Collections.sort(songList);
System.out.println("Sorted according to Artist's name:");
System.out.println(songList);
}
void getTracks() {
System.out.println("gt");
File file = new File("TrackDump.txt");
try{
BufferedReader readr = new BufferedReader(new FileReader(file));
String line = null;
System.out.println(readr);
while ((line = readr.readLine()) != null) {
System.out.println(line);
addSong(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
void addSong(String lineToParse) {
String[] tokens = lineToParse.split("/");
Track nextSong = new Track(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
System.out.println(songList);
}
}
class Track implements Comparator<Track>
{
String title;
String artist;
String rating;
String bpm;
public int compare(Track o1, Track o2) {
return o1.getArtist().compareTo(o2.getArtist());
}
public Track(String a, String t, String r, String b) {
title = t;
artist = a;
rating = r;
bpm = b;
}
public boolean equals(Object aSong) {
return this.equals(aSong);
}
public String getArtist() {
return artist;
}
public String getBpm() {
return bpm;
}
public String getRating() {
return rating;
}
public String getTitle() {
return title;
}
public String toString() {
return title + "-" + artist;
}
}
Trackdump:
Title1/Artist1/8/320
Title2/Artist2/10/48
T5/A7/10/120
Title4/A7/9/240
T7/Artist5/7/320
Title6/Artist6/3/240
T9/A7/1/550
T6/Artist8/5/120
T1/Artist9/5/290
Song2/A0/5/320
Song5/A8/10/320
Song1/A2/6/290
You have to implement Comparable class to your Track class. Not Comparator. Then override compareTo() method. It would look like this:
public class Track implements Comparable<Track> {
// Variables, constructor, getters, setters ...
#Override
public int compareTo(Track other) {
return this.getArtist().compareTo(other.getArtist());
}
}
Finally sort with Collections.sort();
You need to implement the Comparable interface and then you can use Collections.sort().
class Track implements Comparable<Track> {
String title;
String artist;
String rating;
String bpm;
#Override
public int compare(Track other) {
return this.getArtist().compareTo(other.getArtist());
}
...
In theory it would work too when implementing Comparator but then you have to pass a Track object into Collections.sort() to act as the Comparator. But that is a rather weird way of doing it so better use the solution above.
Collections.sort(songList, new Track(null, null, null, null));

How to add objects to CComboBox

I have declared my CComboBox as follows :
final CCombo combobox= new CCombo(shell, SWT.BORDER);
combobox.setBounds(30, 22, 88, 21);
ResultSet result = statement.executeQuery();
I want to add an object of Class myCombo to combobox
while(result.next())
{
String ProName=result.getString(1);
String ProId=result.getString(2);
myCombo comboItem=new myCombo(ProId,ProName); //OBJECT comboItem
combobox.addElement(comboItem); //ERROR The method addElement(myCombo)
is undefined for the type CCombo
}
Error in combobox.addElement(comboItem) .... but addElement() is already defined in CCombo.
This is class myCombo
class myCombo{
private String ProId;
private String ProName;
public myCombo(String ProId, String ProName) {
this.ProId=ProId;
this.ProName=ProName;
}
public String getProductName() {
return ProName;
}
public String getProductId() {
return ProId;
}
#Override
public String toString() {
return ProName;
}
}
How to get back the data which is selected.
Showing ERROR as cant
combobox.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
myCombo item = (myCombo) combo.getItem(getSelectionIndex()) ; //ERROR
if (item!=null) {
System.out.printf("You've selected Product Name: %s, Product ID: %s%n",
item.getProductName(), item.getProductId());
}
}
});
If you are using org.eclipse.swt.custom.CCombo than it does't have addElement(Object o) method.It has add(String s) method you have to override toString().
myCombo comboItem=new myCombo(ProId,ProName);
combobox.add(comboItem.toString())
FOR EXAMPLE
#Override
public String toString() {
return ProId+":"+ProName;
}
TO Fetch Selection,
combo.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
System.out.print("Selected Value-");
System.out.print(combo.getItem(combo.getSelectionIndex()));
}
});

JTable repetitive rows

My jtable should read a text file and show them.
It reads all data correctly, But just show last line record in file, in its all rows repetitive.
Where is my mistake?
My text file:
uiui 898 666999
vvvv 6666 7777
hfsn 5356 56
ds 232 2212
bbnn 2013 211
My AllBooks Class:
public class AllBooks extends AbstractTableModel{
BookInformation Binfos=new BookInformation();
String[] Bcol=new String[]{"Name","Date","Id"};
List<BookInformation> Bdata=new ArrayList<BookInformation>();
public AllBooks(){
try{
FileReader fr=new FileReader("AllBookRecords.txt");
BufferedReader br=new BufferedReader(fr);
String line;
while( (line=br.readLine()) !=null){
Bdata.add(initializeUserInfos(line));
}
br.close();
}
catch(IOException ioe){
}
}
public BookInformation initializeUserInfos(String str){
System.out.println(str);
String[] bookCellArray=str.split(" ");
Binfos.setBookName(bookCellArray[0]);
Binfos.setBookDate(bookCellArray[1]);
Binfos.setBookID(bookCellArray[2]);
return Binfos;
}
#Override
public String getColumnName(int col){
return Bcol[col];
}
#Override
public int getRowCount() {
if(Bdata !=null){
return Bdata.size();
}
else{
return 0;
}
}
#Override
public int getColumnCount() {
return Bcol.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
BookInformation binfo=Bdata.get(rowIndex);
Object value;
switch(columnIndex){
case 0:
value=binfo.getBookName();
break;
case 1:
value=binfo.getBookDate();
break;
case 2:
value=binfo.getBookID();
break;
default :
value="...";
}
return value;
}
}
My AllBooksM Class:
public class AllBooksM {
final AllBooks rbftl=new AllBooks();
final JFrame Bframe=new JFrame("All Book List");
final JTable Btable=new JTable(rbftl);
public AllBooksM(){
JPanel Bpanel=new JPanel();
Bpanel.setLayout(new FlowLayout());
JScrollPane sp=new JScrollPane(Btable);
Bpanel.add(sp);
Bframe.add(Bpanel);
Btable.setAutoCreateRowSorter(true);
Bframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Bframe.setBounds(300, 60, 550, 550);
Bframe.setResizable(false);
Bframe.setVisible(true);
}
public static void main(String[] args){
new AllBooksM();
}
}
My BookInformation Class:
public class BookInformation {
private String BookName;
private String BookDate;
private String BookID;
public String getBookName() {
return BookName;
}
public void setBookName(String book_name) {
this.BookName = book_name;
}
public String getBookDate() {
return BookDate;
}
public void setBookDate(String book_date) {
this.BookDate = book_date;
}
public String getBookID() {
return BookID;
}
public void setBookID(String Book_id) {
this.BookID = Book_id;
}
}
Thanks!
You're using the same BookInformation object with each iteration of the while loop and instead need to create a new one with each iteration. Else that same object will be held by all rows of the table model causing the same information will be displayed on every row.
For instance you can solve it by doing something like this.
public BookInformation initializeUserInfos(String str){
System.out.println(str);
String[] bookCellArray=str.split(" ");
// create and use a local BookInformation variable and object:
BookInformation bInfos = new BookInformation(); // *****
bInfos.setBookName(bookCellArray[0]);
bInfos.setBookDate(bookCellArray[1]);
bInfos.setBookID(bookCellArray[2]);
return bInfos;
}

Categories

Resources