Link to home
Create AccountLog in
Avatar of tyweed420
tyweed420

asked on

Jtable and its defaulttablemodel will not update text from the clipboard. Although changetable shows that the data was edited?

I have a java gui that I have created that uses a jtable with an extension to the defaulttablemodel to hold phone numbers,names,etc. There is a menuitem cut,copy,and paste that i'm trying to implement for the table. So i want to be able to double click into a cell highlight the text and copy/paste the text from selecting copy  menuitem.. Then i want to be able to highlight a cell and then hit the paste menuitem.

I'm using the clipbloard and have the copy function working great. The problem is that when i then select another cell and then click on the paste menuitem nothing changes in the cell? Whats strange is in the tablechanged() it shows the column i highlighted to paste as having the pasted data. But it is not showing. then if i select another cell and then go back and click that cell i pasted into and that pasted content is no longer showing from the changeTable() row,col data is gone. It never showed the pasted data on the actual table. However, the data within the changetabl;e when printing the data shows the pasted value until it is deselected? I'm not sure what is happening? I have tried all fire updates of tablemodel with no luck and even revalidate of jtable.

I'm using the tablemodel.setvalueat(row,column) then calling                                           tm.fireTableCellUpdated(row, column);

this should be all i need however it is not updating the table. Any ideas please!

i should note that when i try to add a row in the paste execution it worked fine? I commented that out that portion of my debugging to reduce confusion. But it shows its something with the tm.setvalueat() that is the problem!



public void tableChanged(TableModelEvent evt)
{
 
        if (evt.getType() == TableModelEvent.UPDATE)
        {
			int column = evt.getColumn();
			int row = evt.getFirstRow();
			System.out.println("Update -> row: " + row + " column: " + column);
			TableModel model = (TableModel)evt.getSource();
			String columnName = model.getColumnName(column);
			Object data = model.getValueAt(row, column);
			System.out.println("CLM " + columnName);
			System.out.println("VAL " + data);
			tableHasChanged=true;
        }
 
    }
 
prints for VAL: the value like it was inserted but nothing shows or stays?
 
================= this is the paste action in actionperformed that is executed when i click paste menuitem================================================
 
			else if(menuItem.getText() == "Paste")
			{
                Transferable clipboardContent = clipboard.getContents(this);
 
 				if ((clipboardContent != null) &&
 	        	(clipboardContent.isDataFlavorSupported (DataFlavor.stringFlavor)))
 	        	{
 					try
 					{
 	           	        String tempString;
 						tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor);
 						if(currFile.equals("Notes.txt"))
 						{
							area.insert(tempString,area.getCaretPosition());
						}
						else
						{
 
							int row = table.getSelectedRow();
							int column = table.getSelectedColumn();
							tm.setValueAt(tempString, row,column);
							tm.fireTableCellUpdated(row, column);
 
							/*String[] s = new String[3];
							s[0] ="t";
							s[1] ="u";
							s[2] = "p";
							tm.addRow(s);
                             */
							
							System.out.println(tempString + " pasted ");
					    }
 					}

Open in new window

Avatar of MicheleMarcon
MicheleMarcon
Flag of Italy image

These situation may be a lot frustrating... I usually avoid manipulation of table's data this way.
And it's also a bad practice to manipulate the data during the event dispatch thread for many reasons.

I suggest that you approach the problem from a different perspective: try implementing your own table model instead. There, you will control all the data manipulation.

jTable.getValueAt(jTable.getSelectedRow(), jTable.getSelectedColumn())

When you have finished, do a jTable.setModel(...) and you are done.

Avatar of Dejan Pažin

>> I'm using the tablemodel.setvalueat(row,column) then calling
>> tm.fireTableCellUpdated(row, column);


tablemodel.setvalueat(row,column)

I belive you are actually using method:

setValueAt(Object aValue, int rowIndex, int columnIndex)

not

setValueAt(int rowIndex, int columnIndex)

Which is ok. There must something else wrong with your code. Simply calling this method
on DefaultTableModel is what you need. The implementation (if you look at the sources) already calls fireTableCellUpdated(row, column);

Try creating the complete runnable code (with the bug) and post it.

MicheleMarcon:
>> And it's also a bad practice to manipulate the data during the event dispatch thread for many reasons

Which reasons are that?

>> I suggest that you approach the problem from a different perspective: try implementing your own table model instead.

How will that change the fact that he is manipulating data from event dispatch thread?

>> When you have finished, do a jTable.setModel(...) and you are done.

Thats exactly what you shouldnt do. Calling that will set a new model on the table each time. You should only change the data inside the model.


The event dispatch threads "hangs" the repaint of the application until is finished. This may lead to graphical inconsistency, freezing and deadlocks if not done properly, Some Look&Feel (like Substance) aren't very tolerant to EDT violations.

Actually, yes, my suggestion DO change data on the EDT, but without programmatically firing table events.

And ok, I set a new model each time, but "it worked for me" so...
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of tyweed420
tyweed420

ASKER

Cehj the answer you gave works. I just wish I could figure out why a simple

                                          tm.setValueAt(tempString, row,column);
is not displaying the value. It must be a focus issue or something. Because your answer deselects the cell and takes it out of editing mode. Where when i do the setvalue method it stays in editing mode with the blinking caret and nothing happens?
dejanpazin: here is the complete code with the bug. Here is the system.out.print in tableChanged() which shos it has the value in the cell but nothing shows nor holds. Any ideas?

Update -> row: 2 column: 2
CLM Address
VAL
Update -> row: 1 column: 2                       <============ here i copied 23456789 from this row
CLM Address
VAL 23456789
Update -> row: 2 column: 2 <= moved down one row same column and pasted see how it shows a value?
CLM Address
VAL 23456789
23456789                                          pasted
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.*;
import java.io.*;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.util.ArrayList;
import javax.swing.event.*;
import javax.swing.table.TableModel;
import java.awt.* ;
import java.awt.datatransfer.*;
 
 
public class PhoneBook extends PhoneBookGui implements TableModelListener,ClipboardOwner
{
	//========== need to make these all private later======================
 
  JTable table;
  MyTableModel tm;
  JPanel tablePanel;
  JPanel topPanel;
  JScrollPane scrollPane;
  Vector headers;
  Vector addContactData;
  JTextField fields[];
  String[] fileData;
  boolean tableHasChanged;
  boolean rebuildContainer;
    private Clipboard clipboard;
 
 
public void tableChanged(TableModelEvent evt)
{
 
        if (evt.getType() == TableModelEvent.UPDATE)
        {
			int column = evt.getColumn();
			int row = evt.getFirstRow();
			System.out.println("Update -> row: " + row + " column: " + column);
			TableModel model = (TableModel)evt.getSource();
			String columnName = model.getColumnName(column);
			Object data = model.getValueAt(row, column);
			System.out.println("CLM " + columnName);
			System.out.println("VAL " + data);
			tableHasChanged=true;
        }
 
    }
 
 
  PhoneBook()
  {
    super();
    createJTableHeaders(configInfo.defaultTable);
    createSortItems();
    createTable();
 
    topPanel = new JPanel();
    topPanel.setLayout(new BorderLayout());
    topPanel.add(buttPanel,"North");
    topPanel.add(scrollPane,"Center");
    getContentPane().add(topPanel);
 
 
    openFile(configInfo.defaultTable);
 
 
  }
 
 private String appendExtension(String file)
 {
            int sizeOfString = file.length();
		    if(file.substring(sizeOfString - 4,sizeOfString).equals(".txt"))//if it does not have .txt add it
		    {
			}
			else
			{
				file = file + ".txt";
			}
 
	 return file;
 }
 
 
 
  private void createJTableHeaders(String currFile)
  {
	 try
	  {
		   currFile = appendExtension(currFile);
		  	headers = new Vector();
	  		BufferedReader br = new BufferedReader(new FileReader(configInfo.files_path + currFile ));
	  		String line = br.readLine();
 
	  		StringTokenizer tokens = new StringTokenizer(line,"\",");
	  		while(tokens.hasMoreTokens())
	  		{
				String temp = tokens.nextToken();
                headers.add(temp);
	  		}
 
	  	  }
	  	  catch(IOException e)
	  	  {JOptionPane.showMessageDialog(this, "Error Opening File " + currFile +  " make sure you created it in your files folder", "Warning . . .", 0);
	      }//currently if it throws exception it crashes the program after may want to fix this later
  }
 
  private void changeTable(String newFile)
  {
 
 
	    if(tableHasChanged == true)
	    {
          int option = JOptionPane.showConfirmDialog(null, "It appears you have possibly changed the table would you like to save these changes before switching to another table?" +
          "\n" +"  (if you select no your changes will be lost)", "", JOptionPane.YES_NO_OPTION);
          if(option == JOptionPane.YES_OPTION)
          {
			tableHasChanged = false;
			saveFile(currFile);
            changeTable(newFile);
 
		  }
          else if(option == JOptionPane.NO_OPTION)
          {
          tableHasChanged = false;
          changeTable(newFile);
	      }
          else
          {
          tableHasChanged = false;
          changeTable(newFile);
		  }
 
        }
		else
		{
			if(rebuildContainer == true)
			{
				getContentPane().remove(topPanel);
				topPanel = new JPanel();
				topPanel.setLayout(new BorderLayout());
				topPanel.add(buttPanel,"North");
				topPanel.add(scrollPane,"Center");
				getContentPane().add(topPanel);
				getContentPane().validate();
				rebuildContainer = false;
			}
 
			currFile = newFile;
			createJTableHeaders(currFile);
			tm = new MyTableModel(headers,0);
			table.setModel(tm);
			table.getModel().addTableModelListener(this);
            openFile(currFile);
            System.out.println("current file at end of changetable(): " + currFile);
 
		}
 
  }
 
  private void createTable()
  {
	   tm = new MyTableModel(headers,0);
       table = new JTable(tm);
       scrollPane = new JScrollPane(table);
       table.addMouseListener(popupListener);
       table.getModel().addTableModelListener(this);
       tableHasChanged = false;
 
  }
 
 
 
   /**
    Clears the table from the view
    */
    private void clearTable()
    {
        tm.setRowCount(0);
    }
 
public void lostOwnership (Clipboard parClipboard, Transferable parTransferable)
  {
 	  	System.out.println ("Lost ownership");
 	  }
  /**
    Performs the specific actions once a listener is invoked
    */
    public void actionPerformed(ActionEvent actionevent)
    {
        Object obj = actionevent.getSource();
        if(obj instanceof JButton )
        {
			JButton button = (JButton) obj;
			if(button.getText() == "Add Contact")
			{
				openContactWindow();
			}
			else if(button.getText() == "Submit")
			{
				getAddContactInfo();
			}
			else if(button.getText() == "Notes")
			{
				   rebuildContainer = true;
			       String file = appendExtension(button.getText());
			       currFile = file;
			       createTextAreaFrame();
                   displayNotesArea();
                   System.out.println("current file at end of notes action performed(): " + currFile);
 
            }
		    else
            {
 
 
              String file = appendExtension(button.getText());
		      changeTable(file);
		      createSortItems();
			}
 
 
		}
		else if(obj instanceof JMenuItem)
		{
			JMenuItem menuItem = (JMenuItem)obj;
			if(menuItem.getText() == "Save as...")
			{
				saveasFile();
			}
			else if(menuItem.getText() == "Save")
			{
				System.out.println("action perform save: " + currFile);
 
				saveFile(currFile);
			}
			else if(menuItem.getText() == "Upload")
			{
			 String htmlFileName = currFile.substring(0,currFile.length()-4);
		     System.out.println(htmlFileName);
 
			 Txt2Html txt2html = new Txt2Html(configInfo.files_path,currFile);
			 FtpTest ftp = new FtpTest();
			 ftp.Upload("./html/" + htmlFileName + ".html");
			}
			else if(menuItem.getText() == "Exit")
			{System.exit(0);
			}
			else if(menuItem.getText() == "Undo")
			{
 
 
			}
			else if(menuItem.getText() == "Cut")
			{
				 Toolkit tools = Toolkit.getDefaultToolkit();
				 clipboard = tools.getSystemClipboard();
                 StringSelection fieldContent = new StringSelection ("test");
                 clipboard.setContents(fieldContent, this);
            }
			else if(menuItem.getText() == "Copy")
			{
				 Toolkit tools = Toolkit.getDefaultToolkit();
				 clipboard = tools.getSystemClipboard();
 
                if(currFile.equals("Notes.txt"))
 			    {
				 String selectedText = area.getSelectedText();
                 StringSelection fieldContent = new StringSelection ( selectedText);
                 clipboard.setContents(fieldContent, this);
				}
				else
				{
 
				 int row = table.getSelectedRow();
				 int column = table.getSelectedColumn() ;
                 StringSelection fieldContent = new StringSelection (((String)table.getValueAt(row,column)));
                 clipboard.setContents(fieldContent, this);
			    }
			}
			else if(menuItem.getText() == "Paste")
			{
                Transferable clipboardContent = clipboard.getContents(this);
 
 				if ((clipboardContent != null) &&
 	        	(clipboardContent.isDataFlavorSupported (DataFlavor.stringFlavor)))
 	        	{
 					try
 					{
 	           	        String tempString;
 						tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor);
 						if(currFile.equals("Notes.txt"))
 						{
							area.insert(tempString,area.getCaretPosition());
						}
						else
						{
 
							int row = table.getSelectedRow();
							int column = table.getSelectedColumn();
							tm.setValueAt(tempString, row,column);
 
/*DefaultCellEditor editor = (DefaultCellEditor) table.getCellEditor(row, column);
JTextField tf = (JTextField)editor.getComponent();
tf.setText(tempString);
*/
 
							System.out.println(tempString + " pasted ");
					    }
 					}
				   catch (Exception e)
				   {
				 	    e.printStackTrace ();
 	               }
			   }
			}
            else if(menuItem.getText() == "Delete Row")
			{
              int[] row =   table.getSelectedRows();
              for(int i= row.length-1; i >= 0 ;i--)
              {
                tm.removeRow(row[i]);
		      }
              saveFile(currFile);
			}
		    else if(menuItem.getText() == "Show Buttons")
			{buttPanel.setVisible(true);
			}
			else if(menuItem.getText() == "Hide Buttons")
			{buttPanel.setVisible(false);
			}
			else if(menuItem.getText() == "Show Notes")
			{areaPane.setVisible(true);
			}
			else if(menuItem.getText() == "Hide Notes")
			{areaPane.setVisible(false);
			}
			else
			{
 
                checkIfSortItemClicked(menuItem);
                checkIfCategoryItemClicked(menuItem);
 
 
			}
 
		}
	}
 
    /**
    If a Sort menuItem is clicked it will loop through and recognize which and sort accordingly
    */
    private void checkIfSortItemClicked(JMenuItem menuItem)
    {
			   for(int i=0;i < sort.getItemCount();i++)
			   {
				 if(menuItem.getText() == sort.getItem(i).getText())
				 {
					 Sort(i);
				 }
		       }
 
	}
 
	/**
	If category menu item is clicked it will loop through and change
	currfile to that file,update table,recreate sort items based on nw table
	*/
	private void checkIfCategoryItemClicked(JMenuItem menuItem)
	{
			   for(int i=0;i < category.getItemCount();i++)
			   {
				 if(menuItem.getText() == category.getItem(i).getText())
				 {
					   currFile =  menuItem.getText();
					   changeTable(currFile);
			           createSortItems();
				 }
		       }
	}
 
    /**
    Sorts the table given a specific row from parameter
    */
    private void Sort(int i)
    {
        tm.sortColumn(i);
 
    }
 
    /**
    For every column header it creates a sort menuItem for it in sort menu
    */
    private void createSortItems()
    {
		sort.removeAll();
 
	  for(int i=0; i < headers.size();i++)
	  {
		  String sortname = headers.get(i).toString();
		  JMenuItem sortItem = createJMenuItem("by " + sortname);
		  sort.add(sortItem);
	  }
 
 
 
	}
 
    /**
    Creates the notes frame window and holds the Jtextarea
    */
    private void createTextAreaFrame()
    {
		JScrollPane scrollPaneArea = new JScrollPane(areaPane);
		getContentPane().remove(topPanel);
		topPanel = new JPanel();
		topPanel.setLayout(new BorderLayout());
		topPanel.add(buttPanel,"North");
		topPanel.add(scrollPaneArea,"Center");
        getContentPane().add(topPanel);
        getContentPane().validate();
 
	}
 
 
    /**
    Creates the addContact window and creates all necessary JTextFields and JTextLabels
    */
    private void openContactWindow()
    {
		int num_of_rows = headers.size();
		JLabel labels[] = new JLabel[num_of_rows];
	    fields = new JTextField[num_of_rows];
        JPanel addContactsPanel = new JPanel();
        addContactsPanel.setLayout(new GridLayout(num_of_rows,2));
 
		for(int i=0; i < headers.size();i++)
		{
 
			labels[i] = new JLabel(headers.get(i).toString() );
			fields[i] = new JTextField(20);
 
			addContactsPanel.add(labels[i]);
			addContactsPanel.add(fields[i]);
 
 
		}
 
		JButton addContactButton = new JButton("Submit");
		addContactButton.addActionListener(this);
		JFrame frame_file = new JFrame();
	    frame_file.setSize(600, 300);
	    frame_file.setTitle("Add Contacts");
		frame_file.getContentPane().setLayout(new BorderLayout()) ;
		frame_file.getContentPane().add(addContactsPanel,BorderLayout.CENTER);
		frame_file.getContentPane().add(addContactButton,BorderLayout.SOUTH);
        frame_file.show();
	}
 
    /**
    Grabs info from JTextFields in the addContact window and adds to a new row
    This method is called when submit button is pressed from addContact window
    */
    private void getAddContactInfo()
    {
		addContactData = new Vector();
		for(int i=0; i < fields.length;i++)
		{
 
			 String fixed = toUppercase(fields[i].getText());
			 addContactData.add(fixed);
			 fields[i].setText("");//clear JTextFields once you get the data
 
		}
 
		tm.addRow(addContactData); // add the vector of info to a new row
		tm.fireTableDataChanged(); // update table info
        saveFile(currFile);
	}
 
   /**
    Turns first character into uppercase
   */
   private String toUppercase(String s)
   {
	   if(s.length() == 0)
	   {
		   return s;
	   }
	   else
	   {
	    //get first char and make uppercase
	    String char1 = s.substring(0,0);
	    char1 = s.toUpperCase();
	    char newUpperChar = char1.charAt(0);
 
	    //replace first char with new uppercase
        char[] chars = s.toCharArray();
        chars[0] = newUpperChar;
        String s2 = new String(chars);
        return s2;
	   }
 
 
   }
 
   /**
   Open notes.txt and read into Jtextarea
   */
   private void displayNotesArea()
   {
	 try
	 {
	    BufferedReader br = new BufferedReader(new FileReader(configInfo.files_path +  "Notes.txt"));
	    String line = br.readLine();
 
	    area.setText("");
	    while( line != null)
	    {
		  area.append(line + "\n");
		  line = br.readLine();
		}
		br.close();
	 }
	 catch(IOException e)
	 {
		JOptionPane.showMessageDialog(this, "Error Opening File . . ." + configInfo.files_path + "Notes.txt" + " make sure it exists in files directory", "Warning . . .", 0);
 
	 }
   }
 
 
 
  /**
  Opens file given from parameter.Must be a text file
  */
  private void openFile(String file)
  {
     try
 	 {
 	    BufferedReader bufferedreader = new BufferedReader(new FileReader(configInfo.files_path + file));
 	    if(bufferedreader == null)
 	    {
 	       bufferedreader.close();
 	    }
 	    if(tableHasChanged == true)
 	    System.out.println("save table first there have been changes");
 	       bufferedreader.readLine();// skip first line it has header info
 	       String s1 = bufferedreader.readLine();
 	       boolean flag = false;
 	       for(; s1 != null; s1 = bufferedreader.readLine())
 	       {
 	          Vector vector = new Vector(10);
 	          for(StringTokenizer stringtokenizer = new StringTokenizer(s1, "\","); stringtokenizer.hasMoreTokens(); vector.add(stringtokenizer.nextToken()))
 	          {
			  }
 	          tm.addRow(vector);
 	       }
 	      bufferedreader.close();
 
 
 	 }
     catch(IOException ioexception)
 	 {
 	   JOptionPane.showMessageDialog(this, "Error Opening File . . ." + configInfo.files_path + file , "Warning . . .", 0);
 	 }
 
    }
 
    /**
    Saves file by writing to file string s1 represents
    if s1 is empty string it opens window so you can name file
    */
    public void saveFile(String file)
    {
		System.out.println("file to be saved: " + file);
        if(file == "")
        {
            saveasFile();
        } else
        {
			File currentfile = new File(file);
		   if(currFile.equals("Notes.txt"))
		   writeToFileJTextArea(currentfile);
		   else
			writeToFile(currentfile);
 
        }
    }
 
    private void writeToFile(File file)
    {
	   	 boolean exceptionThrown = false;
		 try
		 {
		    BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(configInfo.files_path + "temp.txt"));
		    BufferedReader br = new BufferedReader(new FileReader(configInfo.files_path + file));
            System.out.println(" in writetoFile: " + file);
		    //gotta rewrite the first line that has header info when file is re written
		    String firstLine = br.readLine();
		    bufferedwriter.write(firstLine + "\n");
		    br.close();
 
		    //gotta skip first line somehow
            for(int j = 0; j < tm.getRowCount(); j++)
		    {
               for(int k = 0; k < tm.getColumnCount(); k++)
		       {
					if(tm.getValueAt(j, k) == null)// if cell is empty fill in with this value
		            {bufferedwriter.write("n/a" + " " + ",");
				    }
				    else
				    { bufferedwriter.write(tm.getValueAt(j, k) + " " + ",");
				    }
		       }
 
		       bufferedwriter.write("\n");//end of row new line
		    }
 
		    bufferedwriter.close();
		  }
		  catch(Exception e)
		  {
		     JOptionPane.showMessageDialog(this, "Error Opening File During Saving Process and/or writing to temp file. . .", "Warning . . .", 0);
		     exceptionThrown = true;
		     System.out.println(e);
 
		  }
          //ok to now write to actual file if exceptionThrown is false
		  if(exceptionThrown == false)
		  {
			  try
			  {
				  System.out.println("in write to file() bottom: " + file);
                BufferedWriter bw = new BufferedWriter(new FileWriter(configInfo.files_path + file));
                BufferedReader br = new BufferedReader(new FileReader(configInfo.files_path + "temp.txt"));
 
                String line = br.readLine();
                while(line != null)
                {
					bw.write(line + "\n");
					line = br.readLine();
				}
 
                br.close();
                bw.close();
			  }
			  catch(Exception e)
			  {
				 JOptionPane.showMessageDialog(this, "Error Opening File During Saving Process and/or writing to file. . .", "Warning . . .", 0);
			  }
		  }
 
	}
 
	    private void writeToFileJTextArea(File file)
	    {
		   	 boolean exceptionThrown = false;
			 try
			 {
			    BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(configInfo.files_path + "temp.txt"));
	            System.out.println(" in writetoFilejtextarea: " + file);
 
 
			    String contents = area.getText();
                bufferedwriter.write(contents);
 
 
			    bufferedwriter.close();
			  }
			  catch(Exception e)
			  {
			     JOptionPane.showMessageDialog(this, "Error Opening File During Saving Process and/or writing to temp file. . .", "Warning . . .", 0);
			     exceptionThrown = true;
			     System.out.println(e);
 
			  }
	          //ok to now write to actual file if exceptionThrown is false
			  if(exceptionThrown == false)
			  {
				  try
				  {
					 System.out.println("in write to file() bottom: " + file);
	                BufferedWriter bw = new BufferedWriter(new FileWriter(configInfo.files_path + file));
	                BufferedReader br = new BufferedReader(new FileReader(configInfo.files_path + "temp.txt"));
 
	                String line = br.readLine();
	                while(line != null)
	                {
						bw.write(line + "\n");
						line = br.readLine();
					}
 
	                br.close();
	                bw.close();
 
				  }
				  catch(Exception e)
				  {
					 JOptionPane.showMessageDialog(this, "Error Opening File During Saving Process and/or writing to file. . .", "Warning . . .", 0);
				  }
			  }
 
	}
    /**
    Allows you to name or rename current file then saves it
    */
    public void saveasFile()
    {
        JFileChooser jfilechooser = new JFileChooser(configInfo.files_path);
        boolean exceptionThrown = false;
        jfilechooser.setFileSelectionMode(0);
        int i = jfilechooser.showSaveDialog(this);
        if(i == 1)
        {
            return;
        }
        File file1 = jfilechooser.getSelectedFile();
        if(file1 == null || file1.getName().equals(""))
        {
            JOptionPane.showMessageDialog(this, "Invalid file name . . .", "Warning . . .", 2);
        }
        else
        {
           writeToFile(file1);
 
        }
 
    }
 
 
    public static void main(String args[])
    {
        PhoneBook dogfiler = new PhoneBook();
        WindowQuitter windowquitter = new WindowQuitter();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dimension = toolkit.getScreenSize();
        int i = dimension.height - 50;  // i had to subtract a bit from height so jscrollpane would appear a bit sooner
        int j = dimension.width;
        dogfiler.setSize(j, i );
        dogfiler.setTitle("Phone Book v1.0");
        dogfiler.addWindowListener(windowquitter);
        dogfiler.setVisible(true);
    }
 
 
 
 
 
 
}

Open in new window


>> dejanpazin: here is the complete code with the bug

The code you posted is not complete. I need to run the code to see what happents, but here I am missing a lot of classes (PhoneBookGui, MyTableModel,...).

There are two things you can do:

1. Post the complete code with all the classes, so we can run the code
2. Create a new small project, where you reproduce the bug and post that code.

The most important class I am missing here is MyTableModel. Try to make a short project with only simple JTable and MyTableModel and a button simulating paste action (simply hard code a call to setValue()) to see if the bug still occurs.



>>Cehj the answer you gave works.

Yes, but i'm not happy with it