I need to some help about JTable.I'm trying to read data from "Contact.txt" file and populate my table with that datas.I can get data from file correctly with adding to Object[][] 2D array without any problem.When I try to add this Object array to table not happens any thing.
Sorry for my bad English.
Contacts.txt file include "Name","LastName","Phone Num","Email" s.
And this Class read the text and add it to Object :
public class ReadFromText {
public boolean ReadTable(Object [][] data) {
boolean status = false;
File file = new File("/Users/MacbookPro/Documents/Contacts.txt");
BufferedReader bf = null;
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
bf = new BufferedReader(fileReader);
String textLine = null;
String [] text = null;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 4; j++) {
while ((textLine = bf.readLine()) != null) {
text = textLine.split(" ");
data[i][j] = text[j];
status = true;
System.out.println(data[i][j]);
}
}
}
bf.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
return status;
}
}
This part of code from main Class :
Object [][]datas = new Object[10][4];
ReadFromText r = new ReadFromText(); //new object from ReadData class
if(r.ReadTable(datas)== true){
System.out.println("OK");//just for to be sure
}else{
System.out.println("NO");
}
model = new DefaultTableModel(datas, columNames);
table = new JTable(model);
table.setFont(new Font("Monospaced", Font.PLAIN, 13));
table.setBackground(new Color(245, 245, 245));
table.setRowHeight(25);
table.setMinimumSize(new Dimension(60, 20));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
It' return "OK" check it from here
But JTable is empty !!! : look it from this picture
I hope to anyone can help me.THANKS FOR ALL
Your code to read the data from the file is wrong. Think about it for a minute. You start the outer loop with a value of 0, then you have you inner loop with a value of 0 and then you read the entire file using the while loop.
You want your logic to read a single line of data, split that line and add then add the data to the array. So the logic should be something like:
int row = 0;
while ((String textLine = bf.readLine()) != null)
{
String text = textLine.split(" ");
for (int i = 0; i < text.length; i++)
{
data[row][i] = text[i];
}
row++
}
However, you should NOT be using Arrays to hold the data. You should never hardcode the size of a data structure since it does not allow you to add new data. Instead you should be using a Vector to read the data. Then it doesn't matter is you have 10 rows of data or 100.
Using this approach the code would be something like:
Vector data = new Vector();
while ((String textLine = bf.readLine()) != null)
{
String text = textLine.split(" ");
Vector row = new Vector();
for (int i = 0; i < text.length; i++)
{
row.addElement( text[i] );
}
}
So you would need to change the method to return the Vector of data. You would also need to change your "columnNames" to be added to a Vector so you can create the TableModel using the two Vectors.
I hope this answer will help you find the problem. It is also meant to demonstrate the importance of posting an MCVE, like the following:
mport java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestTable extends JFrame {
public TestTable() {
super("Main");
setSize(400, 300);
Object [][]datas = new Object[][]{
{"A1", "A2","A3","A4"},
{"B1", "B2","B3","B4"}
};
Object[] columNames = {"Name","LastName","Phone Num","Email"};
DefaultTableModel model = new DefaultTableModel(datas, columNames );
JTable table = new JTable(model);
table.setBackground(new Color(245, 245, 245));
table.setRowHeight(25);
table.setMinimumSize(new Dimension(60, 20));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
add(new JScrollPane(table));
setVisible(true);
}
public static void main(String[] args) {
new TestTable();
}
}
Not only an MCVE helps you get better and faster response, in many cases, like this one, it helps you pin point the problem and solve it by yourself.
Removing everything that is not essential to reproduce the problem, help you (and who ever tries to help) focus on where the problem is.
In this case you can see that eliminating the input part, you can see that the JTable works fine.
Related
I want to read a csv File and put words " Jakarta " and " Bandung " in a combobox. Here's the input
id,from,
1,Jakarta
2,Jakarta
5,Jakarta
6,Jakarta
10,Bandung
11,Bandung
12,Bandung
I managed to get the words and put it in the combobox, but as you can see, the text file itself contains a lot word " Jakarta " and " Bandung " while i want to show both only once in the combobox.
Here's my temporary code, which works for now but inefficient and probably can't be used if the word has more variety
public String location;
private void formWindowOpened(java.awt.event.WindowEvent evt) {
String csvFile = "C:\\Users\\USER\\Desktop\\Project Data.csv";
BufferedReader br = null;
LineNumberReader reader = null;
String line = "";
String cvsSplitBy = "-|\\,";
br = new BufferedReader(new FileReader(csvFile));
reader = new LineNumberReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bookingdata = line.split(cvsSplitBy);
location = bookingdata[1];
ComboBoxModel model = cmb1.getModel();
int size = model.getSize();
cmb1.addItem(location);
for(int i = 1; i < size; i++){
if(model.getElementAt(i).equals("from")){
cmb1.removeItemAt(i);
}
else if(model.getElementAt(i).equals("Bandung")){
cmb1.removeItemAt(i);
}
for(int j = 2; j < i; j++){
if(model.getElementAt(j).equals("Jakarta")){
cmb1.removeItemAt(j);
}
}
}
}
}
Someone else recommended this approach
boolean isEquals = false;
for(i = 0; i < a && !isEquals; i++){
isEquals = location.equals("Jakarta");
if(isEquals){
cmb1.addItem("Jakarta");
}
}
This code doesn't work. As the code doesn't stop once it adds a " Jakarta " but it stops after it completed a loop. thus it still creates duplicate within the combobox.
I would like to know if there's any other code i can try. Thank you
Try putting all the words in a Set first and then add it in the combobox. Set itself will take care of exact one occurrence of each word.
Something like this:
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bookingdata = line.split(cvsSplitBy);
location = bookingdata[1];
ComboBoxModel model = cmb1.getModel();
int size = model.getSize();
// add all location in set and set will only allow distinct values
locationSet.add(location);
}
// after looping through all location put it in combobox
for(String location:locationSet)cmb1.addItem(location);
}
}
As discussed in comments, Sets are meant to keep unique values. Please find the screenshot of JShell below:
PS: This is just to give an idea and may need some amendment as per requirement.
--EDITED--
As discussed, it seems you are still missing something, I tried and write below piece of code and worked fine
package com.digital.core;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Test {
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setSize(300, 300);
String data = "id,from,\n" +
"1,Jakarta\n" +
"2,Jakarta\n" +
"5,Jakarta\n" +
"6,Jakarta\n" +
"10,Bandung\n" +
"11,Bandung\n" +
"12,Bandung";
String[] dataArr = data.split("\n");
Set<String> locationSet = new HashSet<>();
for(String line:dataArr) {
locationSet.add(line.split(",")[1]);
}
JComboBox<String> comboBox = new JComboBox<>();
for(String location:locationSet)
comboBox.addItem(location);
jframe.add(comboBox);
jframe.setVisible(true);
}
}
You could create an ObservablArrayList of strings and as you read the CSV file, check if the list already contains that string:
ObservableList<String> locationsList = FXCollections.observableArrayList();
// Add your strings to the array as they're loaded, but check to
// make sure the string does not already exist
if (!locationsList.contains(location)) {
locationsList.add(location);
}
Then, after reading the whole file and populating the list, just set the items in your combobox to that ObservableArrayList.
I'm just a tad bit confused, I need to find the median and mode through this code through an array and I want to input it into a textfield since i'm using Jframes.
This is the code i'm using for the actual CSV document, it already reads the files from the CSV, but the mean and median bit is a bit confusing...
public void theSearch() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Joshua\\Desktop\\Data Set.csv")));
//BufferedReader br = new BufferedReader(new FileReader(new File("H:\\2nd Year\\Programming Group Project\\Data Set.csv")));
List<String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
setMinimumSize(new Dimension(640, 480));
String[] columnNames = new String[] {
"Reporting period", "Period of coverage", "Breakdown", "ONS code", "Level", "Level description", "Gender", "Indicator value", "CI lower", "CI upper", "Denominator", "Numerator"
};
Object[][] content = new Object[elements.size()][13];{
for(int i=1; i<elements.size(); i++) {
content[i][0] = elements.get(i)[0];
content[i][1] = elements.get(i)[1];
content[i][2] = elements.get(i)[2];
content[i][3] = elements.get(i)[3];
content[i][4] = elements.get(i)[4];
content[i][5] = elements.get(i)[5];
content[i][6] = elements.get(i)[6];
content[i][7] = elements.get(i)[7];
content[i][8] = elements.get(i)[8];
content[i][9] = elements.get(i)[9];
content[i][10] = elements.get(i)[10];
content[i][11] = elements.get(i)[11];
content[i][12] = elements.get(i)[12];
}
};
jTable.setModel(new DefaultTableModel(content,columnNames));
jScrollPane2.setMinimumSize(new Dimension(600, 23));
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
add(jScrollPane2);
//TableModel model = new DefaultTableModel (content, columnNames);
//JTable jTable = new JTable(model);
//jTable.setPreferredScrollableViewportSize(new Dimension(1200, 400));
// TableRowSorter<TableModel> sorted = new TableRowSorter <TableModel>(model);
// jTable.setRowSorter(sorted);
// jTable.setEnabled(false);
// JScrollPane pane = new JScrollPane(jTable);
System.out.println(jTable.getModel().getValueAt(1, 1));
} catch (Exception ex) {
ex.printStackTrace();
}
}
To calculate statistics such as mean and median you need to have numbers rather than strings. So the first thing you need to do is to convert the strings you are reading from the file into the appropriate data type. By far the best way to do this in Java is to create a class to represent objects in each row and then turn your rows into a collection of those objects.
I'm not sure what your rows represent so I'll just call the class Row here:
class Row {
private final int reportingPeriod;
private final int level;
...
public Row(String[] values) {
this.reportingPeriod = Integer.valueOf(values[0]);
this.level = Integer.valueOf(values[1]);
...
}
public int getLevel() {
return level;
}
}
List<Row> rows = new ArrayList<>();
while((line = br.readLine())!=null) {
rows.add(new Row(line.split(","));
}
Or in Java 8:
List<Row> rows = br.lines().map(l -> new Row(l.split(","))).collect(toList());
To find the median and mean:
int[] levels = new int[rows.size()];
int sum = 0;
for (int i = 0; i < rows.size(); i++) {
levels[i] = rows.get(i).getLevel();
sum += levels[i];
}
Arrays.sort(levels);
int median = levels[rows.size() / 2];
double mean = (double)sum / rows.size();
In Java 8 this would be:
int median = rows.stream().mapToInt(Row::getLevel).sorted().skip(rows.size() / 2).findFirst().get();
double mean = rows.stream().mapToInt(Row::getLevel).average().getAsDouble();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am still learning JAVA and have been trying to find a solution for my program for a few days, but I haven't gotten it fixed yet.
I have many text files (my program saves). The files look like this:
text (tab) number (tab) number (tab)...
text (tab) number (tab) number (tab)...
(tab) means that there is tabulation mark,
text means that is text (string),
number means that there is number (integer).
number of files can be from 1 up to 32 and file with names like: january1; january2; january3...
I need to read all of those files (ignore strings) and sum only numbers like so:
while ((line = br.readLine()) != null) {
counter=counter+1;
String[] info = line.split("\\s+");
for(int j = 2; j < 8; j++) {
int num = Integer.parseInt(info[j]);
data[j][counter]=data[j][counter]+num;
}
};
Simply I want sum all that "tables" to array of arrays (or to any similar kind of variable) and then display it as table. If someone knows any solution or can link any similar calculation, that would be awesome!
So, as I see it, you have four questions you need answered, this goes against the site etiquette of asking A question, but will give it a shot
How to list a series of files, presumably using some kind of filter
How to read a file and process the data in some meaningful way
How to manage the data in data structure
Show the data in a JTable.
Listing files
Probably the simplest way to list files is to use File#list and pass a FileFilter which meets your needs
File[] files = new File(".").listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().startsWith("janurary");
}
});
Now, I'd write a method which took a File object representing the directory you want to list and a FileFilter to use to search it...
public File[] listFiles(File dir, FileFilter filter) throws IOException {
if (dir.exists()) {
if (dir.isDirectory()) {
return dir.listFiles(filter);
} else {
throw new IOException(dir + " is not a valid directory");
}
} else {
throw new IOException(dir + " does not exist");
}
}
This way you could search for a number of different set of files based on different FileFilters.
Of course, you could also use the newer Paths/Files API to find files as well
Reading files...
Reading multiple files comes down to the same thing, reading a single file...
// BufferedReader has a nice readline method which makes
// it easier to read text with. You could use a Scanner
// but I prefer BufferedReader, but that's me...
try (BufferedReader br = new BufferedReader(new FileReader(new File("...")))) {
String line = null;
// Read each line
while ((line = br.readLine()) != null) {
// Split the line into individual parts, on the <tab> character
String parts[] = line.split("\t");
int sum = 0;
// Staring from the first number, sum the line...
for (int index = 1; index < parts.length; index++) {
sum += Integer.parseInt(parts[index].trim());
}
// Store the key/value pairs together some how
}
}
Now, we need some way to store the results of the calculations...
Have a look at Basic I/O for more details
Managing the data
Now, there are any number of ways you could do this, but since the amount of data is variable, you want a data structure that can grow dynamically.
My first thought would be to use a Map, but this assumes you want to combining rows with the same name, otherwise you should just us a List within a List, where the outer List represents the rows and the Inner list represents the column values...
Map<String, Integer> data = new HashMap<>(25);
File[] files = listFiles(someDir, januraryFilter);
for (File file : files {
readFile(file, data);
}
Where readFile is basically the code from before
protected void readData(File file, Map<String, Integer> data) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = null;
// Read each line
while ((line = br.readLine()) != null) {
//...
// Store the key/value pairs together some how
String name = parts[0];
if (data.containsKey(name)) {
int previous = data.get(name);
sum += previous;
}
data.put(name, sum);
}
}
}
Have a look at the Collections Trail for more details
Showing the data
And finally, we need to show the data. You could simply use a DefaultTableModel, but you already have the data in structure, why not re-use it with a custom TableModel
public class SummaryTableModel extends AbstractTableModel {
private Map<String, Integer> data;
private List<String> keyMap;
public SummaryTableModel(Map<String, Integer> data) {
this.data = new HashMap<>(data);
keyMap = new ArrayList<>(data.keySet());
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class type = Object.class;
switch (columnIndex) {
case 0:
type = String.class;
break;
case 1:
type = Integer.class;
break;
}
return type;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
switch (columnIndex) {
case 0:
value = keyMap.get(rowIndex);
break;
case 1:
String key = keyMap.get(rowIndex);
value = data.get(key);
break;
}
return value;
}
}
Then you would simply apply it to a JTable...
add(new JScrollPane(new JTable(new SummaryTableModel(data)));
Take a look at How to Use Tables for more details
Conclusion
There are a lot of assumptions that have to be made which are missing from the context of the question; does the order of the files matter? Do you care about duplicate entries?
So it becomes near impossible to provide a single "answer" which will solve all of your problems
I took all the january1 january2... files from the location and used your same function to calculate the value to be stored.
Then I created a table with two headers, Day and Number. Then just added rows according to the values generated.
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
String line;
model.addColumn("Day");
model.addColumn("Number");
BufferedReader br = null;
model.addRow(new Object[]{"a","b"});
for(int i = 1; i < 32; i++)
{
try {
String sCurrentLine;
String filename = "january"+i;
br = new BufferedReader(new FileReader("C:\\january"+i+".txt"));
int counter = 0;
while ((sCurrentLine = br.readLine()) != null) {
counter=counter+1;
String[] info = sCurrentLine.split("\\s+");
int sum = 0;
for(int j = 2; j < 8; j++) {
int num = Integer.parseInt(info[j]);
sum += num;
}
model.addRow(new Object[]{filename, sum+""});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
Use Labled Loop and Try-Catch. Below piece adds all number in a line.
You could get some hint from here:
String line = "text 1 2 3 4 del";
String splitLine[] = line.split("\t");
int sumLine = 0;
int i = 0;
contSum: for (; i < splitLine.length; i++) {
try {
sumLine += Integer.parseInt(splitLine[i]);
} catch (Exception e) {
continue contSum;
}
}
System.out.println(sumLine);
Here is another example using vectors . in this example directories will be searched for ".txt" files and added to the JTable.
The doIt method will take in the folder where your text files are located.
this will then with recursion, look for files in folders.
each file found will be split and added following you example file.
public class FileFolderReader
{
private Vector<Vector> rows = new Vector<Vector>();
public static void main(String[] args)
{
FileFolderReader fileFolderReader = new FileFolderReader();
fileFolderReader.doIt("D:\\folderoffiles");
}
private void doIt(String path)
{
System.out.println(findFile(new File(path)) + " in total");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("File Name");
columnNames.addElement("Size");
JTable table = new JTable(rows, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
private int findFile(File file)
{
int totalPerFile = 0;
int total = 0;
File[] list = file.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String fileName)
{
return fileName.endsWith(".txt");
}
});
if (list != null)
for (File textFile : list)
{
if (textFile.isDirectory())
{
total = findFile(textFile);
}
else
{
totalPerFile = scanFile(textFile);
System.out.println(totalPerFile + " in " + textFile.getName());
Vector<String> rowItem = new Vector<String>();
rowItem.addElement(textFile.getName());
rowItem.addElement(Integer.toString(totalPerFile));
rows.addElement(rowItem);
total = total + totalPerFile;
}
}
return total;
}
public int scanFile(File file)
{
int sum = 0;
Scanner scanner = null;
try
{
scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
String[] info = line.split("\\s+");
int count = 1;
for (String stingInt : info)
{
if (count != 1)
{
sum = sum + Integer.parseInt(stingInt);
}
count++;
}
}
scanner.close();
}
catch (FileNotFoundException e)
{
// you will need to handle this
// don't do this !
e.printStackTrace();
}
return sum;
}
}
I am making a GUI in which i have 6 combo boxes, i read data from a text file to these
combo boxes. My text file has 3 rows and 2 columns, so when i read data only my first 2 combo boxes is getting populated with data that to with the values of the 3rd row of the text file instead of the 1st row and the remaining combo boxes remains empty.As my text file contains 6 values it should display in the 6 combo boxes.Please help
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Read extends JPanel {
public Read() {
JPanel buttonPanel = new JPanel();
add(buttonPanel);
buttonPanel.setLayout(new GridLayout(0, 2, 5, 5));
JComboBox comboBox1 = new JComboBox();
comboBox1.addItem("1");
comboBox1.addItem("2");
comboBox1.addItem("4");
JComboBox comboBox2 = new JComboBox();
comboBox2.addItem("1");
comboBox2.addItem("2");
comboBox2.addItem("4");
JComboBox comboBox3 = new JComboBox();
comboBox3.addItem("1");
comboBox3.addItem("2");
comboBox3.addItem("4");
JComboBox comboBox4 = new JComboBox();
comboBox4.addItem("1");
comboBox4.addItem("2");
comboBox4.addItem("4");
JComboBox comboBox5 = new JComboBox();
comboBox5.addItem("1");
comboBox5.addItem("2");
comboBox5.addItem("4");
JComboBox comboBox6 = new JComboBox();
comboBox6.addItem("1");
comboBox6.addItem("2");
comboBox6.addItem("4");
buttonPanel.add(comboBox1);
buttonPanel.add(comboBox2);
buttonPanel.add(comboBox3);
buttonPanel.add(comboBox4);
buttonPanel.add(comboBox5);
buttonPanel.add(comboBox6);
try{
InputStream ips=new FileInputStream("tl.txt");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null) {
String[] s = line.split(" ");
comboBox1.setSelectedItem(s[0]);
comboBox2.setSelectedItem(s[1]);
}
br.close();
}
catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
Read a = new Read();
JFrame f = new JFrame("");
f.getContentPane().add(a);
f.setSize(300,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
text file
2 4
1 2
4 1
Declare a JCombobox array and store all your JCombobox in the array as below,
JComboBox[] comboBoxs = new JComboBox[6];
comboBoxs[0] = comboBox1;
comboBoxs[1] = comboBox2;
comboBoxs[2] = comboBox3;
comboBoxs[3] = comboBox4;
comboBoxs[4] = comboBox5;
comboBoxs[5] = comboBox6;
Declare a Arraylist and store the data which you read from the file as below,
// Other code goes here.
ArrayList<String> list = new ArrayList<String>();
String line;
while ((line=br.readLine())!=null) {
String[] s = line.split(" ");
list.add(s[0]);
list.add(s[1]);
}
br.close();
Finally loop over each Arraylist and populate the Combobox's.
for(int i = 0; i < comboBoxs.length; i++) {
comboBoxs[i].setSelectedItem(list.get(i));
}
This should do good.
Please look at your code, you are filling data only to combobox 1 and 2, other comboboxes you are not filling any data.
If you want data in other compoboxes, fill them as well in the while loop.
Hope this helps.
thanks
public class Read extends JPanel{
String[] values=new String[6];
JCombobox<String>[] combos=new JCombobox<String>[6];
public Read() {
//Do your layout initialization operations here
this.initCombo();
//Put the logic to add the comboboxes to the UI here
}
public void intiCombo(){
try{
ArrayList<String> tmp=new ArrayList<String>();
InputStream ips=new FileInputStream("tl.txt");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null) {
String[] s = line.split(" ");
tmp.add(s[0]);
tmp.add(s[1]);
}
br.close();
}
catch (Exception e){
e.printStackTrace();
}
values=tmp.toArray(new String[1]);
for(int i=0;i<conbos.length;i++)combos[i]=new JCombobox(values);
}
//Your main method comes here
}
I have a code that reads a multiple text files from a folder and I need to put them in a table.So far,everything is good except that every line from my text files are displayed in a different table.I know that the problem is that the table receives each line separately.I tried to create an object and fill it and then call inside the table but I couldn't make it work so if anyone can tell me the solution that would be great. Also I need to be able to compare the values and find an average,so if you have any tips for that to,would be great
here's an example of my text file
17/10/2012 10:00:06.67 [RX] - E usbR<LF>
817EE765FF53-53<LF>
817AA765FF53-34<LF>
817CC765FF53-25<LF>
00<LF>
E qEnd<LF>
and this is what I need to get in the table
ID RSSI
817EE765FF53 53
817AA765FF53 34
817CC765FF53 25
here is the code
import java.awt.BorderLayout;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Foldersearch1
{
public static void main(String[] args)
{
// Directory path here
String path = "C:/Users/Nikica/Desktop/text files";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
();
String currentLine="";
File textFile = new File(folder.getAbsolutePath() + File.separator + files);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textFile);
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String line;
//Read File Line By Line
// int p=0;
// Object[][] Table=null;
while ((strLine = br.readLine()) != null) {
processLine(strLine);
Table(strLine);
// Print the content on the console
//System.out.println (strLine);
}
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
}
public static void processLine(String line) {
// skip header & footer
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) {return;}
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
System.out.println("ID [" + ID + "]\t RSSI [" + RSSI +"]");
}
public static void Table(String line) {
JFrame frame = new JFrame("proba");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) return;
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
Object rowData[][] = { { ID, RSSI } };
Object columnNames[] = { "ID", "RSSI" };
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
To make your code work with minimal changes, Create a Vector with the rowdata, and use the constructor public JTable(Vector rowData, Vector columnNames). The following code snippet should give you an idea on how to do it.
Vector<String> columnNames = new Vector<String>();
columnNames.add("ID");
columnNames.add("RSSI");
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
for(int i=0; i<20; i++) {
Vector<String> row = new Vector<String>();
row.add("ID_" + i);
row.add("RSSI_" + i);
rowData.add(row);
}
JTable table = new JTable(rowData, columnNames);