Results 1 to 16 of 16
  1. #1
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default 2 JTables using 2 seperate text files

    I need some guidance for an assignment I need to complete. I need to create 2 JTables one for holding a list of questions, the questions numbers, the asker, and the question number. The other holds the answers to the questions, the question number, the number of views, the person who answered the question, and the answers ID.

    I guess I need some help about how to go about doing this. This is an advanced Java course and I haven't had Java for about 3 years. Any suggestions would be very helpful. I will post code as I go along if I can get some insight on how to go about this.

    Thanks.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    So, where are you stuck? Do you know how to open a file? read from a file? store what you read in an appropriate data structure?

    Create a JTable? specify the data to be shown in the table? display a JTable?

    Recommended reading: How To Ask Questions The Smart Way

    db

  3. #3
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default

    I can read to and from the file. My problems are this:

    1. How do I put two JTables in one JFrame ?
    2. Can I use more than one Model?

    I guess those two are the bigger of the problems. I know how to create one table from one text file in JFrame but not how to put in the second.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by dispatch4599 View Post
    I can read to and from the file. My problems are this:

    1. How do I put two JTables in one JFrame ?[
    You would simply add the two tables into the JFrame. This should be fairly trivial to do, and without telling us what you're having problems with, we won't know how to help you. So again, what have you tried and what's not working? What are you having problems with? The layouts?


    2. Can I use more than one Model?
    Yes.


    I guess those two are the bigger of the problems. I know how to create one table from one text file in JFrame but not how to put in the second.
    You would do the same thing you do for one with the second one. When you add one JTable to a GUI, there is nothing to prevent you from adding a second; there's nothing to prevent you from reading in another text file, creating a second model and adding a second JTable.

    I'm sorry but your posts don't give us the least clue on what's causing your hang up. Perhaps if you posted an SSCCE (please see my link below), we'd have an idea.

  5. #5
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default

    You just answered my question. Thank you. I have one table already set up and yes, I guess my issue was more or less the layout. Even though I obviously didn't ask my question correctly you seemed to know what my issue seems to be. Thanks!

    I will post my code later this evening when I am get home and have decent internet, etc. Vacations and school really don't work well together.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    Quote Originally Posted by Fubarable View Post
    You would do the same thing you do for one with the second one.
    That does so remind me of a line from Fiddler on the Roof :)

  8. #8
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default Still not getting it. UGGHH!!

    Here is my Code for inserting the one JTable... Now where do I put the second so that it appears? Every time I try it, it never shows the second table.

    Java Code:
    import javax.swing.*;
    import java.io.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    
    public class Main extends JFrame implements ActionListener {
    	private QuestionModel QuestModel;
    	private JTable QuestTable;
            private AnswerModel AnswerModel;
            private JTable AnsTable;
           
    	public Main( ) {
    		super( "Questions and Answers" );
    
                   
    		try {
    			QuestModel = new QuestionModel( "Questions.txt" );
                          	QuestTable = new JTable( QuestModel );
                          	QuestTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
                                                 
    			JScrollPane scroller = new JScrollPane( QuestTable );
                          	add( scroller, "Center" );
    
    		} catch( FileNotFoundException fnfe ) {
    			JOptionPane.showMessageDialog( this, fnfe );
    		} catch( IOException ioe ) {
    			JOptionPane.showMessageDialog( this, ioe );
    		}
    
    		JPanel buttonPanelQuest = new JPanel( );
                    
    		JButton saveButtonQuest = new JButton( "Save Question" );
    		buttonPanelQuest.add( saveButtonQuest );
                   
                    JButton addButtonQuest = new JButton( "Add Question" );
    		buttonPanelQuest.add( addButtonQuest );
                           
     		JButton removeButtonQuest = new JButton( "Remove Question" );
    		buttonPanelQuest.add( removeButtonQuest );
                  	add( buttonPanelQuest, "South" );
                    
    
    		saveButtonQuest.addActionListener( this );
                   	addButtonQuest.addActionListener( this );
                   	removeButtonQuest.addActionListener( this );
    
    
                    
    	} //end constructor
    
    	
            public void actionPerformed( ActionEvent ae ) {
    		if( ae.getActionCommand( ).equals( "Save Question" ) ){  
                            try {
    				QuestModel.saveData( );
    			} catch( IOException ioe ) {
    				JOptionPane.showMessageDialog( this, "There was an error saving the data" );
    			}
    		} else if( ae.getActionCommand( ).equals( "Add Question" ) ) {
    			QuestModel.addQuestion( );
    		} else if( ae.getActionCommand( ).equals( "Remove Question" ) ) {
    			QuestModel.removeQuestion( QuestTable.getSelectedRow( ) );}
                               
    	}
    
    	/**
    	 * @param args the command line arguments
    	 */
    	public static void main(String[] args) {
    		Main m = new Main( );
    		m.setSize( 600, 200 );
    		m.setDefaultCloseOperation( m.EXIT_ON_CLOSE );
    		m.setVisible( true );
    
                }
    
    }

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You need to nest JPanels, each using its own layout and place your components in the JPanels. For instance, a JPanel using GridLayout(1, 0) could hold the two JScrollPanes that hold your two JTables, and then that can be placed into the main app which uses BorderLayou in the BorderLayout.CENTER position,...etc..

  10. #10
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default

    OK so now I have both of my tables appearing. Thank you all for guiding me to the documentation and helping me out. I now have a new problem which is probably easier than what I may think it is.

    In the first column of each row I am storing an ID number. For the ID number I would like to use the ROW number. When new data is added, a new ID is automatically assigned or if data is erased that the table adjusts accordingly. What I am thinking is that I would need to do something in the Model for the setValueAt.

    The other issue with this is that the values for each row are strings.

    Any suggestions or documentation that can help me would really be appreciated.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Without code, it's hard to help. You may wish to post an SSCCE, a small compilable runnable program that shows your problem or at least sets up your problem.

  12. #12
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default

    Hi Fubarable!

    I need to know what code I need to post is part of the problem. I know for the problem that I am having that it may affect several parts. Where I think I need to do the looping is in the Model so here is that code.

    Java Code:
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.io.*;
    
    public class QuestModel extends AbstractTableModel {
    	private String filename;
    	private ArrayList quests;
    
    	public QuestModel( String fn ) throws IOException, FileNotFoundException {
    		filename = fn;
    		quests = new ArrayList( );
    		loadData( );
    	}
    
    	@Override
    	public boolean isCellEditable(int rowIndex, int columnIndex) {
                if (columnIndex == 1 || columnIndex == 2){
    		return true;
                } else{
                    return false;
                }
    	}
    
    	public int getColumnCount( ) {
    		return Quest.FIELDCOUNT;
    	}
    
    	public String getColumnName( int col ) {
    		return Quest.HEADERS[col];
    	}
    
    	public int getRowCount( ) {
    		return quests.size( );
    	}
    
    	public Object getValueAt( int row, int col ) {
    		Quest quest = (Quest)quests.get( row );
                    return quest.get( col );
    	}
    
    	public void setValueAt( Object o, int row, int col ) {
    		Quest quest = (Quest)quests.get( row );
    
    		try {
    			quest.set( o , col );
    		} catch( NumberFormatException nfe ) {
    			JOptionPane.showMessageDialog( null, "Invalid Data Format" );
    		}
    	}
    
    	public void addQuest( ) {
    		quests.add( new Quest( ) );
                    fireTableDataChanged( );
    	}
    
    	public void removeQuest( int row ) {
    		quests.remove( row );
    		fireTableDataChanged( );
    	}
    
    
    	private void loadData( ) throws IOException, FileNotFoundException {
    		StreamTokenizer tok = new StreamTokenizer( new FileReader( filename ) );
    
    		tok.wordChars(32, 126);
    		tok.whitespaceChars(',', ',');
    
    		tok.nextToken( );
    
    		while( tok.ttype != tok.TT_EOF ) {
    			String QuestId = Integer.toString((int)tok.nval);
    			tok.nextToken( );
    			String question = tok.sval;
    			tok.nextToken( );
    			String asker = tok.sval;
    			tok.nextToken( );
    			String viewed = Integer.toString((int)tok.nval);
    
    			quests.add( new Quest( QuestId, question, asker, viewed ) );
    
    			tok.nextToken( );
    		}
    	}
    
    	public void saveData( ) throws IOException {
    		//save things here
    		BufferedWriter writer = new BufferedWriter( new FileWriter( filename ) );
    		Iterator i = quests.iterator( );
    		while( i.hasNext( ) ) {
    			Quest quest = (Quest)i.next( );
    			writer.write( quest.toString( ) );
    		}
    
    		writer.close( );
    	}
    }
    This may also help:
    Java Code:
    public class Quest {
    	public final static int FIELDCOUNT = 4;
    	public final static String [ ] HEADERS = {"Question ID", "Question", "Asker", "Views"};
    
    	private String QuestId;
    	private String question;
    	private String asker;
    	private String views ;
    
    	public Quest( ) {
    		this("", "", "", "");
    	}
    
    	public Quest(String QuestId, String question, String asker, String views) {
    		this.QuestId = QuestId;
    		this.question = question;
    		this.asker = asker;
    		this.views = views;
    	}
    
    	@Override
    	public String toString() {
    		return QuestId + "," + question + "," + asker + "," + views + ",\n";
    	}
    
    	public String getQuestId() {
    		return QuestId;
    	}
    
    	public void setQuestId(String QuestId) {
                           
    		this.QuestId = QuestId;
    	}
    
    	public String getQuestion() {
    		return question;
    	}
    
    	public void setQuestion(String question) {
    		this.question = question;
    	}
    
    	public String getAsker() {
    		return asker;
    	}
    
    	public void setAsker(String asker) {
    		this.asker = asker;
    	}
    
    	public String getViews() {
    		return views;
    	}
    
    	public void setViews(String views) {
    		this.views = views;
    	}
    
    	public Object get( int col ) {
    		Object value = null;
    
    		switch( col ) {
    			case 0: value = QuestId; break;
    			case 1: value = question; break;
    			case 2: value = asker; break;
    			case 3: value = views; break;
    			default: value = "Oh No!";
    		}
    
    		return value;
    	}
    
    	public void set( Object value, int col ) throws NumberFormatException {
    		switch( col ) {
    			case 0: setQuestId((String)value ); break;
    			case 1: setQuestion( (String)value ); break;
    			case 2: setAsker( (String)value ); break;
    			case 3: setViews( (String)value ) ; break;
    		}
    	}
    }

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by dispatch4599 View Post
    Hi Fubarable!

    I need to know what code I need to post is part of the problem.
    You need to post just what I mentioned above, a short, self-contained, compilable example, or SSCCE for short, that is compilable, runnable, that we can run, test, modify, and correct. It should be in one file, or have a few classes in one file, and should run easily for us without any outside dependencies. For more details on this, please see this link:

    The SSCCE

  14. #14
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default

    Hey Fubarable I sent you a message. You have been a great help!

  15. #15
    dispatch4599 is offline Member
    Join Date
    Sep 2010
    Posts
    8
    Rep Power
    0

    Default Outside TextFile

    Here is the Question.txt file. Questions.txt

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    The key in my mind is for you to change your TableModel to allow for a row index as the first column. This means adding a column that is not associated with data held by the Quest objects.

    I would:

    1) Make your ArrayList a generic one: ArrayList<Quest>. This allows for compile-time type safety, and also allows you to get rid of casting objects to Quest
    2) Add a getColumnClass(int.. method to tell the Model which column holds Integers. Note that if you tell the model that the column holds an Integer, it had better be an Integer.
    3) Shift your column indices over throughout the model to account for this new column, "Row Index". This means shifting the isCellEditable columnIndex numbers, the getColumnCount number, the getColumnName index, and pretty much all references to the column index throughout the model code.

    My own opinion is that the Question ID field should not hold what I'm calling the Row Index as the index is really independent of what constitutes a Quest object.

    For example (yeah, I took the time to create an SSCCE since you didn't... last time I'll do it since it really should be your responsibility):

    Java Code:
    import javax.swing.table.*;
    import java.util.*;
    import java.awt.BorderLayout;
    import java.io.*;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class TestQuest extends JPanel {
       private static final String QUEST_FILE_PATH = "Questions.txt"; //!! **** this will change depending on the location of this file !!!
       private QuestModel questModel;
       private JTable questTable;
       
       public TestQuest() {
          try {
             questModel = new QuestModel(QUEST_FILE_PATH);
             questTable = new JTable(questModel);
             
             setLayout(new BorderLayout());
             add(new JScrollPane(questTable));
          }
          catch (FileNotFoundException e) {
             e.printStackTrace();
             System.exit(1);
          }
          catch (IOException e) {
             e.printStackTrace();
             System.exit(1);
          }
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("TestQuest");
          frame.getContentPane().add(new TestQuest());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    @SuppressWarnings("serial")
    class QuestModel extends AbstractTableModel {
       private String filename;
       private ArrayList<Quest> quests; //!! added generic type
    
       public QuestModel(String fn) throws IOException, FileNotFoundException {
          filename = fn;
          quests = new ArrayList<Quest>();
          loadData();
       }
       
       @Override 
       public Class<?> getColumnClass(int columnIndex) {
          //!! tell model that column 0 holds Integers
          if (columnIndex == 0) {
             return Integer.class;
          }
          return super.getColumnClass(columnIndex);
       }
       
       @Override
       public boolean isCellEditable(int rowIndex, int columnIndex) {
          if (columnIndex == 2 || columnIndex == 3) { //!! incremented by 1 for Row Index column
             return true;
          }
          else {
             return false;
          }
       }
    
       public int getColumnCount() {
          return Quest.FIELDCOUNT + 1; //!! incremented by 1 for Row Index column
       }
    
       public String getColumnName(int col) {
          if (col == 0) {
             return "Row Index"; //!! first column holds the row index
          }
          return Quest.HEADERS[col - 1]; //!! other columns hold Quest's HEADERS Strings
       }
    
       public int getRowCount() {
          return quests.size();
       }
    
       public Object getValueAt(int row, int col) {
          if (col == 0) {
             return Integer.valueOf(row); //!! first column simply returns the row number
          }
          Quest quest = quests.get(row); //!! generics allows us to get rid of cast
          return quest.get(col - 1); //!! other columns hold Quest data
       }
    
       public void setValueAt(Object o, int row, int col) {
          if (col == 0) {
             return;
          }
          Quest quest = quests.get(row); //!! generics allows us to get rid of cast
    
          try {
             quest.set(o, col - 1);
          }
          catch (NumberFormatException nfe) {
             JOptionPane.showMessageDialog(null, "Invalid Data Format");
          }
       }
    
       public void addQuest() {
          quests.add(new Quest());
          fireTableDataChanged();
       }
    
       public void removeQuest(int row) {
          quests.remove(row);
          fireTableDataChanged();
       }
    
       private void loadData() throws IOException, FileNotFoundException {
          StreamTokenizer tok = new StreamTokenizer(new FileReader(filename));
    
          tok.wordChars(32, 126);
          tok.whitespaceChars(',', ',');
    
          tok.nextToken();
    
          while (tok.ttype != StreamTokenizer.TT_EOF) { //!! changed to get static constant from class
             String QuestId = Integer.toString((int) tok.nval);
             tok.nextToken();
             String question = tok.sval;
             tok.nextToken();
             String asker = tok.sval;
             tok.nextToken();
             String viewed = Integer.toString((int) tok.nval);
    
             quests.add(new Quest(QuestId, question, asker, viewed));
    
             tok.nextToken();
          }
       }
    
       public void saveData() throws IOException {
          // save things here
          BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
          Iterator<Quest> i = quests.iterator(); //!! added generic type
          while (i.hasNext()) {
             Quest quest = i.next(); //!! generics allows us to get rid of cast
             writer.write(quest.toString());
          }
    
          writer.close();
       }
    }
    
    class Quest {
       public final static int FIELDCOUNT = 4;
       public final static String[] HEADERS = {"Question ID", "Question", "Asker", "Views"};
    
       private String QuestId;
       private String question;
       private String asker;
       private String views;
    
       public Quest() {
          this("", "", "", "");
       }
    
       public Quest(String QuestId, String question, String asker, String views) {
          this.QuestId = QuestId;
          this.question = question;
          this.asker = asker;
          this.views = views;
       }
    
       @Override
       public String toString() {
          return QuestId + "," + question + "," + asker + "," + views + ",\n";
       }
    
       public String getQuestId() {
          return QuestId;
       }
    
       public void setQuestId(String QuestId) {
    
          this.QuestId = QuestId;
       }
    
       public String getQuestion() {
          return question;
       }
    
       public void setQuestion(String question) {
          this.question = question;
       }
    
       public String getAsker() {
          return asker;
       }
    
       public void setAsker(String asker) {
          this.asker = asker;
       }
    
       public String getViews() {
          return views;
       }
    
       public void setViews(String views) {
          this.views = views;
       }
    
       public Object get(int col) {
          Object value = null;
    
          switch (col) {
             case 0:
                value = QuestId;
                break;
             case 1:
                value = question;
                break;
             case 2:
                value = asker;
                break;
             case 3:
                value = views;
                break;
             default:
                value = "Oh No!";
          }
    
          return value;
       }
    
       public void set(Object value, int col) throws NumberFormatException {
          switch (col) {
             case 0:
                setQuestId((String) value);
                break;
             case 1:
                setQuestion((String) value);
                break;
             case 2:
                setAsker((String) value);
                break;
             case 3:
                setViews((String) value);
                break;
          }
       }
    }

Similar Threads

  1. CheckBoxes and JTables
    By lakshayghai in forum AWT / Swing
    Replies: 1
    Last Post: 03-16-2010, 08:01 PM
  2. working with files (text files)
    By itaipee in forum New To Java
    Replies: 1
    Last Post: 02-24-2009, 11:38 AM
  3. [SOLVED] Writing ArrayList to Text File on seperate Lines
    By shinjitsunohana in forum New To Java
    Replies: 9
    Last Post: 08-27-2008, 05:53 PM
  4. Behaving text files like binary files
    By Farzaneh in forum New To Java
    Replies: 2
    Last Post: 08-27-2008, 03:20 PM
  5. Text and image files within jar files
    By erhart in forum Advanced Java
    Replies: 8
    Last Post: 01-19-2008, 04:43 AM

Tags for this Thread

Posting Permissions

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