我想將PrintWrite數據寫入文件,但java只創建文件而沒有寫入任何數據。爲什麼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});
}
}
}
}
'getTableSTimeData()'方法永遠不會被調用,因此'sData'爲'null'。 – Braj
查看註釋和代碼'Object val = cModel.getValueAt(i,1); //第i行第3列的值# – Braj
請發佈完整的代碼,以便我們可以運行它來解決問題。 – Braj