What I want to do is very basic: I have an interface that contains a button; when I push that button, I want my program to read the next line from a text file and display it in a textfield. But nothing happens, and I have a feeling it's because it doesn't read my file correctly :\ Please help, I'm a complete newbie in the Java world and I was even happy that I got rid of the compiler errors (yay me!) but this is worse, 'cause now I don't know what to google :))
package practice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MyApp extends JFrame {
JButton button;
JTextArea afisaj;
MyApp(){
setTitle("MyApp");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
setSize(500,500);
setLocationRelativeTo(null);
setVisible(true);
}
public void init(){
this.setLayout(null);
button = new JButton("Read more");
afisaj = new JTextArea();
button.setBounds(200,50,100,30);
add(button);
afisaj.setBounds(40,100,400,300);
add(afisaj);
}
public static void main(String[] args){
final MyApp m = new MyApp();
File f = new File("C:\\myfile.txt");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
try{
b = new BufferedReader(new FileReader(f));
}
catch (FileNotFoundException e){System.out.println("error 1")}
final BufferedReader bf = b;
m.button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = new String();
try{
if ((s=bf.readLine())!= null){
m.afisaj.append(s);
}
}
catch (Exception ee){System.out.println("error 2")}
}
});
try{
bf.close();
}
catch (Exception e1){System.out.println("error 3")};
}
}