问题
Now that I managed to put the objects from a file into a ArrayList
, I have to display them into a JTable
.
These are the 3 objects contained in my ArrayList
Lieu<Double, String>(45.573715, -73.900295, "p1");
Lieu<Double, String>(45.573882, -73.899748, "p2");
Lieu<Double, String>(45.574438, -73.900099, "p3");
In the Lieu
class I have the methods getX()
and getY()
But I can't figure out how to diplay them in a JTable
.
Longitude Latitude
45.573715 -73.900295
45.573882 -73.899748
45.574438 -73.900099
Here's what I have for a start:
public class MonModel extends AbstractTableModel{
@Override
public int getColumnCount() {
return 2;
}
@Override
public int getRowCount() {
return l.size();//l is the arraylist that contains the 3 elements
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(columnIndex==0){
return l.get(rowIndex).getX();
}
else if(columnIndex==1){
return l.get(rowIndex).getY();
}
return null;
}
回答1:
Use your TableModel
to create a JTable
and add it to a JFrame
. Also consider overriding getColumnName()
, as shown here. See also How to Use Tables.
MonModel model = new MonModel();
JTable table = new JTable(model);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(table), BorderLayout.CENTER);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
回答2:
Use a TableModel
for showing data in the JTable
. For Example:
In UI class, set the table model to the table.
JTable table = new JTable(new MonModel());
Table Model class
class MonModel extends AbstractTableModel {
private List<LatNLon> l;
private String[] columnNames = {"Longitude", "Latitude"};
public MonModel() {
l = new ArrayList<LatNLon>();
l.add(new LatNLon("45.573715", "-73.900295"));
l.add(new LatNLon("45.573715", "-73.900295"));
l.add(new LatNLon("45.573715", "-73.900295"));
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return l.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
if(columnIndex==0){
return l.get(rowIndex).getX();
}
else if(columnIndex==1){
return l.get(rowIndex).getY();
}
return null;
}
}
Latitude and Longitude class.
class LatNLon {
private String x;
private String y;
public LatNLon(String x, String y) {
this.x = x;
this.y = y;
}
// Code: For Getters and Setters.
}
Also read How to use Tables.
来源:https://stackoverflow.com/questions/15956187/create-jtable-from-arraylist