2016-11-04 8 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());

関連する問題