java - 如何在 JTable 的行中设置文本?

标签 java swing jtable

我正在尝试用 java JFrame 制作一个带有表格的程序。 我想保存行中的文本。 我将文本放入文本文件中并且可以正常工作。

但我想将文本文件中的文本放入我的表中。 我尝试了很多事情,但没有任何效果。 有人可以帮忙吗?

最佳答案

“假设”,如果您将文本逐行存储在文件中,例如如下所示:

测试仪.txt:

Star Wars
Star Trek
The Lord of The Rings

然后您可以逐行读取它,当您读取足够的行时,向表格中添加一行。为了向现有表添加一行,我相信您确实需要使用模型,或者如果从新鲜创建,请预先准备数据,然后创建。下面是使用上述 txt 文件的一个粗略示例:

public class SO {
public static void main(String[] args) {

    //Desktop
    Path path = Paths.get(System.getProperty("user.home"), "Desktop", "tester.txt");

    //Reader        
    try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
        Vector<String> row = new Vector<String>();

        //Add lines of file
        int numOfCellsInRow = 3; //Num of cells we want
        int count = 0;
        while (count < numOfCellsInRow){
                row.addElement(reader.readLine());
                count++;
        }

        //Column names
         Vector<String> columnNames = new Vector<String>();
         columnNames.addElement("Column One");
         columnNames.addElement("Column Two");
         columnNames.addElement("Column Three");  

         Vector<Vector<String>> rowData = new Vector<Vector<String>>();
         rowData.addElement(row);

         //Make table
         JTable table = new JTable(rowData, columnNames);

         //How you could add another row by drawing more text from the file,
         //here I have just used Strings
         //Source: http://stackoverflow.com/questions/3549206/how-to-add-row-in-jtable
         DefaultTableModel model = (DefaultTableModel) table.getModel();
         model.addRow(new Object[]{"Darth Vader", "Khan", "Sauron"});

         //Make JFrame and add table to it, then display JFrame
         JFrame frame = new JFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         JScrollPane scrollPane = new JScrollPane(table);
         frame.add(scrollPane, BorderLayout.CENTER);
         frame.pack();
         frame.setVisible(true);

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

有两件事需要注意,首先我使用了 vector ,但由于我认为速度问题,不鼓励使用 vector ,因此您可能需要考虑对这些进行改变。第二个也是主要问题是文件中的文本。只有知道您打算如何存储文本,我们才能知道如何将其成功读回到表中。希望这个例子能为您指明正确的方向。

编辑

关于您重新发布的代码,首先我将其定为最终的:

final Path path = Paths.get(System.getProperty("user.home"), "Desktop", "File.txt");

然后更改您的监听器方法,以通过单击“保存”按钮根据您创建的文件获取文本输入:

  btnGetFile.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) 
    {
        //This prevents exception
        if(!Files.exists(path)){//If no file
            JOptionPane.showMessageDialog(null, "File does not exist!");//MSg
            return;//End method
        }
        /*changed this bit so that it reads the data and 
         * should then add the rows
         */
        try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))){
            String line;
            while((line = reader.readLine()) != null){//Chek for data, reafLine gets first line 
                Vector<String> row = new Vector<String>();//New Row
                row.addElement(line);//Add first line
                  int numOfCellsInRow = 3; //Num of cells we want
                  int count = 0;
                  //We only want 2 because we got the first element at loop start
                  while (count < (numOfCellsInRow - 1)){
                      row.addElement(reader.readLine());
                      count++;
                  }
                  model.addRow(row);//Add rows from file
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }  
    }
});

添加了评论以尝试解释正在发生的事情。

它通过将文件中的行添加到 JTable 来为我工作。希望它现在也适合您!

关于java - 如何在 JTable 的行中设置文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991190/

相关文章:

java - JTable 不显示输出

java - 如何在 Java 中使用 dcm4che3 创建 DICOM MWL 查询?

java - 如何生成与 JLabel 标签相同的文本图像?

java - 我怎样才能让这个 JButton 工作

java - 当 setResizable 为 false 时,窗口在 JFrame 上的 setSize 之后移动

java - 如何在 JTable 中排除自动调整大小的列

java - JTable 构造函数可以接受数组以外的其他数据结构吗?

java - 如何测试 spring-security-oauth2 资源服务器安全性?

java - 在线程中访问类级别变量

Java 游戏无法运行