This is just a small snippet of my program but it's a gui and the criteria is when the Open option comes up the user can select a text file that contains the data that is going to be loaded into the JTable.

My code only places the first line of the file into the first row and first column in the JTable. I can't figure out whyyy! :/

else if(ae.getActionCommand().equals("Open")){

			JFileChooser jfc = new JFileChooser();

			// pop up the file menu box, "null" means we don't want to associate it with a component

			//if you want a Save Box to show instead
			//call the method showSaveDialog....
			int result = jfc.showOpenDialog(null);

			//the box will stay open until the user hits ok, cancel, x....

			//if the user selectes "Ok", extract the file 

			File f=null;
		
			Scanner sc = null;
			if(result == JFileChooser.APPROVE_OPTION){
				f = jfc.getSelectedFile();
				docName=f.getName();
				//read and display the data from the file

				try{
					sc = new Scanner(f);
				}catch(FileNotFoundException e){
					System.out.println("File Not Found!");
					System.exit(-1);
				}

				int column=0;
				int row=0;
				
				while(sc.hasNext()){

					theTable.setValueAt(sc.nextLine(), row, column);
					//last column, start back at 0 increase row
					if(column==4){
						column=0;//start column back at 0
						row++;//row number increase
					}
					//increase column
					else{
						column++;
					}

					//update JTable
					tableChanged(new TableModelEvent(theTable.getModel()));

				}
	
				setTitle(docName + "*");
			}

Any help is very much appreciated.

Recommended Answers

All 2 Replies

Don't use table.setValueAt() for adding data to a table. Add the data to your table model and fire a tableChanged event.

If the system showed errors, show them.
possible cases:
-Your text file contains only single row (check this in line 34)

//34.
                System.out.println(row * 5 + column);

- line 47 introduces an unwanted side effect (comment this line).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.