View RSS Feed

fatabass

Reading a Files first line with a simple gui application

Rating: 1 votes, 1.00 average.
by , 01-15-2012 at 11:12 PM (1396 Views)
Java Code:
package myPackage;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class FileOrganizer extends JFrame implements ActionListener 
{
	public static final int WIDTH = 400;
	public static final int HEIGHT = 300;
	public static final int NUMBER_OF_CHAR = 30;
	
	private JTextField fileNameField;
	private JTextField firstLineField;
	
	public FileOrganizer()
	{
		setSize(WIDTH,HEIGHT);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		Container contentPane = getContentPane();
		contentPane.setLayout(new FlowLayout());
		
		JButton showButton = new JButton("Show first line");
		showButton.addActionListener(this);
		contentPane.add(showButton);
		
		this.fileNameField = new JTextField(NUMBER_OF_CHAR);
		contentPane.add(fileNameField);
		this.fileNameField.setText("Enter File Name Here");
		
		this.firstLineField = new JTextField(NUMBER_OF_CHAR);
		contentPane.add(firstLineField);
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		try 
		{
			showFirstLine();
		} 
		catch (FileNotFoundException e1) 
		{
			e1.printStackTrace();
		}
	}
	
	private void showFirstLine() throws FileNotFoundException
	{
		Scanner fileInput = null;
		String fileName = this.fileNameField.getText();
		
		File fileObject = new File(fileName);
		fileInput = new Scanner(fileObject);
		
		String firstLine = fileInput.nextLine();
		this.firstLineField.setText(firstLine);
		fileInput.close();
	}
	
	public static void main(String[] args) 
	{
		FileOrganizer f1 = new FileOrganizer();
		f1.setVisible(true);
	}

}

Submit "Reading a Files first line with a simple gui application" to Facebook Submit "Reading a Files first line with a simple gui application" to Digg Submit "Reading a Files first line with a simple gui application" to del.icio.us Submit "Reading a Files first line with a simple gui application" to StumbleUpon Submit "Reading a Files first line with a simple gui application" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments