• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

How to read a text file into a JTable using JFilechooser?  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If Anyone Knows , can you please help me how to read the text file to JTable by using JFilechooser ?
Even the text file contains the specific charecters line length
eg: idUsernamePasswordEmailAgeGender         ( ID = 2 Chars, Username = 10 chars ( if username not having 10 chars means, it include space for that, password = 5 chars, email = 5 chars, Age = 2 chars, Gender = 1 chars)


     01Amruta          12345email24F
 
Marshal
Posts: 62231
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

What a horrible requirement. Anybody formatting files like that ought to be shot  You can however use these two (very similar) methods (1 2) to get substrings from a line.
Please explain what that means about spaces. Does it mean that a username like Amruta (six letters) would be followed by four spaces to make it up to ten? If so, you can still find a substring, and maybe one of these two methods would be useful, too:- (1 2). I have never tried No 2 because it was new in Java11, but I think it may be better.
Which part of the process are you having difficulty with? I presume you know about file reading and how to close the file with try with resources. As an alternative to a buffered reader, do you know how to read a file with a Scanner? Do you know how to turn your lines into a User object? Once you have your User objects, I presume you know how to get them into a List or array? Don't even think of creating the table until you have done all those things.
Finally, do you need a file chooser to find your file? Look in the Java™ Tutorials. It can be as simple as this:-Needless to say, that naïve version doesn't allow for errors finding the file, starting in a default directory, or seeking particular kinds of files.
 
Amruta sriram
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Here is my code :
i am not getting error .

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TestTable5 {

   public TestTable5() {
       String[] defaultCols = {"Id", "Username", "Password", "email","Name","Age","Gender"};
       DefaultTableModel model = new DefaultTableModel(defaultCols, 0);
       JTable table = new JTable(model);

       JButton button = createButton(table);
       JFrame frame = new JFrame();
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.add( new JScrollPane(table));
       frame.add(button, BorderLayout.SOUTH);
       frame.pack();
       frame.setLocationByPlatform(true);
       frame.setVisible(true);
   }

   private JButton createButton(final JTable table) {
       JButton button = new JButton("Get File");
       button.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               JFileChooser chooser = new JFileChooser();
               int result = chooser.showOpenDialog(table);
               if (result == JFileChooser.APPROVE_OPTION) {
                   File file = chooser.getSelectedFile();
                   DefaultTableModel model = createModel(file);
                   table.setModel(model);
               }
           }
       });
       return button;
   }

   private DefaultTableModel createModel(File file) {
       DefaultTableModel model = null;

       try {
           BufferedReader txtReader = new BufferedReader(
                   new FileReader(file));
           String header = txtReader.readLine();
           model = new DefaultTableModel(header.split("\\s+"), 0);
           String line;
           while ((line = txtReader.readLine()) != null) {
               model.addRow(line.split("\\s+"));
           }
       } catch (IOException ex) {
           ex.printStackTrace();
       }

       return model;
   }

   public static void main(String[] args) {
       SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               new TestTable5();
           }
       });
   }
}

And my text file values : ( i saved in sampleinput.txt)

I uploaded here ( filename : 1c.png)

But my ouput is :

1a.PNG
[Thumbnail for 1a.PNG]
1b.PNG
[Thumbnail for 1b.PNG]
1c.PNG
[Thumbnail for 1c.PNG]
 
Amruta sriram
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want it displayed in jtable with specific rows and columns.
 
Campbell Ritchie
Marshal
Posts: 62231
193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pleasee always use the code button; then your code will look much better, like this():-I think you shoiuldn't try readiung in the same class you are using for your display. The many imports suggest that you are trying to do too much in a single class. Move your reading code into a different class.
I can't remember much about JTables, but:-
  • 1: Do you have to repaint anything after adding lines to your table?
  • 2: Why are you adding the lines to the table model? Surely you would have to add details of a user, which means you would have to process the lines. I don't think split("\\s+") will do anything useful.
  • 3: Have you verified that the header will split into the right number of pieces? Do you need the second argument (0)?
  • 4: Have you printed each line as you read it, to verify correct reading?
  • It is probably a good idea to have methods to create buttons, but that method seems only to create buttons associated with a table, so why is it a method at all? Why not a block of code?
     
    Amruta sriram
    Greenhorn
    Posts: 13
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Sir, is it possible to modify this code. Because i did'nt get it . what you told. i am trying to read that. But unfortunately i want this code within 2 days.
     
    Campbell Ritchie
    Marshal
    Posts: 62231
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Amruta sriram wrote:. . . i want this code within 2 days.

    Lots of time.

    I suggest you start with a class for file reading. Get that working. You obviously know most of the things you have to do and your code is good style Now, put the reading code into a separate class; you want to be able to write this sort of code:-This is one of those instances where Swing hasn't been updated to use the new Collections Framework class like ArrayList (or better, List). But Vector has an overridden toString() method, so you should see what you have entered into that table model. Once you have got that code working, you can put the model into your table.
     
    Rancher
    Posts: 2990
    20
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Using the split(...) method is only useful when you data is delimited by a special character.

    ( ID = 2 Chars, Username = 10 chars ( if username not having 10 chars means, it include space for that, password = 5 chars, email = 5 chars, Age = 2 chars, Gender = 1 chars)



    In your case you stated the data is column dependent, which mean you need to use the substring(...) method to access each column of data.

    So your code might be something like:
     
    Amruta sriram
    Greenhorn
    Posts: 13
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    @ Rob camick , Did you have that code? can you please share that is it very usefull for me . I am troubling to solve this
     
    Rob Camick
    Rancher
    Posts: 2990
    20
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    In your first picture you have a table with many columns because you manually create the array to be used for the column names.

    In your second picture you only have a single column because you try to use the "split" method to create an array of column names. The problem is the split method isn't working so you need to fix it.

    I have no idea how to split a string like you have in our file. As I suggested. in my answer I only know how to use the split() method when you file contains a string with delimiters.

    Here is a simple example:


    So your problem is the format of your data.

    I showed you:

    1. How so parse the data when you have a delimiter by using the split() method
    2. How so use "substring(...)" to get the data when you have a fixed column size

    You need to apply these concepts to your code. I can't control the format of your data. It is up to you to format your data and use the appropriate approach to parse the data into individual pieces of data that you can use to add to the TableModel.
     
    Campbell Ritchie
    Marshal
    Posts: 62231
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Rob Camick wrote:. . . I have no idea how to split a string like you have in our file. . . . I only know how to use the split() method when you file contains a string with delimiters. . . .

    Without delimiters, split() won't work full stop.
     
    Campbell Ritchie
    Marshal
    Posts: 62231
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you for noticing; did OP get an answer there. I can't seem to read that link.
     
    Don't listen to Steve. Just read this tiny ad:
    RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
    https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!