2

A quick Question:

I'm trying to import some information from a CSV into a jtable that is located on a swing panel in my program.

I've imported the information into the actionListener using inputstream and parsed through it with bufferedreader. I just used a simple while loop afterwards to add to the Jtable. however, when I run the app, no information shows up in my jtable.

When I try to debug the program, I have no issues toggling between the two jpanels (and the other information that is on them) its just my jtable that shows up empty.

Here's my code:

public class wert extends JFrame {

    private JPanel contentPane;
    private JPanel panel;
    private JTable table;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    wert frame = new wert();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public wert() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 925, 486);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        JButton btnNewButton = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    Path filePath = Paths.get("\\test folder\\newNeetest.csv\\");
                    InputStream input = null;

                    input = Files.newInputStream(filePath);
                     BufferedReader reader = new BufferedReader (new InputStreamReader(input));

                     DefaultTableModel model = (DefaultTableModel)table.getModel();

                    Object [] lines = reader.lines().toArray();

                    for (int q =0; q > lines.length; q++) {
                        String dsa = lines[q].toString();
                        String [] dataRow = dsa.split(",");
                        model.addRow(dataRow);
                    }
                    } 


                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }



            }
        );
        contentPane.add(btnNewButton, BorderLayout.NORTH);

        panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);

        table = new JTable();
        GroupLayout gl_panel = new GroupLayout(panel);
        gl_panel.setHorizontalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addGap(475)
                    .addComponent(table, GroupLayout.PREFERRED_SIZE, 230, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(188, Short.MAX_VALUE))
        );
        gl_panel.setVerticalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(table, GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE)
                    .addGap(375))
        );
        panel.setLayout(gl_panel);
    }

}
K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
Leemi
  • 103
  • 8
  • How do you know data was added to the TableModel? How do you know your method is referencing the table that is visible on the GUI. Maybe you created two instance of the JTable. – camickr Dec 03 '18 at 01:25
  • 1
    This is not a simple question as you're asking help debugging code that we can't compile, run or test. If you don't get a solution soon, please consider posting a valid [mcve] program as code-formatted text (as you've done with your code snippet here) with your question. This offers the best chance of us being able to help figure out the problem and its solution. – Hovercraft Full Of Eels Dec 03 '18 at 01:25
  • @camickr while I have multiple tables in my application, the default table model is referencing table three, which is the only table within the panel i'm working on... unless I've missed something? – Leemi Dec 03 '18 at 01:29
  • @HovercraftFullOfEels updated code. – Leemi Dec 03 '18 at 01:36
  • 1
    @Leemim, 1) I asked you two questions. 2) your updated code still tell us nothing. a) we have no idea where you create the table. b) it is not an "MCVE". We can't compile/test the code and we don't have access to your file. So int the "MCVE" you should be adding hard coded data to the model. Once you prove that works, then you get the data from the file. And in your "MCVE" we don't care about you other tables, only the one that is causing the problem. – camickr Dec 03 '18 at 01:41
  • Thanks for the additional code, but I'm still without a clue as your posted code is not yet complete enough to allow me to copy, paste, compile and run it, all requirements for a valid MCVE. We don't want your entire program, as this would have much code that is not relevant to the problem, but we do want *enough* code, enough so that the posted code demonstrates the problem for us. If you're still stuck, please re-read the [MCVE](https://stackoverflow.com/help/mcve) link and give this another go. Yes, this is asking a lot of you, but it is usually worth it – Hovercraft Full Of Eels Dec 03 '18 at 01:54
  • 1
    In addition to @HovercraftFullOfEels' advice on creating an MCVE, remove the external data file & replace it with a hard coded `String` than contains just two lines of data. BTW *"Importing CSV into JTable on Jpanel (no CSVReader)"* By the time you achieve this, you will have at least a simple CSV reader. – Andrew Thompson Dec 03 '18 at 01:55
  • @Hovercraft Full Of Eels Thank you all for your patience. I've recrafted the example about. Let me know if it suits your needs. Your support is appreciated. – Leemi Dec 03 '18 at 02:31
  • `Let me know if it suits your needs.` - no because we still can't execute the code for reasons given multiple time above. – camickr Dec 03 '18 at 04:47

1 Answers1

3

A few problems with your posted code:

  1. First of all, it requires an outside file, one that we are not privy to. Fortunately this can be overcome
  2. You don't put your JTable into a JScrollPane. Scroll panes are perfect for displaying the full JTable including its column headers.
  3. You use GroupLayout, not necessary, and more importantly perhaps messing things up for you, since it limits the visualization of your table
  4. You don't give your JTable a decent table model, one with column headers, so when you add new data to it, the model is confused and may not know how many columns to display

Suggestions:

  • Put the table into a JScrollPane
  • Place that JScrollPane BorderLayout.CENTER -- your contentPane JPanel would work well for this.
  • Give the JTable a decent model. Even a most simple DefaultTableModel, one with a column header String array and an int, 0, for the number of initial rows.
  • Be sure that the column header String array's length is the actual number of columns needed

For example, your code changed to an MCVE that works:

import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class Wert2 extends JFrame {

    private JPanel contentPane;
    private JTable table;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Wert2 frame = new Wert2();
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Wert2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        JButton btnNewButton = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // file I/O code removed for sake of MCVE
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                for (int i = 0; i < 10; i++) {
                    Vector<String> rowData = new Vector<>();
                    for (int j = 0; j < 3; j++) {
                        rowData.add(String.format("[%d, %d]", i, j));
                    }
                    model.addRow(rowData);
                }
            }

        });
        contentPane.add(btnNewButton, BorderLayout.NORTH);

        // contentPane.add(panel, BorderLayout.CENTER);
        String[] colNames = {"A", "B", "C"};
        table = new JTable(new DefaultTableModel(colNames, 0));
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        contentPane.add(scrollPane);
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thank you for your infinite patience. I will work through this example on my application. – Leemi Dec 03 '18 at 13:13