我正在尝试将PrintWrite数据写入文件,但只创建java文件而不编写任何数据。
数据存储在ArrayList中,我认为这个问题是因为sData.size()方法。当用户点击保存图标时,使用操作方法部分,表格将没有任何数据。用户单击该按钮可将数据添加到Jtable。
末尾的部分代码会显示错误消息java.lang.NullPointerException
。
public class ee extends JFrame {
String[] columnNames = {"#", "c1", "c2", "data column"};
public final JTable table;
JToolBar toolBar;
private final JTextField enterText,startTime,endTime;
static DefaultTableModel cModel ;
JButton Obutton;
int counter = 1;
public static ArrayList<String> sData = new ArrayList<String>();
public static ArrayList<String> eData = new ArrayList<String>();
public static ArrayList<String> tData = new ArrayList<String>();
public static void main(String[] args) throws IOException
{
ee is = new ee("iss");
}
//the constrictor
public ee(String title){
cModel =new DefaultTableModel(columnNames, 0);
table = new JTable(cModel);
行动方法
Action saveAction = new AbstractAction("Save", saveIcon) {
@Override
public void actionPerformed(ActionEvent e) {
File myFile = new File("the-file-name.txt");
try (PrintWriter writer = new PrintWriter(myFile)) {
for (int i =0 ; i< sData.size(); i++)
{
writer.println(i+1 + "\n");
writer.println(sData.get(i)+" --> " + eData.get(i));
writer.println(tData.get(i)+"\n");
}
}catch(FileNotFoundException ioEx){
}
}
};
}
从JTable获取数据并将其保存到ArrayList
public static ArrayList<String> getTableSTimeData(){
sData = new ArrayList<String>();
for (int i=0; i < cModel.getRowCount(); i++){
Object val = cModel.getValueAt(i, 1); // value of ith row and 3rd column
sData.add((String) val);
}
return sData;
}
数据插入JTable的方式
public class MenuBarMethod implements ActionListener{
@Override
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(Obutton)){
String STime = startTime.getText();
String ETime = endTime.getText();
String text = enterText.getText();
clearEntity();
cModel.addRow(new Object[] {getCounter(),STime, ETime, text});
}
}
}
}
答案 0 :(得分:0)
在声明时初始化ArrayList
以避免NullPointerException
public class ee extends JFrame {
...
public static List<String> sData = new ArrayList<String>();
public static List<String> eData = new ArrayList<String>();
public static List<String> tData = new ArrayList<String>();
...
}