我有一个JTable。当用户选择列时,想法是将浮点数据添加到ArrayList。我稍后会尝试在arrayList上做一些统计数据。
目前我正在设法将所需数据添加到ArrayList,并且当我从侦听器中打印到控制台时可以看到数据。但是,即使从侦听器外部声明ArrayList,数据也无法从侦听器外部获得。
TableColumnModel columnModelCompareL = table_CompareL.getColumnModel();
ArrayList<Float> statsCompareL=new ArrayList<Float>();
columnModelCompareL.addColumnModelListener(new TableColumnModelListener() {
public void columnSelectionChanged(ListSelectionEvent e) {
Object[] data = columnToArray(table_CompareL,table_CompareL.getSelectedColumn());
System.out.println("MY data length"+data.length);
try {
for(int i = 0; i < data.length; i++){
if (data[i]!=null){
try {
statsCompareL.add(Float.parseFloat((data[i]).toString().trim()));
} catch (Exception e1) {
System.out.println("nought to add here");
}
}
}
} catch (NumberFormatException e1) {
System.out.println("You haven't selected a numeric column. Please select again");
}
}
@Override
public void columnAdded(TableColumnModelEvent e) {
}
@Override
public void columnRemoved(TableColumnModelEvent e) {
}
@Override
public void columnMoved(TableColumnModelEvent e) {
}
@Override
public void columnMarginChanged(ChangeEvent e) {
}
});
System.out.println("statsCompareL"+statsCompareL);
答案 0 :(得分:1)
更新的ArrayList在UI构造代码中不可见(因为此代码在更新ArrayList之前很久就结束了。)
但是在其他事件监听器中可用:
TableColumnModel columnModelCompareL = table_CompareL.getColumnModel();
ArrayList<Float> statsCompareL=new ArrayList<Float>();
columnModelCompareL.addColumnModelListener(new TableColumnModelListener() {
// implementation left out for brevity
});
// this runs during construction time, long before statsCompareL is updated
System.out.println("statsCompareL"+statsCompareL);
JButton testButton = new JButton("Test ArrayList");
testButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// this runs after the button is clicked, so it will see the changes statsCompareL
System.out.println("statsCompareL"+statsCompareL);
}
});
// add the button somewhere convenient for testing purposes