Question

I have a program that using JSCH runs a command on a server and get the following results out

   rcpt  7554   Jan-21 01-03:43:27       ? /usr/bin/Program
ncuser2  7202   Jan-21 01-04:22:08       ? /usr/bin/Program
    lyn  6277   Dec-17 36-02:14:51       ? /usr/bin/Program 10.15.1.104:0.0
    lyn  6268   Dec-17 36-02:15:17       ? /usr/bin/Program 10.15.1.104:0.0

These results are stored in one string.

What I need to do is convert/Output these results into a JTable.

What I cant work out is how to get what's in the single string above into multiple cells of a JTable in Swing so it looks like this

  User | PID | Launch | Runtime    | TTYP | Program |
  -----------------------------------------------
  rcpt | 7554| Jan-21 |01-03:43:27 | ?    |/usr/bin/Program
ncuser2| 7202| Jan-21 |01-04:22:08 | ?    |/usr/bin/Program
    lyn| 6277| Dec-17 |36-02:14:51 | ?    |/usr/bin/Program 10.15.1.104:0.0
    lyn| 6268| Dec-17 |36-02:15:17 | ?    |/usr/bin/Program 10.15.1.104:0.0

The main issue I am having is finding a way of splitting the string, I want to do it on space, looking at this. Even if I could split it into variables for every space I could possibly work it out but at the moment I don't have a clue!

Was it helpful?

Solution

You can achieve it as below :

public static void main(String[] args) {

        String dataStr = "rcpt  7554   Jan-21 01-03:43:27       ? /usr/bin/Program\n"
                + "ncuser2  7202   Jan-21 01-04:22:08       ? /usr/bin/Program\n"
                + "lyn  6277   Dec-17 36-02:14:51       ? /usr/bin/Program 10.15.1.104:0.0\n"
                + "lyn  6268   Dec-17 36-02:15:17       ? /usr/bin/Program 10.15.1.104:0.0\n";

        String rows[] = dataStr.split("\n");


        Vector<Vector<String>> dataVector = new Vector<Vector<String>>();
        for (String row : rows) {
            row = row.trim();  //UPDATE
            Vector<String> data = new Vector<String>();
            data.addAll(Arrays.asList(row.split("\\s+")));
            dataVector.add(data);
        }

        Vector<String> header = new Vector<String>(2);
        header.add("User");
        header.add("PID");
        header.add("Launch");
        header.add("Runtime");
        header.add("TTYP");
        header.add("Program");

        TableModel model = new DefaultTableModel(dataVector, header);
        JTable table = new JTable(model);

        JFrame frame = new JFrame("DemoFrame");
        frame.add(new JScrollPane(table));
        frame.setSize(300, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

OUTPUT

enter image description here

OTHER TIPS

  1. split("\n") for the lines
  2. split("\s+") for the cells
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top