Populating a JTable with parsed information - java

I am trying to populate a JTable with information taken from a website (namely price and item name). I have a class that asks the user to input a URL and scans the page for the price and item name as well as the URL. Currently it takes all the parsed information and stores it in three different text files, one for price, one for item name, and one for the URL. I am trying to populate a JTable containing three columns (item name, price, and URL) with this information but every time I scan a new page the text files are overwritten and the previous information is lost. I don't necessarily need the JTable to be populated via the text file, I just need it to somehow get the information. Here is some of my code.
public BestBuy (JFrame frame){
super (frame, "Best Buy URL", true);
setLayout (new FlowLayout());
label = new JLabel ("Enter Best Buy URL");
add (label);
url = new JTextField ("Enter URL Here", 40);
add (url);
submit = new JButton ("Submit");
add (submit);
event b = new event ();
submit.addActionListener (b);
}
public class event implements ActionListener{
public void actionPerformed (ActionEvent b){
try {
String datab = url.getText(); //perform your operation
datab = datab.trim();
datab = datab.toLowerCase();
Document document = Jsoup.connect(datab).get();
String amountb = document.select(".amount").first().text();
String nameb = document.select(".product-title").first().text();
FileWriter stream = new FileWriter ("C:\\Users\\Daniel\\Desktop\\price.txt");
BufferedWriter out = new BufferedWriter (stream);
out.write(amountb + "\n");
out.newLine();
out.close();
FileWriter stream1 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\itemName.txt");
BufferedWriter out1 = new BufferedWriter (stream1);
out1.write(nameb + "\n");
out1.newLine();
out1.close();
FileWriter stream2 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\url.txt");
BufferedWriter out2 = new BufferedWriter (stream2);
out2.write(datab + "\n");
out2.newLine();
out2.close();
}
catch (Exception ex) {
}
setVisible (false);
}
This class asks the user for a Best Buy URL and parses the given page for item name, and price then writes it to files on my desktop.
public FirstGui (){
setLayout (new FlowLayout ());
String[] columnName = {"Item Name", "Price", "URL"};
Object [] [] data = {
};
table = new JTable (data, columnName);
table.setPreferredScrollableViewportSize(new Dimension (500, 300));
table.setFillsViewportHeight (true);
JScrollPane scrollpane = new JScrollPane (table);
add (scrollpane);
Now I am trying to get that parsed information onto my JTable but I have no idea how to do so. I tried to do
public getdatab() {
return datab;
}
public getnameb() {
return nameb;
}
public getamountb() {
return amountb;
}
but all these strings are within a void so that did not work. As you can probably see I am quite new to java and this might have an obvious solution but I have been stuck on this for a few days and cant figure it out. Thank you.

I'm not sure exactly how your getting your data, but you want to do something like this. Since you're trying to write the data to three different files, I will assume the data is coming in from three different streams. Here's the thing though. For this to work, all the data needs to be in parallel, Meaning that the first item, should correspond to the first price and first url, and so on. If this is the case, you can do something like this.
Have three separate lists.
List<String> names = new ArrayList<String>();
List<String> prices = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
Then for each item you were going to add to a file, add to the list instead.
Use a DefaultTableModel as the model of your JTable
String[] columnName = {"Item Name", "Price", "URL"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
Now you can just add rows, using the data from the lists. Use the method model.addRow(row), where row is an array of Objects
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
String price = prices.get(i);
String url = urls.get(i);
model.addRow(new Object[] { name, price, url });
}
That's all there is to it. The model will update the table for you dynamically. But remember, like I said, the data in the lists must be in sync with one another for you to get the desired result.
If you're getting data in one row at a time, instead of one column at a time, that makes it even easier. For each set of data, that comes in, just add it as a row like it did in step 5.

Related

Java GUI import textfile data to a JTable

I am writing a program, for my assignment, which should get some user input data from GUI(jtextfield) to a textfile and then retrive those data from the textfile to another GUI(JTable).
I have some basic knowledge about the file handling and JAVA swing, and I get some problems now.
First of all, please let me tell what I have done now (code below).
appending the data
public void actionPerformed(ActionEvent ae) {
//once clicked the button write the file
Object[] cols = new Object[]{
model.getText(),
make.getText(),
year.getText()
};
try {
FileOutputStream fstream = new FileOutputStream("words.txt", true);
ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
outputFile.writeObject(cols);
//bw.close();
outputFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Reading the data from the word file to Jtable
public class read extends JFrame {
JTable table = new JTable();
JScrollPane pane;
Object[] cols = null;
public read() throws ClassNotFoundException, IOException {
cols = new String[]{"c1", "c2", "c3",};
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setColumnIdentifiers(cols);
File f = new File("words.txt");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Object[] data = (Object[]) ois.readObject();
model.addRow(data);
pane = new JScrollPane(table);
pane.setBounds(100, 150, 300, 300);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
setSize(500, 500);
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
new read();
}
}
It's working now but it only retrive one piece of data from the file, I want it to show all the data added to the file.
My questions are:
My words file looks like different:
and I am not sure if it just me or it just what it should be? Because I am expecting that it should be exact what I write, so even the addrow(object) method is not working I can add row using getline.
(Important) Because I write multible different data to the words file(and its shown in the image above), but it only shows one.
I assume that is because I should add an array of objects to the table in read.java instead of just addrow(object) but i dont know how, I mean I dont know how to let the array recognise that there are a lot of objects in the words file. also, is it okay to write the data as object to the file and retrive them in the read.java, is it a proper way?
Can someone tell me how, thanks fore your help.
Please don't hesitate to ask if I didn't state it properly.

Selecting a file, reading through it, and appending its content to 2 linked lists

I'm currently writing a program that should read through a file, go through the file line-by-line, use StringTokenizer to separate the Make (String), Model (String), Year (Integer), and Mileage (Integer), store those values in a Car object (Car(Make, Model, Year, Mileage), in that order), which will then be added as a node to 2 linked lists (one of which sorts by Make and the other doesn't). I successfully did all this and it worked just fine, however, I am now tasked to implement event-driven programming into my existing program (actionListener, JMenuItem, JMenuBar, JMenu, etc.). Before I'd just declare a String object called "file" and set that equal to the file which we're supposed to read from (cars.txt) in the main class, but now I have to add a file menu to the CarGUI to open the file reading. It currently runs but it doesn't display anything in the GUI. One change that I did was make my readFile method accept Files as arguments instead of Strings so that it could be compatible with what's in the FileMenuHandler class.
CarGUI class
This is the class where the JFrame is created and the readFile method exists. This is where the linked lists (SortedCarList and UnSortedCarList) are appended onto the JTextAreas.
public class CarGUI extends JFrame { //CarGUI inherits all the features of JFrame
private JTextArea leftTextArea; //make 2 JTextAreas for the Jframe
private JTextArea rightTextArea;
private StringBuilder leftSide; //make 2 StringBuilders which we'll later use to append the 2 ArrayLists onto
private StringBuilder rightSide;
//Instantiate the two child linked lists we created
static SortedCarList sortedList = new SortedCarList();
static UnsortedCarList unSortedList = new UnsortedCarList();
public CarGUI() //default constructor for the GUI class
{
// Instance variables
this( Project 3 );
}
public CarGUI(String title) //the 1-argument parameter constructor
{
// Call the super class constructor to initialize the super
// class variables before initializing this class's variables
super(title); //Inherited the title from the previous constructor
// Configure the JFrame
// Configure the JFrame components we inherited
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500); //setting the size to an arbitrary width and height
this.setLocation(200, 200);
this.getContentPane().setLayout(new GridLayout(1, 2)); //1 row and 2 columns, where the 2 lists' toStrings can be appended onto
this.getContentPane().setBackground(Color.ORANGE);
this.leftSide = new StringBuilder("Unsorted Cars" + "\n"); //just titling the 2 columns on the JFrame
this.rightSide = new StringBuilder("Sorted Cars" + "\n");
this.leftTextArea = new JTextArea(this.leftSide.toString());
this.rightTextArea = new JTextArea(this.rightSide.toString());
this.getContentPane().add(this.leftTextArea); //add the currently empty TextAreas to the content panes (the left and right ones)
this.getContentPane().add(this.rightTextArea);
//create menu buttons and menu bar
JMenuItem open = new JMenuItem("Open");
JMenuItem quit = new JMenuItem("Quit");
JMenuItem msg = new JMenuItem("Msg");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
FileMenuHandler fmh = new FileMenuHandler(this);
// Add the action listener to the menu items
open.addActionListener(fmh);
quit.addActionListener(fmh);
msg.addActionListener(fmh);
// Add the menu items to the file menu
fileMenu.add(open);
fileMenu.addSeparator();
fileMenu.add(quit);
fileMenu.addSeparator();
fileMenu.add(msg);
// Add file menu to the menu bar, and set this gui's
// menu bar to the menuBar we created above
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
this.setVisible(true); //without this, the GUI wouldn't even show up
}
//Method that will read from a file, sieve through the lines via the StringTokenizer
//Create Car objects after each line and add them to 2 Linked Lists as CarNodes
//Move on to the next line and keeps going until there are no more tokens to be found in the file
//Then it'll append the lists onto StringBuilders which will then be placed into the textAreas
public void readFile(File file) throws FileNotFoundException{
Scanner scanner = new Scanner(file.getName()); //scanner will now read through the file, whatever it is
String line = scanner.nextLine(); //'line' is assigned to the first line of the file
String delimiter = ",";
StringTokenizer tokenizer = new StringTokenizer(line, delimiter); //tokenizer will go through the line and separate by ","
int tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens and makes tokenCount equal to amount of tokens
while(tokenizer.hasMoreTokens()){ //keeps iterating until there are no more tokens to be found.
//if there aren't exactly 4 tokens, print it to the console
if(tokenCount == 1){ //in the case there's only one text token that can be found
String CarMakeUNO = tokenizer.nextToken();
System.out.println(CarMakeUNO + "\n"); //print to console
}
if(tokenCount == 2){ //in the case there are two tokens that were found in the current line
String CarMakeDOS = tokenizer.nextToken();
String CarModelDOS = tokenizer.nextToken();
System.out.println(CarMakeDOS + ", " + CarModelDOS + "\n"); //print to console
}
else if(tokenCount == 3){ //in the case there are three tokens that were found, doing this just in case another .txt file is used
String CarMakeTRES = tokenizer.nextToken();
String CarModelTRES = tokenizer.nextToken();
int CarYearTRES = Integer.parseInt(tokenizer.nextToken());
System.out.println(CarMakeTRES + " " + CarModelTRES + " " + CarYearTRES + "\n"); //print to console
}
//finally, if there are 4 tokens in the current line, use tokenizer to extract the Make, Model, Year, and Mileage and put them into a new Car Object
else if (tokenCount == 4){ //since the Make, Model, Year, and Mileage are in fixed order, we can just do it by each subsequent token:
String CarMake = tokenizer.nextToken();
String CarModel = tokenizer.nextToken();
int CarYear = Integer.parseInt(tokenizer.nextToken()); //since years are integers, we need to parse it with parseInt
int CarMileage = Integer.parseInt(tokenizer.nextToken());
//make a new object with the above values
//newCar(Make, Model, Year, Mileage);
Car newCar = new Car(CarMake, CarModel, CarYear, CarMileage); //put the appropriate variables in the newly instantiated Car object
unSortedList.addIt(newCar); //place the Car object into the linked list as a node
sortedList.insert(newCar);
}//goes through a single line of the file
if(scanner.hasNextLine()){ //if there are more lines in the file
line = scanner.nextLine(); //assigns string line to the next line of the file/goes to the next line
tokenizer = new StringTokenizer(line, delimiter); //StringTokenizer tokenizes the current line
tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens of the new line
}
}//end of while loop (stops when no more tokens)
scanner.close(); //close the scanner since it's not necessary anymore
leftSide.append(unSortedList.toString()); //adds the LinkedLists to their respective StringBuilder
rightSide.append(sortedList.toString()); //Utilizes the overrided toString in CarList
//adds the 2 StringBuilders to the 2 JTextAreas
this.leftTextArea.setText(this.leftSide.toString());
this.rightTextArea.setText(this.rightSide.toString());
}
}// end of CarGUI
This is my FileMenuHandler class, which handles the actionListener (makes the JMenuItems behave like we want). It calls the readFile method from the CarGUI class which the selected file (fc.getSelectedFile) is the argument of.
public class FileMenuHandler implements ActionListener
{
//this code is fine
// Save the reference to the GUI object this FileMenuHandler is
// associated with
private CarGUI gui;
// Constructor that takes as its parameter the GUI associated
// with this FileMenuHandler
public FileMenuHandler(CarGUI gui)
{
this.gui = gui;
}
public void actionPerformed(ActionEvent event)
{
// Get the command name from the event
String menuName = event.getActionCommand();
if (menuName.equals("Open")) //if Open is selected
{
// Create the object that will choose the file
JFileChooser fc = new JFileChooser();
// Attempt to open the file
int returnVal = fc.showOpenDialog(null);
// If user selected a file, create File object and pass it to
// the gui's readFile method
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
try {
this.gui.readFile(file); //calls readFile method in CarGUI class
} catch (FileNotFoundException e) {
System.out.println(" There is no file");
e.printStackTrace();
}
}
else if (returnVal == JFileChooser.CANCEL_OPTION)
{
System.out.println("Open command cancelled by user.");
}
}
else if (menuName.equals("Quit")) //if Quit is selected
{
System.exit(1); //end the program
}
else if (menuName.equals("Msg")) //if Msg is selected
{
JOptionPane.showMessageDialog(null, "You clicked on \'Msg\'"); //display this message
}
}
}
This is my main class
public class Project3 {
public static void main(String arg[]) throws FileNotFoundException{ //main method that enables us to even run this class
CarGUI testGUI = new CarGUI(); //create a new CarGUI object
}
}
I tried to annotate it as much as I could. It returns 2 nulls in the place where the linked lists are supposed to be displayed.
Okay. I solved the problem. It wasn't reading because I put .getName in file in my readFile method... hahahaha. It's working just fine now!

Auto Refresh in Swing (Jtable)

I wrote a code which is get text from text area and save to file after that get data from file and show at jtable but I want to do that automatically when I add a new text to file it should be automatically show at the jtable does any one can help me?
try {
BufferedReader br = new BufferedReader(new FileReader(new File ("Member.txt")));
Object [] row = {id, firstname, lastname, age};
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
Object[] tableLines = br.lines().toArray();
for(int i = 0; i < tableLines.length; i++)
{
String line = tableLines[i].toString().trim();
String[] dataRow = line.split(" ");
dtm.addRow(dataRow);
}
} catch (Exception ex) {
System.out.println(ex);
}
this code help me to show data from file at jtable.
Your starting point is: using a watch service to determine when that file changed on disk.
Then you have to read the whole file and figure what changed (for example by keeping a "copy" of all lines of the file in memory).
Then you extract the newly added lines and add them to your table model.

Conversion of String to JComboBox

How do I convert string to JComboBox object model ?
Note: Im using NetBeans IDE 8.0.2
to change JComboBox from <String> to <Object>
right click on JComboBox and select properties
select code tab
click on ... button from type parameters
replace <String> to <Object> and click ok.
You don't convert a String to a ComboBoxModel. You add the String to the combo box or the ComboBoxModel.
For example:
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.add( "One" );
comboBox.add( "Two" );
comboBox.add( "Three" );
Read the section from the Swing tutorial on How to Use Combo Boxes for more information and other examples.
You can also search the forum or web for other examples.
I solved the problem.
I needed to be able to grab each line independent of the other so I can use just one Text file but break it out to different j combo boxes. Below was what I did. Is there a shorter way of doing this? I will have 20 JComboBox with each having around 7 select entries. The entries for the drop down boxes are around 50 lines of selections.
public void inputFile() throws IOException{
//File reader method
FileReader file = new FileReader("c:\\jcboEntries.dat");
try (BufferedReader br = new BufferedReader(file)) {
String[] lines = new String [6];
String [] jcbo = new String [6];
try {
int i =0;
lines[0] = br.readLine();
jcbo[0] = lines[0];
jcbo0 = jcbo[0];
jcboNUMONE.addItem(jcbo0);
System.out.println(jcbo0);
lines[1] = br.readLine();
jcbo[1] = lines[1];
jcbo1 = jcbo[1];
jcboNUMONE.addItem(jcbo1);
System.out.println(jcbo1);
lines[2] = br.readLine();
jcbo[2] = lines[2];
jcbo2 = jcbo[2];
jcboNUMONE.addItem(jcbo2);
System.out.println(jcbo2);
lines[3] = br.readLine();
jcbo[3] = lines[3];
jcbo3 = jcbo[3];
jcboNUMONE.addItem(jcbo3);
System.out.println(jcbo3);
lines[4] = br.readLine();
jcbo[4] = lines[4];
jcbo4 = jcbo[4];
jcboNUMONE.addItem(jcbo4);
System.out.println(jcbo4);
lines[5] = br.readLine();
jcbo[5] = lines[5];
jcbo5 = jcbo[5];
jcboNUMONE.addItem(jcbo5);
System.out.println(jcbo5);
} catch (IOException e){}
} catch (IOException e){}
}

How do i set text in rows of a JTable? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm trying to make a program in java JFrame with a table.
I want to save my text from the rows.
I put the text in a text file and that is working.
But i want to get my text from my text file into my table.
I have tried a lot of things but nothing is working.
can somebody help pls?
'Hypothetically' if you stored the text in your file line by line, for example like this:
tester.txt:
Star Wars
Star Trek
The Lord of The Rings
Then you could read it in line by line and when you have read enough lines add a row to the table. In order to add a row to an existing table I believe you do need to use the Model, or if creating from fresh prepare the data beforehand and then create. Below is a rough example using the above txt file:
public class SO {
public static void main(String[] args) {
//Desktop
Path path = Paths.get(System.getProperty("user.home"), "Desktop", "tester.txt");
//Reader
try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
Vector<String> row = new Vector<String>();
//Add lines of file
int numOfCellsInRow = 3; //Num of cells we want
int count = 0;
while (count < numOfCellsInRow){
row.addElement(reader.readLine());
count++;
}
//Column names
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Column One");
columnNames.addElement("Column Two");
columnNames.addElement("Column Three");
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
rowData.addElement(row);
//Make table
JTable table = new JTable(rowData, columnNames);
//How you could add another row by drawing more text from the file,
//here I have just used Strings
//Source: http://stackoverflow.com/questions/3549206/how-to-add-row-in-jtable
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Darth Vader", "Khan", "Sauron"});
//Make JFrame and add table to it, then display JFrame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Two things to note, firstly I have used Vectors, but these are discouraged due I believe to speed issues so you may want to look into varying on these. The second and main issue is the text in the file. Only by knowing how you intend to store the text can we know how to read it back successfully into the table. Hopefully though this example can point you in the right direction.
EDIT
Regarding your re-posted code, firstly I made this final:
final Path path = Paths.get(System.getProperty("user.home"), "Desktop", "File.txt");
Then altered your listener method to take the text input based of the file you make by clicking the save button:
btnGetFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//This prevents exception
if(!Files.exists(path)){//If no file
JOptionPane.showMessageDialog(null, "File does not exist!");//MSg
return;//End method
}
/*changed this bit so that it reads the data and
* should then add the rows
*/
try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
String line;
while((line = reader.readLine()) != null){//Chek for data, reafLine gets first line
Vector<String> row = new Vector<String>();//New Row
row.addElement(line);//Add first line
int numOfCellsInRow = 3; //Num of cells we want
int count = 0;
//We only want 2 because we got the first element at loop start
while (count < (numOfCellsInRow - 1)){
row.addElement(reader.readLine());
count++;
}
model.addRow(row);//Add rows from file
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
Added comments to try and explain what is going on.
It worked for my by adding the rows from the file to the JTable. Hopefully it works for you now also!

Categories