1

Can someone tell me how to modify below program? Program's data is passed by object[][] - instead of that will just give file name which is having data should be print in a table.

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;

public SimpleTableDemo() {                                              
    super(new GridLayout(1,0));

    String[] columnNames = {"First Name",
                            "Last Name",
                            "Sport",
                            "# of Years",
                            "Vegetarian"};

    Object[][] data = {
    {"Kathy", "Smith",
     "Snowboarding", new Integer(5), new Boolean(false)},
    {"John", "Doe",
     "Rowing", new Integer(3), new Boolean(true)},
    {"Sue", "Black",
     "Knitting", new Integer(2), new Boolean(false)},
    {"Jane", "White",
     "Speed reading", new Integer(20), new Boolean(true)},
    {"Joe", "Brown",
     "Pool", new Integer(10), new Boolean(false)}
    };

    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);

    if (DEBUG) {
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                printDebugData(table);
            }
        });
    }

    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    //Add the scroll pane to this panel.
    add(scrollPane);
}

private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();

    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
        System.out.print("    row " + i + ":");
        for (int j=0; j < numCols; j++) {
            System.out.print("  " + model.getValueAt(i, j));
        }
        System.out.println();
    }
    System.out.println("--------------------------");
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("SimpleTableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    SimpleTableDemo newContentPane = new SimpleTableDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}
7
  • I'm having a hard time understanding what the problem is. Touching up your English will help you get a better answer faster.
    – Scruffy
    Apr 21, 2015 at 5:49
  • Create a new TableModel with the data you need Apr 21, 2015 at 5:51
  • Object[][] data = { {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)}, {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)}, {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)}, {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)}, {"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)} }; i dont want to pass object[][] instead of this i want to give one name which should access from file like ResourceBundle bundle2 = ResourceBundle.getBundle("resources//config");
    – jagan
    Apr 21, 2015 at 5:56
  • Should we assume you know how to reference a resource and read it? Apr 21, 2015 at 6:00
  • receiver = receiver entity = entity businessReferenceId = business Reference Id flowUserId = flowUserId securityCode = security Code
    – jagan
    Apr 21, 2015 at 6:03

1 Answer 1

0

If I understood question correct, you can replace Object[][] data with something like this:

    String line;
    ArrayList<String[]> toData = new ArrayList<String[]>();
    File file = new File("\\file path");
    try{
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while ((line = reader.readLine()) != null) {
            String[] lineElements = line.split(",");
            toData.add(lineElements);
        }
    }catch (Exception ex){
        ex.printStackTrace();
        System.out.println("File not found");
    }
    String[][] data = new String[toData.size()][];
    int index = 0;
    for(String[] a: toData){
        data[index]=a;
        index++;
    }

In this exemple, it will work if data in file is formatted as: name, surname, sportage, is Vegetarian. However you can change that easily, but remember to also change symbol in brackets in line.split().

EDIT: I don't fully understand what you want to achieve, however I would do it like this:

import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.ArrayList; public class Project { private JScrollPane scrollPane; private JFrame frame; private JTable table; public static void main (String[] args){ Project project = new Project(); project.createGUI(); } public void createGUI(){ frame = new JFrame(); scrollPane = new JScrollPane(); JPanel panel = new JPanel(); JButton open = new JButton("Open"); open.addActionListener(new OpenListener()); JButton submit = new JButton("Submit"); submit.addActionListener(new SubmitListener()); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new CancelListener()); panel.add(open); panel.add(submit); panel.add(cancel); frame.getContentPane().add(BorderLayout.CENTER,scrollPane); frame.getContentPane().add(BorderLayout.SOUTH,panel); frame.setSize(500,500); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } public void createAndDisplayList(String[][] data){ String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"}; table = new JTable(data, columnNames); frame.setVisible(false); frame.remove(scrollPane); scrollPane = new JScrollPane(table); frame.getContentPane().add(BorderLayout.CENTER,scrollPane); frame.revalidate(); frame.setVisible(true); } private class OpenListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); String line; ArrayList<String[]> toData = new ArrayList<String[]>(); fileChooser.showOpenDialog(frame); try{ BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile())); while ((line = reader.readLine()) != null) { String[] lineElements = line.split(","); toData.add(lineElements); } reader.close(); }catch (Exception ex){ ex.printStackTrace(); JOptionPane.showMessageDialog(frame, "File not found", "Error", JOptionPane.ERROR_MESSAGE); } String[][] data = new String[toData.size()][]; int index = 0; for(String[] a: toData){ data[index]=a; index++; } createAndDisplayList(data); } } private class CancelListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { frame.remove(scrollPane); scrollPane = new JScrollPane(); frame.getContentPane().add(BorderLayout.CENTER,scrollPane); frame.revalidate(); frame.setVisible(true); } } private class SubmitListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.showSaveDialog(frame); try{ BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile())); for(int i = 0; i<table.getRowCount(); i++){ for(int j = 0; j<table.getColumnCount(); j++){ System.out.println(i + "," + table.getRowCount()); bufferedWriter.write(table.getValueAt(i, j).toString() + ","); } bufferedWriter.newLine(); } bufferedWriter.close(); }catch (IOException ex){ ex.printStackTrace(); JOptionPane.showMessageDialog(frame,"File not found","Error",JOptionPane.ERROR_MESSAGE); } } } }

However be aware it is a primitive and amateur written code, but it works to some extent. You can open, change content and save file(submit), but you cannot add rows in table, you need to do it in .txt file (but you cannot leave any empty space at the end of file). Anyway, I hope you will find something usufull here.

3
  • how could you please add submit and cancel buttons in the above program so that when run the program output Jframe window should contain jscroll and submit and cancel button should exist.by that we can scroll and check all the key values and submit and cancel/
    – jagan
    Apr 22, 2015 at 10:52
  • Hi in the above code is absolutely working fine but JTable used , is it possible to impliment in JTableModel so that we can add more properties?
    – jagan
    May 19, 2015 at 4:26
  • @jagan it is possible, but it is beyond the scope of this question, so I think, to avoid mess, you should post new question - how to implement JTableModel to get desired properties. By the way, if my answer was useful for you, please consider upvoting or accepting it. But of course, if you don't want, you don't need to.
    – m.cekiera
    May 19, 2015 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.