Home > Enterprise >  How do you create a JTable from multiple ArrayLists?
How do you create a JTable from multiple ArrayLists?

Time:09-17

ArrayList<String> mediaCompany = new ArrayList<String>();
ArrayList<Double> rank = new ArrayList<Double>();

// SAMPLE CODE
static void displayTable(ArrayList<String> mediaCompany, ArrayList<Double> rank) {

        // ADD TABLE
        String [] columnNames = {"Media Platform", "Ranking"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        JTable table = new JTable(model);

        for (int i = 0; i < mediaCompany.size(); i  ) {
            Object[] row = {mediaCompany.get(i), rank.get(i)};
            model.addRow(row);
        }

    }

So I'm fairly new to Java and would like to learn how to create a table where the elements of someStringX are displayed in columns and x are displayed in rows on the console such that:

someStringX Value of X
someStringX x1
someStringX2 x2
someStringX3 x3
someStringX4 x4
... ...

Example: mediaCompany = [Facebook, Google, Twitter]

rank = [4, 7, 2]

mediaCompany rank
Facebook 4
Google 7
Twitter 2

So far I haven't been able to get JTable up and running despite importing the appropriate packages.

CodePudding user response:

Here is a sample code that will do what you need:

public static void main(String[] args) {
    List<String> mediaCompany = List.of("Facebook", "Google", "Twitter");
    List<Integer> rank = List.of(4, 7, 2);

    DefaultTableModel model = populateTableModel(mediaCompany, rank);
    createTable(model);
}

static DefaultTableModel populateTableModel(List<String> mediaCompany, List<Integer> rank) {
    String[] columnNames = { "Media Platform", "Ranking" };
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);

    for (int i = 0; i < mediaCompany.size(); i  ) {
        Object[] row = { mediaCompany.get(i), rank.get(i) };
        model.addRow(row);
    }

    return model;
}

static void createTable(DefaultTableModel model) {
    JFrame jFrame = new JFrame();
    JTable jTable = new JTable(model);
    JScrollPane sp = new JScrollPane(jTable);
    jFrame.add(sp);
    jFrame.setSize(300, 400);
    jFrame.setVisible(true);
}

I've used "List.of" to populate the lists, which is a Java 9 feature, you can populate them any other way.

The populateTableModel() method is responsible of retrieving the DefaultTableModel with all the column names and rows already populated.

The createTable() method will do the actual generation of the table.

  • Related