Lösung Übung 18: Einfacher Text-Viewer

 
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class SimpleTextViewer extends Frame {

	protected TextField dateiFeld;
	protected Button ladeButton;
	protected TextArea textFeld;
	
	public SimpleTextViewer() {

		this.setLayout( new BorderLayout() );
		
		Panel p = new Panel();
		//p.setLayout( new GridLayout(1,3) );
		
		Label prompt = new Label("Datei: ");
		dateiFeld = new TextField(30);
		ladeButton = new Button( "Öffnen" );
		ladeButton.addActionListener( new LadeButtonListener() );
		
		textFeld = new TextArea( 25, 2 );
		
		p.add(prompt);
		p.add(dateiFeld);
		p.add(ladeButton);
		
		add( p, BorderLayout.NORTH );
		add(textFeld, BorderLayout.CENTER );
		
		this.addWindowListener(
			new WindowAdapter() {
				// Bei Programmexit-Event beende Programm
				public void windowClosing(WindowEvent e) {
					System.exit(0);
				}
			}
		);

		this.setSize(600,400);
		this.setVisible( true );
	}

	public static void main( String[] args ) {
		new SimpleTextViewer();
	}		

	class LadeButtonListener implements ActionListener {
		public void actionPerformed( ActionEvent e ) {
		
			String dateiName = dateiFeld.getText();
			
			try {
				BufferedReader inputDatei = new BufferedReader( new FileReader(dateiName) );
		
				try {
					while( true ) {
						String line = inputDatei.readLine();	
						
						if( line == null )
							break;
						textFeld.append( line + "\n");	
					}
					
					inputDatei.close();
				}
				catch( IOException ex2 ) {
				}	
			}
			catch( FileNotFoundException ex ) {
				textFeld.setText("Fehler: Datei kann nicht geöffnet werden.");
			}			
		}
			
	}
	
}

																		    		
															
[Index]