0

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")}; 

}

}
  • 6
    Step 1: **don't swallow exceptions**. At least print them out. – Mat Sep 22 '13 at 08:56
  • @Mat Great advice, but I prefer (explicitly) the stacktrace on the basis that is gives excellent detail. OP - Change code of the form `catch (Exception e) { ..` to `catch (Exception e) { e.printStackTrace(); // very informative! ..` – Andrew Thompson Sep 22 '13 at 09:03
  • ook, i get the first 2 errors. But I have no idea why :( – user2707860 Sep 22 '13 at 09:04
  • General advice: 1) For frame positioning, you cannot go by `setLocationByPlatform(true)`. See [this answer](http://stackoverflow.com/a/7143398/418556) for demo. 2) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). .. – Andrew Thompson Sep 22 '13 at 09:05
  • .. 3) Don't set the size of top level containers. Instead layout the content & call `pack()`. 4) **Always copy/paste error & exception output.** Add it as an [edit to the question](http://stackoverflow.com/posts/18942013/edit). – Andrew Thompson Sep 22 '13 at 09:06
  • ok, I will take all this advice into consideration from now on.... but is this the reason why it doesn't work? Really, right now I'm just struggling to do what they tried to teach me in class and failed. – user2707860 Sep 22 '13 at 09:14
  • The file is already closed by the time the `ActionListener` is called. – Mattias Buelens Sep 22 '13 at 09:17
  • 1) *"why it doesn't work?"* Why you don't follow my advice in **bold** in point (4) above? Then I might have a snowball's chance in Hades of telling you why. 2) Tip: Add @Mat (or whoever, the `@` is important) to *notify* them of a new comment. – Andrew Thompson Sep 22 '13 at 09:29

3 Answers3

0

The problem is that the stream you define get closed in try block. So when you try to read it gives Stream is closed.

Ragavan
  • 997
  • 7
  • 11
0

1、data can not be shared,bf in the click event does not get to the

final BufferedReader bf = b; 

2、Code is modified as follows to achieve your results

public static void main(String[] args) {
    final MyApp m = new MyApp();
    m.button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            File f = new File("C:\\myfile.txt");
            BufferedReader b = new BufferedReader(new InputStreamReader(
                    System.in));
            try {
                b = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ee) {
            }

            String s = new String();
            try {
                while ((s = b.readLine()) != null) {
                    m.afisaj.append(s);
                }
                b.close();
            } catch (Exception ee) {
            }
        }
    });
}
sunysen
  • 2,265
  • 1
  • 12
  • 13
0

You should close the stream, when you close the window. Now you close it after you registered the event listener for the button. And before you really press the button.

public static void main(String[] args) throws Exception {
  final MyApp m = new MyApp();

  File f = new File("myfile.txt");
  BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
  b = new BufferedReader(new FileReader(f));

  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 ex) {
        throw new RuntimeException(ex);
      }
    }
  });

  m.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
      try {
        bf.close();
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
  });
}

And please stop swalowing exception. System wouls have told you, that stream is closed and the rest is very simple, once you have that information!

Bernd Ebertz
  • 1,317
  • 8
  • 10