Reputation: 25048
I have a main.java
that has a button, when you press it, it calls a method and retuns an ArrayList of Nodes;
I want to display the ArrayList in a table ( 5 fields as described in class Node)
How to do that, The problem is to display some fields as they are List type?
Node.java
public class Node {
private String name;
private double value;
private List<Node> first;
private List<Node> second;
private List<Double> values;
//some methods...
}
main.java
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Red Bayesiana Visita a Asia ");
JPanel panel = new JPanel();
boton = new Button( "Get");
panel.add(boton);
frame.add(panel);
ArrayList<Node> arrayList;
boton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
arrayList = method("file.txt");
//insert into table arrayList of 5 fields?
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Upvotes: 2
Views: 7160
Reputation: 205785
As discussed in Creating a Table Model, let Nodes
extend AbstractTableModel
and implement the required methods. Use the resulting model to create your JTable
.
Addendum: Here's an outline of the model. The fields name
and value
can use the default renderer, but you'll have decide how to render the List
s found in each Node
.
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/** @see http://stackoverflow.com/questions/5438516 */
public class Nodes extends AbstractTableModel {
private List<Node> nodes = new ArrayList<Node>();
@Override
public int getRowCount() {
return nodes.size();
}
@Override
public int getColumnCount() {
return 5; // A Node has five members
}
@Override
public Object getValueAt(int row, int col) {
Node node = nodes.get(row);
switch (col) {
case 0:
return node.name;
case 1:
return node.value;
case 2:
return node.first;
case 3:
return node.second;
case 4:
return node.values;
default:
return null;
}
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
private class Node {
private String name;
private double value;
private List<Node> first;
private List<Node> second;
private List<Double> values;
}
}
Upvotes: 4