Results 1 to 5 of 5
  1. #1
    the reporter is offline Member
    Join Date
    Jun 2010
    Posts
    17
    Rep Power
    0

    Default Removing rows from DefaultTableModel

    Hi everyone i am trying to remove rows from the defaulttablemodel

    i have a defaulttablemodel in my TableModel.java class
    and my data is added into this model

    TableModel one = new TableModel();
    DefaultTableModel two = one.getModel();


    then i do a return model so that i can use my ButtonCol.java class to get the model that i want

    public DefaultTableModel getModel() {
    return two;
    }

    then i do a two.getModel().removeRow(0);

    But it doesnt remove the row any ideas why?

  2. #2
    the reporter is offline Member
    Join Date
    Jun 2010
    Posts
    17
    Rep Power
    0

    Default

    final1.java


    Java Code:
    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.ArrayList;
    import java.util.Timer;
    import java.util.TimerTask;
    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;
    
    
    
    
    
    
    @SuppressWarnings( { "serial", "unchecked" })
    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();
    	ArrayList<Stock> list = new ArrayList();
    	private ArrayList<Stock> stockList = new ArrayList<Stock>();
    	private String[] stockArray;
    	private ArrayList<Stock> stockDataList = new ArrayList<Stock>();
    	private ArrayList<String> comboList = new ArrayList<String>();
    	private Timer stockRefresh = null;
    
    	  private StockRefreshTask stockRefreshTask = null;
    
    	  private int refresh_interval = 10000; // 1000 = 1 second
    	  
    	Vector<String> v = null;
    	//counter count = new counter();
    
    	//Thread counterThread = new Thread(count);
    	
    	public final1() {
    
    	 stockRefreshTask = new StockRefreshTask();
    		    stockRefresh = new Timer();
    		    stockRefresh.schedule(stockRefreshTask, 0, refresh_interval); 
    		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);
    
    	}
    
    	public void createPage1() {
    		panel1 = new JPanel();
    		panel1.setLayout(new GridLayout(1, 0));
    		panel1.add(one.getScroll());
    		ButtonCol buttonColumn = new ButtonCol(one.getTable(), 4);
        
        
    		
    
    		// store stocks to combobox
    		String line = null;
    		try {
    			FileInputStream fis = new FileInputStream(
    					("C:/Java Sem 2/FYP SEM 1/stocklist.txt"));
    			InputStreamReader isr = new InputStreamReader(fis);
    			BufferedReader input = new BufferedReader(isr);
    			while ((line = input.readLine()) != null) {
    				String[] StockInfo = line.split(",");
    				list.add(new Stock(StockInfo[0], StockInfo[1]));
    				stockArray = new String[list.size()];
    				for (int i = 0; i < list.size(); i++) {
    					stockArray[i] = list.get(i).getName();
    					//System.out.println(stockArray[i]);
    				}
    				
    
    			}
    
    			
    			ipList.setEditable(true);
    
    			v = new Vector<String>();
    			// Starting of loop to add item
    
    			for (int i = 0; i < list.size(); i++) {
    				v.add(list.get(i).name);
    				
    				ipList.addItem(list.get(i));
    			}
    	
    			// search code key listener
    			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().toUpperCase();
    								System.out.println(ipList);
    								ipList.removeAllItems();
    								int st = 0;
    
    								for (int i = 0; i < v.size(); i++) {
    									if (v.get(i).toLowerCase().startsWith(a.toLowerCase())) {
    										//ipList.addItem(v.get(i));
    										ipList.addItem(list.get(i));
    										
    										st++;
    									}
    								}
    								ipList.getEditor().setItem(new String(a));
    								ipList.hidePopup();
    								if (st != 0) {
    									ipList.showPopup();
    								}
    							}
    						}
    					});
    
    		} catch (FileNotFoundException FNF) {
    		} catch (IOException E) {
    		}
    
    	}
    
    	public void createPage2() {
    		panel2 = new JPanel();
    		panel2.add(ipList);
    
    		ipList.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				String line = null;
    				
    
    				try {
    					//if(ipList.getSelectedItem() == null)
    
    						        //return;
    
    					String input1 = ((Stock) ipList.getSelectedItem()).symbol;				
    					String input2 = ((Stock) ipList.getSelectedItem()).name;
    					TableModel method = new TableModel();
    					
    					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,
    						
    						Vector<Object> dataV = new Vector<Object>();
    						dataV.add(input2);
    						dataV.add(yahooStockInfo[1]);
    						dataV.add(yahooStockInfo[4]);
    						dataV.add(yahooStockInfo[8]);
    						dataV.add("delete");
    						System.out.println(dataV);
    						two.addRow(dataV);
    						break;
    					}
    
    				} catch (IOException ex) {
    					ex.printStackTrace();
    
    				}
    			}
    		});
    	}
    	
    	public DefaultTableModel getModel() {
            return two;
        }
    
    	/*class counter implements Runnable {
    		 boolean run1;
    					
    		 public void run(){
    			 run1 = true;
    				
    				int x = 0; 
    				
    				
    				 try {
    						while (run1){
    						x++;
    							Thread.sleep(1000);		
    							if( x ==10){
    							
    								x = 0;
    								  
    								
    							}
    							System.out.println(x);
    						}
    						 					 
    				 }
    						 catch (InterruptedException e) {
    						 }
    
    		}
    		} */
    	class StockRefreshTask extends TimerTask {
    	 public void run() {
    
    	      try {
    	        // Just return if the database is empty
    	        if (stockArray.length == 0)
    	          return;
    	        else {
    	          for (int i = 0; i < stockArray.length; i++) {
    	        	  System.out.println("Stock price for symbol: "
    	                      + stockArray[i] + " is: " + stockArray[i]);
    	            
    	          }
    	        }
    	      } catch (Exception e) {
    	        System.out.println("error('UPDATE FAILED', 2000)");
    	      }
    	    }
    	  }  
    
    	
    	// 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);
    	}
    }

    ButtonCol.java

    Java Code:
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    
    
    public class ButtonCol extends AbstractCellEditor
    implements TableCellRenderer, TableCellEditor, ActionListener
    {
        DefaultTableModel table;
        JButton renderButton;
        JButton editButton;
        String text;
        TableModel TableMod = new TableModel();
    final1 two = new final1();
        public ButtonCol(JTable table, int column)
        {
            this.table = TableMod.getModel();
            renderButton = new JButton();
    
            editButton = new JButton();
            editButton.setFocusPainted( false );
            editButton.addActionListener( this );
    
            TableColumnModel columnModel = table.getColumnModel();
            columnModel.getColumn(column).setCellRenderer( this );
            columnModel.getColumn(column).setCellEditor( this );
        }
    
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            if (hasFocus)
            {
                renderButton.setForeground(table.getForeground());
                renderButton.setBackground(UIManager.getColor("Button.background"));
            }
          
    
            renderButton.setText( (value == null) ? "" : value.toString() );
            return renderButton;
        }
    
        public Component getTableCellEditorComponent(
            JTable table, Object value, boolean isSelected, int row, int column)
        {
            text = (value == null) ? "" : value.toString();
            editButton.setText( text );
            return editButton;
        }
    
        public Object getCellEditorValue()
        {
            return text;
        }
    
        public void actionPerformed(ActionEvent e)
        {
        	
            //int modelRow = Integer.valueOf( e.getActionCommand() );
            //TableMod.getModel().removeRow(modelRow);
    two.getModel().removeRow(0);
        }
    };
    Stock.java
    Java Code:
    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;
    		}
    	
    		
    		
    	     
    	     
    	}
    TableModel.java

    Java Code:
    import java.util.ArrayList;
    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;
    			}
    
    		
    
    		
    
    			
    
    }
    stocklist.txt

    Java Code:
    Apple,APPL
    Yahoo,YHOO

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by the reporter View Post
    But it doesnt remove the row any ideas why?
    Nowhere in your code I can find that you associate your model to a JTable; it might be that the row is removed from your model but you just can't see it ...

    kind regards,

    Jos

    ps. Naming a class TableModel (it is also an interface) is confusing ...

  4. #4
    the reporter is offline Member
    Join Date
    Jun 2010
    Posts
    17
    Rep Power
    0

    Default

    what do u mean?

    My DefaultTableModel is in TableModel.java

    rows is added to this tableModel
    DefaultTableModel two = one.getModel();

    one.getModel is it is retrieving the DefaultTableModel from tablemodel.java

    isnt that correct?

  5. #5
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,234
    Rep Power
    7

    Default

    Well, there is too much code to look at to try and understand what you are doing. Part of the problem is that you don't follow Java naming conventions which makes it even more confusing to look at the code. For example:

    a) Class names SHOULD start with an upper case character.

    b) Variable names should NOT start with an upper case character.

    When using Swing you should be using a Swing Timer, not a TimerTask.

    I don't understand the need for the TableModel class. In addition to being confusing with the name as mentioned earlier you don't need a special class to get the model. All you need to do is:

    DefaultTableModel model = (DefaultTableModel)table.getModel()

    This way you know for sure that you are getting the actual model being used by the table, not just some value in a variable.

    The methods in that class are wrong. The setModel() method does nothing. You can't just change the reference of a variable and expect it to update the table. If you want to change the model of the table then you need to use:

    table.setModel(...)

    So I suggest you get rid of the TableModel class. I think it is causing the problems.

Similar Threads

  1. DefaultTableModel vs AbstractTableModel
    By chyrl in forum AWT / Swing
    Replies: 4
    Last Post: 05-02-2010, 12:10 PM
  2. DefaultTableModel get the updated values
    By stylian in forum AWT / Swing
    Replies: 3
    Last Post: 11-01-2009, 12:26 AM
  3. DefaultTableModel problem
    By stylian in forum AWT / Swing
    Replies: 2
    Last Post: 10-31-2009, 04:23 PM
  4. RequestFocus on DefaultTableModel Particular Cell
    By yernikumar in forum AWT / Swing
    Replies: 1
    Last Post: 03-01-2009, 04:58 PM
  5. Fetching rows from DB
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-06-2008, 09:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •