Importing text into a JTable is not displaying

646 Views Asked by At

I have created a program where I can input data in JTextField and on hitting save button I use a JFileChooser to save the data in a .txt file where each JTextField is in a new line. I also created a button that pops up a JFileChooser to browse for that file and populate its corresponding cells.

I am new to GUIs, the code I wrote is not working. I tried different variations and cannot seem to get it. Can someone point me in the right direction please.

The input is

 john
Doe
st. Jude
100

Here is the code

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;

//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;

public class Charity 
{
@SuppressWarnings("deprecation")
public static void main(String[] args) 
{
    JFrame frame = new JFrame("Learning Team Charity Program");
    Container cp = frame.getContentPane();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Charities
    final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
    final JComboBox selector = new JComboBox(charityArray);
    JPanel first = new JPanel();
    first.setLayout(new FlowLayout());
    first.add(selector);

    // User input JLabels and JTextFields
    JLabel nameLabel = new JLabel("First Name: ");
    final JTextField name = new JTextField();
    JLabel lastLabel = new JLabel("Last Name: ");
    final JTextField lastname = new JTextField();
    JLabel donationAmount = new JLabel("Donation Amount: ");
    final JTextField donation = new JTextField();


    JPanel second = new JPanel();
    second.setLayout(new GridLayout(4,2));
    second.add(nameLabel); second.add(name);
    second.add(lastLabel); second.add(lastname);
    second.add(donationAmount); second.add(donation);


    // Donate & Exit Buttons
    JButton donateButton = new JButton("Donate");
    JButton saveButton = new JButton("Save");
    JButton exitButton = new JButton("Exit");
    JButton openButton=  new JButton("Open File");
    JPanel third = new JPanel();
    third.setLayout(new FlowLayout());
    third.add(donateButton);
    third.add(saveButton);
    third.add(openButton);
    third.add(exitButton);

    // JTable display
    final DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    model.addColumn("First Name");
    model.addColumn("Last Name");
    model.addColumn("Charity");
    model.addColumn("Donation");

    table.setShowHorizontalLines(true);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);      
    JScrollPane scrollPane = JTable.createScrollPaneForTable(table);

    JPanel fourth = new JPanel();
    fourth.setLayout(new BorderLayout());
    fourth.add(scrollPane, BorderLayout.CENTER);

    // Button Events
    exitButton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            System.exit(1); 
        }
    });

    openButton.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e){
    JFileChooser openChooser = new JFileChooser();
    int openStatus = openChooser.showOpenDialog(null);
    if(openStatus == JFileChooser.APPROVE_OPTION){
        try{
            File myFile = openChooser.getSelectedFile();
            BufferedReader br = new BufferedReader(new FileReader(myFile));

            String line;        
        while((line = br.readLine())!= null){
                             model.addRow(line.split(","));           

                    }//end while
                      br.close();
                }//end try

                catch(Exception e2){
                     JOptionPane.showMessageDialog(null, "Buffer Reader Error");
                }//end catch
            }
        }


        private void setValueAt(String line, int row, int col) {
            // TODO Auto-generated method stub

        }

    });

    saveButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e){
            JFileChooser fileChooser = new JFileChooser();
            int status = fileChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION)
            {
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
                //fileChooser.setFileFilter(new FileFilter("txt"));
                PrintWriter output;
                try {
                    File file = fileChooser.getSelectedFile();
                    output = new PrintWriter(file +".txt");
                    for(int row = 0; row<table.getRowCount(); row++){
                        for(int col = 0; col<table.getColumnCount();col++){
                            output.println(table.getValueAt(row, col).toString());

                        }
                        output.println();
                    }

                    output.close();

                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }

});
    donateButton.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {

            DecimalFormat df = new DecimalFormat("##,###.00");
            try 
            {

                Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
                    donation.getText()};
                    model.addRow(rows);
                    name.setText("");
                    lastname.setText("");
                    donation.setText("");
            } 
            catch (Exception ex) 
            {
                JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
    });

    // Frame Settings
    frame.setSize(470,300);
    //frame.setLocation(300,200);
    cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
    cp.add(first);
    cp.add(second);
    cp.add(third);
    cp.add(fourth);
    frame.setVisible(true);

    }   
}
2

There are 2 best solutions below

2
On BEST ANSWER

I figured it out. Thanks for all those that tried to help.

openButton.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e){
    JFileChooser openChooser = new JFileChooser();
    int openStatus = openChooser.showOpenDialog(null);
    if(openStatus == JFileChooser.APPROVE_OPTION){
        try{
            File myFile = openChooser.getSelectedFile();
            //BufferedReader br = new BufferedReader(new FileReader(myFile));
                             Scanner br = new Scanner(new FileReader(myFile));
            String line;        
        while((line = br.nextLine())!= null){
                        Object[] myRow = new Object[]{line,br.nextLine(), br.nextLine(), br.nextLine()};
                             model.addRow(myRow);
                            // line = br.readLine();
                                if(br.nextLine()== " "){
                                    line=br.nextLine();
                                }
                    }//end while
                      br.close();
                }//end try

                catch(Exception e2){
                     return;
                }//end catch
            }
        }

    });
2
On

I understand I have to pass a value in the parenthesis after the addRow.

People don't know what that means because the code you posted here doesn't have an addRow(...) method.

I see you posted a second question 2 hours later: https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable.

Keep all the comments in one place so people understand what is going on.

Also, posting a few random lines of code doesn't help us because we don't know the context of how the code is used. For example, I have no idea what how you created the "model" variable. I don't know if you ever added the model to the table.

Post a proper SSCCE when posting a question so we have the necessary information. The file chooser is irrelevant to the problem because we don't have access to your real file. So instead you need to post hard coded data. An easy way to do this is to use a StringReader.

Here is a working example that shows how to read/parse/load a file into a JTable:

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        try
        {
            DefaultTableModel model = new DefaultTableModel(0, 4);

            String data = "1 2 3 4\na b c d\none two three four";
            BufferedReader br = new BufferedReader( new StringReader( data ) );
            String line;

            while ((line = br.readLine()) != null)
            {
                String[] split = line.split(" ");
                model.addRow( split );
            }

            JTable table = new JTable(model);
            add( new JScrollPane(table) );
        }
        catch (IOException e) { System.out.println(e); }
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new SSCCE());
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

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

All you need to do is change the code to use a FileReader instead of the StringReader.