Hello people,

How can i display the JLabel text using external file.. When user click a button, a file is read and retrieve and will be displayed at the label.. what I did was:

1) Declare all the necessary file IO
2) use the useDelimiter() method to read the file contents (word is separated by coma)
3) display the text
4) while more taken, read next

been trying w/o success.... i tried several tutorial too.. but :-(

can anyone give me suggestion??

Dani AI

Generated

A few practical, robust patterns that build on and :

Keeping the reader open and iterating tokens is simplest. Re-opening the file/Scanner inside the ActionListener restarts reading from the top, which is why the Next button appeared not to advance. A safer approach is to load the questions once and step through them with an index; this also avoids IO on every click and makes end-of-file handling trivial.

private List<String> questions;
private int current = 0;

public MCQquestion() {
    try {
        questions = Files.readAllLines(Paths.get("question.txt"), StandardCharsets.UTF_8);
    } catch (IOException e) {
        questions = Collections.emptyList();
    }
    if (!questions.isEmpty()) lblQuestion.setText(questions.get(0));
}

private void nextQuestion() {
    if (current + 1 < questions.size()) lblQuestion.setText(questions.get(++current));
    else btnNext.setEnabled(false); // no more questions
}

Notes and cautions: initialize file readers inside the constructor (Scanner/FileReader constructors throw checked exceptions — that explains the "unreported exception" when declaring them at class scope without try/catch). If sticking with Scanner, test with hasNext()/hasNextLine() before next()/nextLine() and close the Scanner when finished (or use try-with-resources). Remember useDelimiter() takes a regex — for comma-separated data use "," or split the line; for more complex CSV use a CSV parser. For large files, do the load off the EDT (SwingWorker) and update the label on the EDT. Good that got it working — these patterns make the dialog more robust and easier to extend.

Recommended Answers

All 7 Replies

Show the actual code. The above "process" doesn't really tell us much. For example, what, exactly, is the "necessary file IO"? A FileInputStream, a FileReader, a Scanner? Is that wrapped in a BufferedWhatever? etc, etc.

Show the actual code. The above "process" doesn't really tell us much. For example, what, exactly, is the "necessary file IO"? A FileInputStream, a FileReader, a Scanner? Is that wrapped in a BufferedWhatever? etc, etc.

Thanks for the asap reply. Here is the code.

File questionFile =  new File ("question.txt");
Scanner questionInput = new Scanner (questionFile).useDelimiter("//");


String questions =  questionInput.nextLine();
lblQuestion.setText(questions); //set label text according token

This works well but the scenario is like this... once user answer the question, to proceed next questions, user must click Next button. So for this i added the actionListener. I coded the following..:

public void actionPerformed(ActionEvent nextbtn)
{
 Object source =  nextbtn.getSource();
    if(source==btnNext)
        {
            try
                {
                    File questionFile =  new File ("question.txt");
                    Scanner questionInput = new Scanner (questionFile).useDelimiter("//").next();

                    String questions = questionInput.nextLine();
                                    lblQuestion.setText(questions);
                    }


                    catch(IOException ioe)
                    {
                        System.out.print("IO Errors");
                    }

                }
}

I tried several methods already but still w/o success..what else did i miss?

Declare the scanner at the class level and do not re-open it in the listener. Let it use the one you have already opened.

Declare the scanner at the class level and do not re-open it in the listener. Let it use the one you have already opened.

Im not sure what do u mean by 'at class level'. Im totally new to Java...here is what I did:

lass MCQquestion extends JFrame implements ActionListener
{

    private static final int WIDTH=550;
    private static final int HEIGHT=200;
    private static final int HLOC=340;
    private static final int VLOC=290;
    private JPanel pnlQ, pnlA,pnlButton;
    private JLabel lblQuestion;
    private JFormattedTextField txtAnswer;
    private JButton btnNext;

    //Not Sure what u meant... Im totally new to Java..
    //but declaring it here, at class level generate 'unreported Exception' during compilation
    //where do i insert throw IOException
    //Try n catch dint work at class level..."invalid declaration.."

    File questionFile =  new File ("question.txt");

    Scanner questionInput = new Scanner (questionFile).useDelimiter("//");


    public MCQquestion()
    {

        lblQuestion =  new JLabel();


        try{
                        MaskFormatter ans = new MaskFormatter("U");
                        txtAnswer = new JFormattedTextField(ans);
                        txtAnswer.setPreferredSize(new Dimension(40,30));
                    }

         catch(ParseException pe)
         {
              System.out.println("Error: " + pe.getMessage());
         }

    .... the code continues...

Thanks for the asap reply. Here is the code.

            File questionFile =  new File ("question.txt");
            Scanner questionInput = new Scanner (questionFile).useDelimiter("//");


            String questions =  questionInput.nextLine();
            lblQuestion.setText(questions); //set label text according token

This works well but the scenario is like this... once user answer the question, to proceed next questions, user must click Next button. So for this i added the actionListener. I coded the following..:

public void actionPerformed(ActionEvent nextbtn)
{
 Object source =  nextbtn.getSource();
    if(source==btnNext)
        {
            try
                {
                    File questionFile =  new File ("question.txt");
                    Scanner questionInput = new Scanner (questionFile).useDelimiter("//").next();

                    String questions = questionInput.nextLine();
                                    lblQuestion.setText(questions);
                    }


                    catch(IOException ioe)
                    {
                        System.out.print("IO Errors");
                    }

                }
}

----------------------end of code----

I tried several methods already but still w/o success..what else did i miss?

in the actionPerformed method you declare some objects that you have already declared above, that's your mistake; just use the function to scan the text

and next time, use the CODE tags for your code

You just need to declare them at class level. You can initialize in the constructor as shown or in whichever method reads the first question. Subsequent calls to get the next question just use the same scanner.

class MCQquestion extends JFrame implements ActionListener
{

    private static final int WIDTH=550;
    private static final int HEIGHT=200;
    private static final int HLOC=340;
    private static final int VLOC=290;
    private JPanel pnlQ, pnlA,pnlButton;
    private JLabel lblQuestion;
    private JFormattedTextField txtAnswer;
    private JButton btnNext;

    //Not Sure what u meant... Im totally new to Java..
    //but declaring it here, at class level generate 'unreported Exception' during compilation
    //where do i insert throw IOException
    //Try n catch dint work at class level..."invalid declaration.."

    File questionFile = [B]null[/B];

    Scanner questionInput = [B]null[/B];
    

    public MCQquestion()
    {
        [B]try {[/B]
[B]           questionFile =  new File ("question.txt");
           questionInput = new Scanner (questionFile).useDelimiter("//");
        } catch (Exception e){
            // deal with exceptions here
        }
[/B] 
        lblQuestion =  new JLabel();


        try{
                        MaskFormatter ans = new MaskFormatter("U");
                          txtAnswer = new JFormattedTextField(ans);
                          txtAnswer.setPreferredSize(new Dimension(40,30));
                    }

         catch(ParseException pe)
         {
              System.out.println("Error: " + pe.getMessage());
         }

    .... the code continues...

Thanks Ezzaral, thanks a lot. It worked perfectly...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.