2016-06-30 1 views
0

질문으로, 나는 텍스트 파일이있다. 그 텍스트 파일 안에 몇 줄의 텍스트가 있습니다. JFrame이 시작될 때 textArea에 해당 데이터를 채우고 싶습니다. 내가 사방 보았다 아무것도 발견하지 오전 non-static variable resultBox cannot be referenced from a static context.JFrame의 textArea를 파일의 데이터로 설정 하시겠습니까?

말하는대로

public static void main(String args[]) throws IOException { 

    FileReader reader = new FileReader("C:/filepathchangedforStackOverflow"); 
    BufferedReader br = new BufferedReader(reader); 
    resultBox.read(br, null); 
    br.close(); 

     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new RemoteDesktop().setVisible(true); 

      } 
     }); 
    } 

오류가 resultBox.read(br, null);에 있습니다. 그것은 충분히 간단하게 보입니다. 왜 작동하지 않는지 모르겠습니다.

+0

공유 할 변수 선언을? –

+0

private javax.swing.JTextArea resultBox; –

답변

1

이 시도 :`resultBox`의

클래스 홈페이지

{

static JFrame frame=new JFrame(); 
static JPanel panel=new JPanel(); 
private static void display(JFrame frame) throws IOException 
    { 
     JFileChooser chooser = new JFileChooser(); 
     int returnVal = chooser.showOpenDialog(null); 
     File file = null; 
     if(returnVal == JFileChooser.APPROVE_OPTION)  
     file = chooser.getSelectedFile();  
     JTextArea text = new JTextArea(); 
     BufferedReader in = new BufferedReader(new FileReader(file)); 
     String line = in.readLine(); 
     while(line != null) 
      { 
       text.append(line + "\n"); 
       line = in.readLine(); 
      } 
     panel.add(text); 
     frame.add(panel); 
    } 
public static void main(String args[]) throws IOException 
{ 
    frame. setTitle("Simple example"); 
    frame.setSize(500, 500); 
    display(frame); 
    frame.setVisible(true); 
} 

}

1

변수 resultBox을 포함하는 클래스의 개체를 만들어야합니다. 이제 클래스 객체의 참조 변수를 사용하여 resultBox 변수에 액세스하십시오. 예를 들어 클래스 이름은, Test 경우 :

Test test=new Test();

test.resultBox.read (br, null);

당신은 아래에 언급 된 단계를 수행하고 그 결과를 참조하십시오 수 :

1 단계 : 그 경로 텍스트 파일을 만듭니다 : "D:\\test.txt"

2 단계 : public static void main(String args[])을 다음으로 바꿉니다.

public static void main(String[] args) throws IOException {  
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       RemoteDesktop rd=new RemoteDesktop(); 
       FileReader fr=null; 
       try { 
        fr = new FileReader("D:\\test.txt"); 
        rd.resultBox.read(fr, "Test"); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       }finally{ 
        if(fr!=null){ 
         try { 
          fr.close(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
       rd.setSize(600, 400); 
       rd.setLocationRelativeTo(null); 
       rd.setVisible(true); 
      } 
     }); 
    } 
+0

어디서든 resultBox를 선언하지 않았습니다. 간단히 NetBeans의 디자인 뷰를 사용하여 컨트롤을 폼으로 드래그했습니다. –

+0

내 수정 된 답변을 참조하십시오. –

+0

이것은 내 오류를 수정했습니다! 감사합니다 (추신은 여전히 ​​데이터를 표시하지 않지만 다른 문제 일 수 있습니다) –

관련 문제