2012-12-08 3 views
2

나는이 파일 읽기 및 텍스트 영역 자바에 표시

public class Names { 

    Scanner scan; 
    static String Firstname; 
    static String Surname; 
    static String Fullname; 

    public void OpenFile() 
    { 
     try 
     { 
      scan = new Scanner(new File("test.txt")); 
      System.out.println("File found!"); 
     } 

     catch(Exception e) 
     { 
      System.out.println("File not found"); 
     } 
    } 

    public void ReadFile() 
    { 
     while(scan.hasNext()) 
     { 
      Firstname = scan.next(); 
      Surname = scan.next(); 
      Fullname = Firstname + " " + Surname; 

      System.out.println(Fullname); 
     } 
    } 

    public void CloseFile() 
    { 
     scan.close(); 
    } 
} 

그럼 내가 이름 클래스를 호출이 주요 클래스가 잘 작동 테스트 파일에서 이름을 읽고 다음과 같은 코드입니다. 그것은 테스트 파일의 마지막 이름 만 보여주기 때문에 잘 작동합니다.

public class NameSwing implements ActionListener { 

    private JTextArea tf = new JTextArea(20,20); 
    private JFrame f = new JFrame("names"); 
    private JButton b = new JButton("view"); 

    static String fullName; 

    public NameSwing(){ 
     f.add(new JLabel("Name")); 
     tf.setEditable(true); 
     f.add(tf); 

     b.addActionListener(this); 
     f.add(b); 

     f.setLayout(new FlowLayout()); 
     f.setSize(300,100); 
     f.setVisible(true); 

    } 

    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     if(e.getSource()==b) 
     { 
      tf.setText(fullName); 
     } 
    }  

    public static void main(String[] args) throws FileNotFoundException, IOException { 
     NameSwing nameSwing = new NameSwing(); 

     Names t = new Names(); 
     t.OpenFile(); 
     t.ReadFile(); 
     t.CloseFile(); 

     fullName = Names.Fullname; 
    } 

} 

이것은 테스트 파일의 내용입니다.

닉 해리스

올리 딘

엠마 Sammons

헨리 블랙웰

나는 텍스트 영역이 독자로부터 모든 이름, 그냥 마지막으로하지를 보여주고받을 수있는 방법 이름?

답변

4

Names 클래스는 매우 유용하지는 않으며 정적 필드를 과도하게 사용하므로 이름 클래스를 버리십시오. 내 마음에 가장 좋은 방법은하는 것입니다

  • 가의 BufferedReader 객체를
  • 전화를 만들려면이 파일
  • 사용이 가진을 FileReader 객체를 생성 텍스트 파일
  • 을 보유 파일 만들기 JTextArea에의 read(...) BufferedReader에서 전달하는 메서드
  • 그리고 완료되었습니다.

즉,의 actionPerformed의 :

여기
BufferedRead buffReader = null; 
try { 
    File file = new File("test.txt"); 
    FileReader fileReader = new FileReader(file); 
    buffReader = new BufferedReader(fileReader); 
    tf.read(buffReader, "file.txt"); 
} catch (WhateverExceptionsNeedToBeCaught e) { 
    e.printStackTrace(); 
} finally { 
    // close your BufferedReader 
} 
1

당신이 변화를 여기

while(scan.hasNext()) 
     { 
      Firstname = scan.next(); 
      Surname = scan.next(); 
      //Assigning each time instead of append 
      Fullname = Firstname + " " + Surname; 
     } 

에게 필요가 완료 수정입니다 :

public class NameSwing implements ActionListener { 

    private JTextArea textArea = new JTextArea(20, 20); 
    private JFrame frame = new JFrame("Names"); 
    private JButton btnView = new JButton("View"); 
    private Scanner scanner; 
    private String firstName; 
    private String surName; 
    private String fullName; 

    public NameSwing() { 
     frame.add(new JLabel("Name")); 
     textArea.setEditable(true); 
     frame.add(textArea); 

     btnView.addActionListener(this); 
     frame.add(btnView); 

     frame.setLayout(new FlowLayout()); 
     frame.setSize(300, 100); 
     frame.setVisible(true); 

    } 

    public void OpenFile() { 
     try { 
      scanner = new Scanner(new File("test.txt")); 
      System.out.println("File found!"); 
     } catch (Exception e) { 
      System.out.println("File not found"); 
     } 
    } 

    public void ReadFile() { 
     while (scanner.hasNext()) { 
      firstName = scanner.next(); 
      surName = scanner.next(); 
      // assign first time 
      if(fullName == null) { 
       fullName = firstName + " " + surName; 
      } else { 
       fullName = fullName + "\n" + firstName + " " + surName; 
      } 

      System.out.println(fullName); 
     } 
    } 

    public void CloseFile() { 
     scanner.close(); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == btnView) { 
      textArea.setText(fullName); 
     } 
    } 

    public static void main(String[] args) throws FileNotFoundException, IOException { 
     NameSwing nameSwing = new NameSwing(); 
     nameSwing.OpenFile(); 
     nameSwing.ReadFile(); 
     nameSwing.CloseFile(); 
    } 
} 
1

문제는 줄입니다

,

Fullname = Firstname + " " + Surname;.

그것이

Fullname += Firstname + " " + Surname; + "\n"

당신의 문제가 해결되어 있는지 확인합니다 :)

2
  • 을 당신이 더 좋은 이유에 대한 너무 많은 정적 필드를 사용하고 있습니다. 클래스를 팩토리 클래스로 만들려는 경우 항상 정적 필드를 사용하십시오.이 경우 은 적합하지 않습니다.
  • 각 방법에 public Access Specifier을 제공함으로써 캡슐화의 근본적인 원칙을 깨고 있습니다.
  • setSize()을 호출하는 대신 pack()을 사용하면 지정한 임의의 값보다 훨씬 더 나은 방법으로 컨테이너의 크기를 결정할 수 있습니다.
  • Concurrency in Swing에 대해 읽어 보시기 바랍니다. 귀하의 지식은 약간 부족한 것으로 보입니다.
  • Java Naming Conventions를 배우십시오.
  • 또한 StringBuilder 클래스를 사용하여이 작업을 수행 할 수 있습니다. 수정 된 코드를 살펴보십시오. 당신의 이해를 넘어서는 것을 요구하십시오. 나는 그것에 대해 기꺼이 도와 드리겠습니다.

수정 된 코드 : 좋은 조언을

import java.io.*; 
import java.util.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class NameSwing implements ActionListener { 

    private Names t; 
    private JTextArea tf = new JTextArea(20,20); 
    private JFrame f = new JFrame("names"); 
    private JButton b = new JButton("view"); 

    public NameSwing(){ 

     performFileRelatedTask(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JPanel contentPane = new JPanel(); 
     contentPane.setLayout(new BorderLayout(5, 5)); 

     JScrollPane scroller = new JScrollPane(); 
     scroller.setBorder(BorderFactory.createLineBorder(Color.BLUE.darker(), 5)); 

     JPanel centerPanel = new JPanel(); 
     centerPanel.setLayout(new BorderLayout(5, 5)); 
     centerPanel.add(new JLabel("Name", JLabel.CENTER), BorderLayout.PAGE_START);   
     tf.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); 
     tf.setEditable(true); 
     centerPanel.add(tf, BorderLayout.CENTER); 
     scroller.setViewportView(centerPanel); 

     JPanel footerPanel = new JPanel(); 
     b.addActionListener(this); 
     footerPanel.add(b); 

     contentPane.add(scroller, BorderLayout.CENTER); 
     contentPane.add(footerPanel, BorderLayout.PAGE_END); 

     f.setContentPane(contentPane); 
     f.pack(); 
     f.setLocationByPlatform(true); 
     f.setVisible(true); 
    } 

    private void performFileRelatedTask() 
    { 
     t = new Names(); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     if(e.getSource()==b) 
     { 
      tf.setText(t.getFullNames().toString()); 
     } 
    }  

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

     SwingUtilities.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       new NameSwing(); 
      } 
     });     
    } 

} 

class Names { 

    private Scanner scan; 
    private String firstname; 
    private String surname; 
    private StringBuilder fullnames; 

    public Names() 
    { 
     fullnames = new StringBuilder(); 
     openFile(); 
     readFile(); 
     closeFile(); 
    } 

    public StringBuilder getFullNames() 
    { 
     return fullnames; 
    } 

    private void openFile() 
    { 
     try 
     { 
      scan = new Scanner(new File("test.txt")); 
      System.out.println("File found!"); 
     } 

     catch(Exception e) 
     { 
      System.out.println("File not found"); 
     } 
    } 

    private void readFile() 
    { 
     while(scan.hasNext()) 
     { 
      firstname = scan.next(); 
      surname = scan.next(); 
      fullnames.append(firstname + " " + surname + "\n"); 
     } 
    } 

    private void closeFile() 
    { 
     scan.close(); 
    } 
} 
+1

+1; 또, 새로운 JScrollPane (centerPanel)를 고려해, 주위의 컴퍼넌트에 보더를 추가해주세요. 스크롤 구획. – trashgod

+1

@trashgod : Ahha, 아이디어가 마음에 들었고 마찬가지로 업데이트되었습니다 .-) –