从外部文件获取并显示在JTable中

时间:2015-04-21 05:46:11

标签: java swing jtable

有人可以告诉我如何修改以下程序吗?程序的数据由object[][]传递 - 而不是只提供文件名,其中的数据应该打印在表格中。

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();
        }
    });
}
}

1 个答案:

答案 0 :(得分:0)

如果我理解问题是正确的,您可以用以下内容替换Object [] []数据:

    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++;
    }

在这个例子中,如果文件中的数据格式为: 姓,姓,运动员,素食主义者。但是,您可以轻松地更改它,但请记住也要更改line.split()中括号中的符号。

编辑: 我不完全明白你想要达到的目标,但我会这样做:

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); } } } }

但请注意,它是一个原始的和业余的编写代码,但它在某种程度上有效。您可以打开,更改内容和保存文件(提交),但不能在表中添加行,您需要在.txt文件中执行此操作(但不能在文件末尾留下任何空白空间)。 无论如何,我希望你能在这里找到一些有用的东西。