如何将值列表从表导入到字符串行

时间:2016-10-26 19:43:18

标签: java arrays string netbeans jtable

我在java中创建了一个包含一列和多行的表,我还有一个String行,我想在我的字符串行中导入我的值列表: 我运行了我的代码,结果如下:

begining of line [item1] end of line
begining of line [item2] end of line
begining of line [item3] end of line
begining of line [item4] end of line

但我正在寻找这样的结果:

begining of line    [item1], 
                    [item2], 
                    [item3],
                    [item4]   end of line

my table

这是我的代码:

DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
for (int i=0;i<model.getRowCount();i++){
        String b = " ["+(jTable1.getValueAt(i,0)).toString()+"] ";

        String text="begining of line"+b+"end of line";
    System.out.println(text);
}

我是java新手感谢

2 个答案:

答案 0 :(得分:0)

你可以在for循环之前启动文本for循环,在for循环中添加项目到文本,并在for循环之后添加“end of line”。您可以使用+运算符来连接字符串,或者如果您想要高效,可以使用Stringbuilder类。

答案 1 :(得分:0)

试试这段代码:

    String beginning= "beginning of line";
    String emptySpaces = new String(new char[begining.length()]).replace("\0", " "); // Create empty spaces with the same length of the begining sentence
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < model.getRowCount(); i++) {
        final String first = (i == 0) ? begining : emptySpaces;
        builder.append(first).append(" [").append(jTable1.getValueAt(i,0).toString()).append("]");
        final String last = (i == model.getRowCount() - 1) ? " end of line" : ",\n";
        builder.append(last);
    }
    System.out.println(builder.toString());

我使用字符串构建器来避免字符串创建性能问题

它会显示预期的结果

beginning of line [item1],
                  [item2],
                  [item3],
                  [item4],
                  [item5] end of line