Displaying data in JTable while reading the data from the text file - java

I'm trying to display the column data from separate file and row data from another but it's output is not in normal for row file below attached is the image file for output and both the text file:
private void orbuttonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) orderitemtable.getModel();
model.setRowCount(0);
String filename = "ORDERITEMFILE.txt";
String idnamefile = "odcofile.txt";
File file1 = new File(idnamefile);
File file = new File(filename);
try {
BufferedReader br = new BufferedReader(new FileReader(file1));
BufferedReader br1 = new BufferedReader(new FileReader(file));
//to make the columns name so to get the first line of code
//set columnsname to the jtable Model
String firstLine = br.readLine().trim();
String[] columnsName = firstLine.split("/");
model.setColumnIdentifiers(columnsName);
//get lines from txt files
Object[] tablelines = br1.lines().toArray();
//Extracting the data from lines
//set data to jtable Model
for (int i = 0; i < tablelines.length; i++) {
String line = tablelines[i].toString().trim();
String[] dataRow = line.split(",");
model.addRow(dataRow);
}
} catch (Exception ex) {
Logger.getLogger(productpage.class.getName()).log(Level.SEVERE, null, ex);
}
}
The problem is its displaying the column's until product type after that it changes to new row and display the rest of content over there:
This is the text file for row it read's properly from the txt file the only problem is when it display in JTable it read's in separate row for the last two quantities.
This is the text file for column which.

First off, you really don't need a single file to hold Column Names. You can apply the Column Names as the very first line of your ORDERITEMFILE.txt file, very much like a CSV file would be laid out. Generally the first line of a CSV file would be a delimited string of the Column Names and it's there to be specifically used as such.
If you insist on utilizing two files then may I suggest you deal with the Column Names file first and be rid of it so that it doesn't clutter things up within your event code. Perhaps do this in a separate method:
private String[] getColumnNames(String filePath) {
String[] columns = {};
//Try with Resources (auto closes the reader)
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
// Assumes there is only one line in file.
while ((line = br.readLine()) != null) {
// Ignore blank lines (if any) leading to the line we want.
if (!line.equals("")) { break; }
}
if (line != null && !line.equals("")) {
columns = line.split("/");
}
}
catch (FileNotFoundException ex) {
System.err.println("Column Names File Not Found!");
}
catch (IOException ex) {
System.err.println("IO Exception Encounterd!\n" + ex.getMessage());
}
return columns;
}
Holding the thought of keeping things organized to some degree we now can have another method to set the new Column Names to JTable:
private void setTableColumns(JTable table, String[] columnsName) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setColumnIdentifiers(columnsName);
}
And still holding the organizational thought we have yet another method to fill the JTable with file data:
private int fillTableFromFile(JTable table, String filePath) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int recordCount = 0;
//Try with Resources (auto closes the reader)
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
// Clear current table rows
while (model.getRowCount() > 0) {
for (int i = 0; i < model.getRowCount(); i++) {
model.removeRow(i);
}
}
String dataLine;
Object[] dataArray;
// read in the data and add to table.
while ((dataLine = br.readLine()) != null) {
// Ignore blank lines (if any).
if (dataLine.equals("")) { continue; }
//Split the comma delimited data line into a Object Array
dataArray = dataLine.split(",");
model.addRow(dataArray);
recordCount++;
}
}
catch (FileNotFoundException ex) {
System.err.println("Data File Not Found!");
}
catch (IOException ex) {
System.err.println("IO Exception Encounterd!\n" + ex.getMessage());
}
return recordCount; // The number of records added to table from file.
}
With the above methods in place you can now have some 'easy to follow' (and controllable) code within your JButton Action Performed event. By controllable, I mean for example, you can determine what is to happen if (for whatever reason) the coloumnsName String Array is empty or null (not handled here):
private void orbuttonActionPerformed(java.awt.event.ActionEvent evt) {
String filename="ORDERITEMFILE.txt";
String idnamefile="odcofile.txt";
String[] columnsName = getColumnNames(idnamefile);
setTableColumns(orderitemtable, columnsName);
int numOfRecords = fillTableFromFile(orderitemtable, filename);
JOptionPane.showMessageDialog(orderitemtable, "There were " + numOfRecords +
" Records Added to Table.", "Records Added",
JOptionPane.INFORMATION_MESSAGE);
}
When run and the Order Button is selected the table columns names will be placed, the table will be filled with file data, and a Message Box will appear indicating how many file records were added to table.

Related

How to read CSV data by matching the input in java?

Trying to create a program where the user is asked to enter a location, if the user enters i.e south it can read from the "Location" column in the csv, and whatever row contains "south" (upper or lowercase accepted), the name(s) from the Name column are printed. So if the user enters south, Holos and Deafer are returned.
I can't seem to find how to actually print specific rows that contains matching input, and have only been able to print the whole column.
Any help is much appreciated!
Csv
Name, Location
Holos, South
Tredies, North
Warren, West
Deafer, South
Current code that only reads specific column
public void filter() {
// using buffered reader to read the csv file, still a WIP
String path = "E:\\IT\\2022\\Further Programming\\s3902169_furtherProgrammingA1\\src\\files\\Melbnb.csv";
String line = "";
System.out.println("Enter location");
String stringInput = readUserInput();
BufferedReader br;
try {
br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
if (stringInput.contains(values[1])) {
System.out.print(values[0]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if (stringInput.equalsIgnoreCase(values[1)) {
System.out.println(values[0]);
}

how to import a txt file into a JTable and make the first column auto increment according to the number of lines of the file

i'm doing some java coding and i have to import a file into a Jtable that has 4 columns while my file has 3 (separated by whitespaces, i need the first column of each line to be auto increment, here is my code:
try {
FileReader files = new FileReader(file);
BufferedReader buf = new BufferedReader(files);
String line = null;
String tokens[] = null;
while ((line = buf.readLine()) != null) {
tokens = line.split("\\p{javaWhitespace}+");
//System.out.println( Arrays.toString( tokens ));
model.addRow(tokens);
}
}
and this is what I'm getting :
and this is my file :
Simply add an additional token to the front of your data. This is easiest using a Vector and not an array. The first item in the vector is your row index, the next itmes are filled from your tokens array. For example:
try {
FileReader files = new FileReader(file);
BufferedReader buf = new BufferedReader(files);
String line = null;
String tokens[] = null;
int count = 0;
while ((line = buf.readLine()) != null) {
tokens = line.split("\\p{javaWhitespace}+");
Vector<Object> row = new Vector<>();
row.add(count);
count++;
for (String text: tokens) {
row.add(text);
}
model.addRow(row); // add the Vector, not the tokens array
}
}
There are other ways, including extending the table model such that it automatically does this, and these may need to be done, depending on your needs -- for example, are the rows to renumber if one row is deleted or added during the running of the program? If so the logic needs to be within the table model.

Need Advice on How To Set ComboBox and JXDatePicker back to original setting after clearing screen

I have a jpanel with some textfields, comboboxes, and jxdatepickers and a table which holds the values to those fields. Now, I want to select a row from the table and edit the values by repopulating them in order to change them. I have the following code for when I click the "edit" button after I have selected a row:
private void jButton_editActionPerformed(java.awt.event.ActionEvent evt) {
File h = new File("caseInfoTemp.txt");
BufferedWriter buf;
try {
buf = new BufferedWriter(new FileWriter(h, true));
int row = jTable_caseInfo.getSelectedRow();
for(int j = 0; j < jTable_caseInfo.getColumnCount(); j++) {
buf.write(jTable_caseInfo.getValueAt(row, j).toString() + "\t");
}
buf.newLine();
buf.close();
}catch (Exception e){
}
try{
FileInputStream fstream = new FileInputStream("caseInfoTemp.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
String[] delims = line.split("\t");
jSpinner_case.setValue(Integer.parseInt(delims[0]));
jTextField_case.setText(delims[1]);
//fix to set combobox to what was chosen
jComboBox_client.setPopupVisible(true);
//fix to set datepicker to what was chosen
jXDatePicker_openDate.setDate(null);
}
}catch (IOException | NumberFormatException e) {
}
}
I have the //comment lines explaining what I would like to do, but I do not know which option to select to get the "string" values from the text file to populate the comboboxes and the jxdatepicker fields. I can only get the textfields to populate correctly. Any advice would be much appreciated.
This is what I have found to work:
jComboBox_client.setSelectedItem(delims[2]);
now I just need to find the right way to setDate of jxdatepicker back to date picked.

How to load text data into a table using Java

I have a text data like
name = abc
id = 123
Place = xyz
Details = some texts with two line
name = aaa
id = 54657
Place = dfd
Details = some texts with some lines
I need to place them in a table or csv and my output should look like
name id Place Details
abc 123 xyz Some texts
dfd 54657 dfd Some texts
How can I do this with java?
Code for the CSV version :) It reads the input file and create a CSV in the format you asked for:
try {
BufferedReader sc = new BufferedReader(new FileReader("input2.txt"));
ArrayList<String> name = new ArrayList<>();
ArrayList<String> id = new ArrayList<>();
ArrayList<String> place = new ArrayList<>();
ArrayList<String> details = new ArrayList<>();
String line = null;
while ((line = sc.readLine()) !=null) {
if (!line.trim().equals("")) {
System.out.println(line);
if (line.toLowerCase().contains("name")) {
name.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("id")) {
id.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("location")) {
place.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("details")) {
details.add(line.split("=")[1].trim());
}
}
}
PrintWriter pr = new PrintWriter(new File("out.csv"));
pr.println("name;id;Place;Details;");
for (int i = 0; i < name.size(); i++) {
pr.println(name.get(i) + ";" + id.get(i) + ";" + place.get(i) + ";" + details.get(i) + ";");
}
pr.close();
} catch (Exception e) {
e.printStackTrace();
}
Sample file content it processes:
name = abinhav
Location =Bangalore
Id =613636064725610496
Details = infoodnetwork: Q2 is up. You can still join the Megakitchens in India contest and grab some exciting vouchers. RT if you are enjoying…
name = Mathi
Location =Chennai
Id =613636066474508289
Details = i am the drifter Of course they can, but the BBC needs a daily negative story on India.
Reading from text file and writing to csv(comma seperated values) can be achieved using java io.
your logic should once write the headers to a text file with separator as comma and then read the corresponding values from the text may be use split("=") and append to the file with comma separator. You can create new files write the values and save the file with csv extension
try {
BufferedReader bReader = new BufferedReader(new FileReader("input file"));
String line = "";
while ((line = bReader.readLine()) != null) {
String[] strArray = line.split("=");
// write this to file
System.out.println( strArray[1]);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Parse the text file with a Scanner (doc here)
Create a DefaultTableModel (doc here). DefaultTableModel model = new DefaultTableModel(data, new String[]{"name","id","Place","Details"});, where data is a 2D String array with your data.
Create a JTable (doc here) with the model you just created. JTable table = new JTable(model);
Add the table to a JPanel, or JFrame, with a JScrollPane (if needed): panel.add(new JScrollPane(table));.

populate a 'JTable' with values from a text file [duplicate]

This question already has an answer here:
populate a 'JTable' with values from a '.txt' file
(1 answer)
Closed 7 years ago.
I have a text file like this
0786160384|P. K.|Tharindu|912921549v|Colombo|
0711495765|P. K.|Gamini|657414589v|Colombo|
0114756199|H. P.|Weerasigha|657895478v|Kandy|
each |separates a data. I want to display the data on this file in a jTable. below is my code so far.
public class PrintGUI extends javax.swing.JFrame {
File file, tempFile;
FileReader fileReader;
FileWriter fileWriter;
ArrayList ClientList;
Vector data = new Vector();
Vector columns = new Vector();
public PrintGUI() {
initComponents();
this.setIconImage(new ImageIcon(getClass().getResource("/Images/icon.png")).getImage());
file = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\phonebook.txt");
tempFile = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\tempphonebook.txt");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
PhoneBookTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Phone No", "First Name", "Last Name", "NIC", "City"
}
)
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
String line = null;
DefaultTableModel dtm = (DefaultTableModel) PhoneBookTable.getModel();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
StringTokenizer st1 = new StringTokenizer(br.readLine(), "|");
while (st1.hasMoreTokens()) {
columns.addElement(st1.nextToken());
}
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "|");
while (st2.hasMoreTokens()) {
data.addElement(st2.nextToken());
}
}
br.close();
dtm.addRow(new Object[]{columns, data});
} catch (Exception e) {
e.printStackTrace();
}
}
problem is when I run the program it shows a whole line on text from the .txt file instead of a single data per column.
more specifically it shows the whole line of
[0786160384, P. K., Tharindu, 912921549v, Colombo]
in the first row first column and
[0711495765, P. K., Gamini, 657414589v, Colombo, 0114756199, H. P., Weerasigha, 657895478v, Kandy]
in the first row second column
Instead I want it to display single data per cell. can some one please help?
You only call addRow once, so of course there will be only one row added to the table model.
You need to move that statement inside your file-reading loop.
Each line you read from the file corresponds to a row in your table. As such, you need to call addRow each time you have read a line, and call it with the contents of that line.
Finally found the error. It should be like
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
data = new Vector();// this is important
StringTokenizer st1 = new StringTokenizer(line, "|");
while (st1.hasMoreTokens()) {
String nextToken = st1.nextToken();
data.add(nextToken);
System.out.println(nextToken);
}
System.out.println(data);
dtm.addRow(data);//add here
System.out.println(".................................");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources