2016-11-04 30 views
-1

什麼問題?非靜態變量數據不能從靜態上下文中引用。我想從.dat文件加載數據,但我不知道該怎麼做?我嘗試過,但因爲之前的錯誤消息,它不起作用。感謝您的幫助。JTable,數據,非靜態方法

public class StudentFrame extends JFrame { 
    private StudentData data; 
    private static String[] columnNames = {"A","B","C","D"}; 
     private void initComponents() { 
      this.setLayout(new BorderLayout()); 

     } 
     @SuppressWarnings("unchecked") 
     public StudentFrame() { 
      super("Hallgatói nyilvántartás"); 
      setDefaultCloseOperation(EXIT_ON_CLOSE); 

      try { 
       data = new StudentData(); 
       ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat")); 
       data.students = (List<Student>)ois.readObject(); 
       ois.close(); 
      } catch(Exception ex) { 
       ex.printStackTrace(); 
      } 
      addWindowListener(new WindowAdapter() { 
       @Override 
       public void windowClosing(WindowEvent e) { 
        try { 
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students.dat")); 
         oos.writeObject(data.students); 
         oos.close(); 
        } catch(Exception ex) { 
         ex.printStackTrace(); 
        } 
       } 
      }); 
      setMinimumSize(new Dimension(500, 200)); 
      initComponents(); 
     } 
     public static void main(String[] args) { 
      StudentFrame sf = new StudentFrame(); 
      sf.setVisible(true); 


      sf.setLayout(new BorderLayout()); 


      JTable table = new JTable(data,columnNames);//PROBLEM 

      table.setFillsViewportHeight(true); 
      /*Jscroll...*/ 

      scrollPane.setViewportView(table); 
      sf.add(table.getTableHeader(), BorderLayout.PAGE_START); 
      sf.add(table, BorderLayout.CENTER); 
      sf.add(scrollPane, BorderLayout.LINE_END); 
      sf.setVisible(true); 

     } 
    } 
+1

嘗試:私有靜態StudentData數據;而不是:私人StudentData數據; – DevilsHnd

+0

請格式化您的問題,清楚您在哪一行上得到的編譯器錯誤。同時檢查https://stackoverflow.com/help/mcve ---更好的問題往往會得到更好的答案。 – Robert

回答

0

建議重構您的代碼並將主要方法的內容移動到您的StudentFrame類中。沒有真正的理由使用靜態變量,使TableData成爲StudentFrame的成員變量。只能從main方法實例化StudentFrame,設置框架並顯示它。如何顯示內容應該是StudentFrame類的一部分。

columnNames很好,因爲它是一個常數。

0

你StudentFrame私有成員變量需要公衆存取,然後你會引用它們的主要爲JTable table = new JTable(sf.getData(), StudentFrame.getColumnNames());