본문 바로가기

나는 엔지니어/JAVA

JAVA FILE 읽기 ( 파일 오픈 / 텍스트 에리어 )

public class FileReadMain 

{

public static void main(String[] args) 

{

// TODO Auto-generated method stub

CreateFrame cf = new CreateFrame();

}


}


public class CreateFrame 

{

private JFrame frm;

public CreateFrame()

{

this.frm = new JFrame();

this.createLayOut();

}

private void createLayOut()

{

this.frm.setBounds(100, 100, 700, 500);

this.frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//this.frm.setLayout(new FlowLayout());

JPanel pBase = new JPanel();

JPanel p1 = new JPanel();

JPanel p2 = new JPanel();

p1.setLayout(new BoxLayout(p1,BoxLayout.X_AXIS));

JTextField txt1 = new JTextField(null,20);

JButton btn = new JButton("SEARCH");

JTextArea textarea = new JTextArea("JTextArea");

//textarea.setLineWrap(true);

   JScrollPane scrollpane = new JScrollPane(textarea);

   scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

   scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

   ActionListener li = new ActionEventHandler(txt1,textarea);

btn.addActionListener(li);

p1.add(txt1);

p1.add(btn);

this.frm.add(p1,BorderLayout.NORTH);

this.frm.add(scrollpane,BorderLayout.CENTER);

this.frm.setVisible(true);

//this.frm.pack();

}

}



public class ActionEventHandler implements ActionListener 

{

private JTextField txt1;

private JTextArea textarea;


public ActionEventHandler(JTextField txt1,JTextArea textarea )

{

this.txt1 = txt1;

this.textarea = textarea;

}


@Override

public void actionPerformed(ActionEvent e) 

{

// TODO Auto-generated method stub

FileSearch fs = new FileSearch();

String fileFullName = fs.getFileFullName(); 

this.txt1.setText(fileFullName);


File f = new File(txt1.getText());

Scanner s;

try 

{

s = new Scanner(f);

while(s.hasNext())

{

textarea.append(s.nextLine()+"\n");

}

catch (FileNotFoundException e1) 

{

// TODO Auto-generated catch block

e1.printStackTrace();

}


}


}


public class FileSearch extends JFrame

{

private static final long serialVersionUID = 1L;


public String getFileFullName()

{

FileDialog fd = new FileDialog(this,"File Open", FileDialog.LOAD);

fd.setVisible(true);

return fd.getDirectory() + fd.getFile();

}

}