JAVA IO - How To Import A Text From Txt File To A JTextPane In Java

JAVA - How To Set A Text From Txt File To A JTextPane In Java

__________________________________________________________________________

In this java IO Tutorial we will see How To Display Text from Text File To JTextPane
In Java NetBeans .


Project Source Code:

package JavaDB_001;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.io.*;
import javax.swing.*;



public class Work extends JFrame{



    public Work(){



    super("Set Text From TXT File To JTextPane");



    JPanel p = new JPanel();
    JTextPane tp = new JTextPane();



    // call the Function TextFromFile
    TextFromFile(tp);



    Font font = new Font("",Font.BOLD,20);
    tp.setFont(font);



    tp.setForeground(Color.WHITE);
    tp.setBackground(Color.BLACK);



    JScrollPane jp = new JScrollPane(tp);



    p.setLayout(new BorderLayout());
    p.add(jp,BorderLayout.CENTER);



    setContentPane(p);



    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setSize(800,300);
    setVisible(true);
    }
    
    /*
    create a function to get the text from a text file 
    and set it into a JTextPane
    */ 
    public static void TextFromFile(JTextPane tp)
     {
        try{
            //the file path
            String path = "C:\\Users\\samsng\\Desktop\\TextFile.txt";
            File file = new File(path);
            FileReader fr = new FileReader(file);
            while(fr.read() != -1){
              tp.read(fr,null);
            }
            fr.close();
        } catch(Exception ex){
          ex.printStackTrace();
        }
     }
    
    public static void main(String[] args){
        new Work();
    }
   }

///////////////END
/////OUTPUT:
get the text from a text file and set it into a JTextPane
get the text from a text file and set it into a JTextPane



Share this

Related Posts

Previous
Next Post »