cannot fetch correct data from URL into JTable

I keep fetching the same single data instead of the second.

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 1547 Views - Last Post: 25 July 2010 - 06:11 PM Rate Topic: -----

#1 Guest_Xiangsheng*


Reputation:

cannot fetch correct data from URL into JTable

Posted 20 July 2010 - 10:53 PM

I have a text file with input like this "YAHOO,YHOO"<next line>"APPLE,AAPL" and these are under my drop down box. When I click on the second data which is the APPLE, they keep showing me YAHOO data in the JTable. I've tried very long to figure this, hope I can lend some help...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class stockTicker extends JFrame {

	JTabbedPane tabPanel;
	JPanel panel1;
	JPanel panel2;
	JPanel panel3;
	
	//Threading
	//counter count = new counter();
	//boolean run1;
	//Thread counterThread = null;
	tableModel dTable = new tableModel();
	JComboBox dbBox = new JComboBox();

    
	

	//stockTable.getTableHeader();
    

    
    public stockTicker() {
    	setTitle("Stock Ticker");
    	setSize(500,300);
    	setBackground(Color.white);
    	
    	JPanel topPanel = new JPanel();
    	topPanel.setLayout(new BorderLayout());
    	getContentPane().add(topPanel);
    	
    	//setting dbBox size and make it editable
    	dbBox.setBounds(20, 20, 200, 20);
    	dbBox.setEditable(true);
    	
    	//creating the tab pages
    	createPage1();
    	createPage2();
    	
    	tabPanel = new JTabbedPane();
    	//create tabbed panels
    	tabPanel.addTab("Stocks", panel1);
    	tabPanel.addTab("Search", panel2);
    	
    	topPanel.add( tabPanel, BorderLayout.CENTER);
    	
    	String line = null;
    	try
    {
      FileInputStream fis = new FileInputStream(("C:/Users/82115/stock.txt"));
      InputStreamReader isr = new InputStreamReader(fis);
      BufferedReader input = new BufferedReader(isr);
      while  ((line = input.readLine()) != null){
              String[] StockInfo = line.split(",");  
              stock myStock = new stock(StockInfo[0],StockInfo[1]);
              dbBox.addItem(myStock);
      }       
    }
    	catch(FileNotFoundException FNF){}
    	catch(IOException E)
    	{
    	}
    }
    	
    	public void createPage1()
 {	
    		panel1 = new JPanel();
    		
    		panel1.add(dTable.getScrollpane());
 }
    	
    	public void createPage2()
 {
    		panel2 = new JPanel();
    		panel2.setLayout(new BorderLayout());
    		
    		panel3 = new JPanel();
    		panel3.add(dbBox);
    		panel2.add(panel3);
    		
    		
    		//Drop down box - Adding listener to react to action
    		 dbBox.addActionListener(new ActionListener() {
    	         public void actionPerformed(ActionEvent e) {
    	         	String line = null;
    	                 try {                                                  
    	                	 String input1 =((stock)dbBox.getSelectedItem()).symbol;
    	                 	 URL url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s="+input1+"&f=sl1d1t1c1ohgv&e=.csv");
    	                     URLConnection connection = url.openConnection();
    	         	         connection.setDoInput(true);
    	         	         InputStream inStream = connection.getInputStream();
    	         	         BufferedReader input = new BufferedReader(new InputStreamReader(inStream));
    	         	            while ((line = input.readLine()) != null){
    	         	            	String[] yahooStockInfo = line.split(",");  
    	         	            	dTable.getModel().addRow(new Object[] {yahooStockInfo[0],yahooStockInfo[1], yahooStockInfo[4],yahooStockInfo[8]});
    	         					//lastPriceOP.setText(yahooStockInfo[1]);
    	         					//changeOP.setText(yahooStockInfo[4]);
    	         					//volumeOP.setText(yahooStockInfo[8]);         	
    	                         }
    	     				} catch (IOException ex) {
    	     					ex.printStackTrace();
    	     				}
    	     			}
    	     		});
    }
    	
    	//dbBox.addKeyListener(new KeyListener) {
    	
    	/*class counter implements Runnable {
    		 boolean run1;
    					
    		 public void run(){
    			 run1 = true;
    				
    				int x = 0; 
    				 try {
    						while (run1){
    							x++;
    							Thread.sleep(2000);		
    				    		
    						}		 					 
    				 }
    						 catch (InterruptedException e) {
    						 }
    				}
    		}*/
    	
public static void main( String args[] ){
    		stockTicker st = new stockTicker();
    		st.setVisible(true);
    	}
}




Is This A Good Question/Topic? 0

Replies To: cannot fetch correct data from URL into JTable

#2 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: cannot fetch correct data from URL into JTable

Posted 20 July 2010 - 11:04 PM

Would you mind providing the tableModel and stock classes, as I cannot run the program without them?

Have you tried printing out what input1 is, to verify that the correct symbols are being obtained?

This post has been edited by bcranger: 20 July 2010 - 11:18 PM

Was This Post Helpful? 0
  • +
  • -

#3 Guest_XiangSheng*


Reputation:

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 12:22 AM

This is my tableModel.java

 

import java.util.Vector;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class tableModel {

//For JTable
	
	String[] columnNames = {"Symbols","Last Price","Change","Volume"};
	Vector<Object> rowData = new Vector<Object>();
    
	DefaultTableModel model = new DefaultTableModel(null, columnNames);
	final JTable stockTable = new JTable(model);
	JScrollPane scrollpane = new JScrollPane(stockTable);
	public String[] getColumnNames() {
		return columnNames;
	}
	public void setColumnNames(String[] columnNames) {
		this.columnNames = columnNames;
	}
	public DefaultTableModel getModel() {
		return model;
	}
	public void setModel(DefaultTableModel model) {
		this.model = model;
	}
	public JScrollPane getScrollpane() {
		return scrollpane;
	}
	public void setScrollpane(JScrollPane scrollpane) {
		this.scrollpane = scrollpane;
	}
	public JTable getStockTable() {
		return stockTable;
	}
	public Vector<Object> getRowData() {
		
		return rowData;
	}
	public JTable getTable() {	
	
		return stockTable; 
	}

	
}



And this is my stock.java

import java.util.ArrayList;


public class stock {

    ArrayList<Object> Stock = new ArrayList<Object>();
    String name, symbol;
    
    public stock(String n1, String s1) {
        name = n1;
        symbol = s1;
    }
    public String toString() {
       return name;
    }	
}



sorry about it..
Was This Post Helpful? 0

#4 Guest_XiangSheng*


Reputation:

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 12:25 AM

Ya the input1 is the correct one, but the result keep giving me only Yahoo data and not the next stock name/symbols..
Was This Post Helpful? 0

#5 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 12:53 AM

Erm when I ran it, the JTable initially showed Yahoo info, then when I changed to Apple, it showed Yahoo and Apple in JTable...
Was This Post Helpful? 0
  • +
  • -

#6 Guest_XiangSheng*


Reputation:

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 12:58 AM

Yes, there's wad happen, but how come you are able to see Apple and yahoo's stock data in JTable ? Do you mean you see it on the console or on the JTable?

Here is what I got:

http://yfrog.com/1syahoofp
Was This Post Helpful? 0

#7 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 01:02 AM

I got it in the JTable, nothing in console.

Apple has the correct data in JTable too.

Maybe your text file is wrong?

I used code you pasted on this thread, with a text file I made mimicing yours. This is all it has in it:

YAHOO,YHOO
APPLE,AAPL

Here is image:

Posted Image

This post has been edited by bcranger: 21 July 2010 - 01:04 AM

Was This Post Helpful? 0
  • +
  • -

#8 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2555
  • View blog
  • Posts: 10,655
  • Joined: 20-September 08

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 01:15 AM

Quote

dTable.getModel().addRow(new Object[] 


You are adding to the TableModel - you should be replacing it/adding to a new model. See http://technojeeves....v-to-tablemodel for a convenient way to turn csv into a TableModel

That's assuming you want to show a new stock on its own on each click

Otherwise, as bcranger say, it works

This post has been edited by g00se: 21 July 2010 - 01:28 AM

Was This Post Helpful? 0
  • +
  • -

#9 Guest_XiangSheng*


Reputation:

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 04:45 AM

sorry. i pasted the wrong info. i will repost the code which is the error i facing as below

 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.table.DefaultTableModel;



public class final1 extends 	JFrame
{
	JTabbedPane tabbedPane;
	JPanel		panel1;
	JPanel		panel2;
	JPanel		panel3;
	JComboBox ipList = new JComboBox();
	TableModel one = new TableModel();
	DefaultTableModel two = one.getModel();
	
	
	public final1()
	{
		 one.getTable().setPreferredScrollableViewportSize(new Dimension(500, 100));
		setTitle( "Java Stock Ticker" );
		setSize( 500, 300 );
		setBackground( Color.gray );

		JPanel topPanel = new JPanel();
		topPanel.setLayout( new BorderLayout() );
		getContentPane().add( topPanel );

		// Create the tab pages
		createPage1();
		createPage2();


		// Create a tabbed pane
		tabbedPane = new JTabbedPane();
		tabbedPane.addTab( "Stock", panel1 );
		tabbedPane.addTab( "Search", panel2 );
		
		topPanel.add( tabbedPane, BorderLayout.CENTER );
		
		//store stocks to combobox
	    String line = null;
	  try
	{
	  FileInputStream fis = new FileInputStream(
	                  ("C:/fyp/Stock.txt"));
	  InputStreamReader isr = new InputStreamReader(fis);
	  BufferedReader input = new BufferedReader(isr);
	  while ((line = input.readLine()) != null){
	          String[] StockInfo = line.split(",");  
	          Stock myitem = new Stock(StockInfo[0],StockInfo[1]);
	          ipList.addItem(myitem);
	          ipList.setEditable(true); 
	          
	  }
	
	}
	  catch(FileNotFoundException FNF){
	  }
	  catch(IOException E)
	  {	  
	  }	  
	  }
	  
	public void createPage1()
	{
		
		panel1 = new JPanel();
		panel1.setLayout(new GridLayout(1,0) );
		panel1.add(one.getScroll());
		
		
		
		/*  ipList.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() != 38 && e.getKeyCode() != 40 && e.getKeyCode() != 10) {
            String a = ipList.getEditor().getItem().toString();
            ipList.removeAllItems();
            int st = 0;
        
            for (int i = 0; i < Stock.al.size(); i++) {
                if (Stock.al.get(i).startsWith(a)) { ipList.addItem(Stock.al.get(i)); st++; }
            }
            ipList.getEditor().setItem(new String(a));
            ipList.hidePopup();
            if (st != 0) {ipList.showPopup(); }
        }
    } } );*/
		
	}

	public void createPage2()
	{
		panel2 = new JPanel();
		panel2.add(ipList);
	

	ipList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        	String line = null;
        	Vector<Object> rowData1 = one.getRowData() ;
        	
                try {                   
                	
                	String input1 = ((Stock) ipList.getSelectedItem()).symbol;
                	String input2 = ((Stock) ipList.getSelectedItem()).name;
                        URL url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s="+input1+"&f=sl1d1t1c1ohgv&e=.csv");
                        URLConnection connection = url.openConnection();
        	            connection.setDoInput(true);
        	            InputStream inStream = connection.getInputStream();
        	            BufferedReader input =
        	            new BufferedReader(new InputStreamReader(inStream));
        	            while ((line = input.readLine()) != null){
        	            	String[] yahooStockInfo = line.split(",");    	
        	            	//one.getModel().addRow(new Object[]{input2, yahooStockInfo[1], yahooStockInfo[4], yahooStockInfo[8]});
        	        
        	            		rowData1.add(input2);
        	           	rowData1.add(yahooStockInfo[1]);
        	           rowData1.add(yahooStockInfo[4]);
        	          rowData1.add(yahooStockInfo[8]);
        	         
        	        
        	           
        	            	two.addRow(rowData1);
        	            	
        	            	
        	            break;
                        }
        	     
    				} catch (IOException ex) {
    					ex.printStackTrace();

    				}
    			}
    		});                 
}
	/*class counter implements Runnable {
		 boolean run1;
					
		 public void run(){
			 run1 = true;
				
				int x = 0; 
				
				
				 try {
						while (run1){
						x++;
							Thread.sleep(1000);		
							if( x ==10){
							final1 f1 = new final1();
								  f1.repaint();
								x = 0;
								  
								
							}
							System.out.println(x);
						}
						 					 
				 }
						 catch (InterruptedException e) {
						 }

		}
		}
*/

	// Main method to get things started
	public static void main( String args[] )
	{
		// Create an instance of the test application
		final1 mainFrame	= new final1();
		mainFrame.setVisible( true );
	}


TableModel

import java.util.Vector;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class TableModel {
	  String[] columnNames = {"Stock Name",
      		"Last Price",
      		"Change",
      		"Volume",};
	  Vector<Object> rowData = new Vector<Object>() ;
	   

	   DefaultTableModel model = new DefaultTableModel(null, columnNames);
	// final JTable table = new JTable(data, columnNames);
	   final JTable table = new JTable(model);
		JScrollPane Scroll = new JScrollPane(table);
		
      	
         
			public JScrollPane getScroll() {
			return Scroll;
		}
			
		public void setScroll(JScrollPane scroll) {
			Scroll = scroll;
		}
		public JTable getTable() {
			return table;
		}
			String[] getColumnNames() {
				return columnNames;
			}
			public void setColumnNames(String[] columnNames) {
				this.columnNames = columnNames;
			}
			
		
			public DefaultTableModel getModel() {
				return model;
			}
			public void setModel(DefaultTableModel model) {
				this.model = model;
			}

			public Vector<Object> getRowData() {
				return rowData;
			}

			public void setRowData(Vector<Object> rowData) {
				this.rowData = rowData;
			}

		

		

			

}



Stock

import java.util.ArrayList;


public class Stock {
	     // list of all registered stock
	static ArrayList<Stock> al = new ArrayList<Stock>();

	     String name, symbol;

	     // constructor
	  public   Stock(String n1, String s1) {

	         name = n1;
	         symbol = s1;
	     }
	     // to return the name for the combo
	  public String getName() {
	        return name;
	     }
	     public String toString() {
	        return name;
	     }
	     public String getSymbol() {
		        return symbol;
		     }
		public static ArrayList<Stock> getAl() {
			return al;
		}
		public static void setAl(ArrayList<Stock> al) {
			Stock.al = al;
		}
	
		
		
	     
	     
	}


Was This Post Helpful? 0

#10 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2555
  • View blog
  • Posts: 10,655
  • Joined: 20-September 08

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 05:20 AM

Try

                        while ((line = input.readLine()) != null) {
                            String[] yahooStockInfo = line.split(",");
                            two.addRow(new Object[]{input2, yahooStockInfo[1], yahooStockInfo[4], yahooStockInfo[8]});

                            break;
                        }


Was This Post Helpful? 0
  • +
  • -

#11 Guest_XiangSheng*


Reputation:

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 05:40 AM

View Postg00se, on 21 July 2010 - 04:20 AM, said:

Try

                        while ((line = input.readLine()) != null) {
                            String[] yahooStockInfo = line.split(",");
                            two.addRow(new Object[]{input2, yahooStockInfo[1], yahooStockInfo[4], yahooStockInfo[8]});

                            break;
                        }


i know this will work. but because i wanted the values to be stored in a vector first for future purpose by calling the Vector from the TableModel class. so if i were to use what you suggested, where is the values actually stored at?
Was This Post Helpful? 0

#12 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2555
  • View blog
  • Posts: 10,655
  • Joined: 20-September 08

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 06:25 AM

You mean you want to cache it? If so, just add the data to the cache too
Was This Post Helpful? 0
  • +
  • -

#13 Guest_XiangSheng*


Reputation:

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 06:49 AM

i don't know how should i rephrase but i have to do it the way i posted the code earlier on. so hopefully someone can fix the error for me.
Was This Post Helpful? 0

#14 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2555
  • View blog
  • Posts: 10,655
  • Joined: 20-September 08

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 06:56 AM

Quote

but i have to do it the way i posted the code earlier on.


The way you're doing it is wrong, so you mustn't ;)

You need to keep a cache and check that before making the request. What's posing as a cache at the moment is actually just a reference to the table model itself. I would suggest using a Map with stock symbol as key for the cache
Was This Post Helpful? 0
  • +
  • -

#15 Guest_XiangSheng*


Reputation:

Re: cannot fetch correct data from URL into JTable

Posted 21 July 2010 - 07:56 AM

i got the example from here and implement it to my code http://cit.wta.swin....TableModel.html this example are able to draw different values from the database using the same code i did.

if you did a print out over here
        	            		rowData1.add(input2);
        	           	rowData1.add(yahooStockInfo[1]);
        	           rowData1.add(yahooStockInfo[4]);
        	          rowData1.add(yahooStockInfo[8]);
        	          System.out.println(rowData1);


you can see the next stocks value did appear but just that it isn't registered to the tablemodel.
Was This Post Helpful? 0

  • (2 Pages)
  • +
  • 1
  • 2