Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9300689
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T22:50:20+00:00 2026-06-18T22:50:20+00:00

I have a JTextFiled and JTable that read data from text file. I want

  • 0

I have a JTextFiled and JTable that read data from text file.

I want to add a keyListener to my JTextFiled that when enter a number ‘ program should search my textfile and show lines that start with that number on my JTable.

My Text File:

26     thired     62     Yes
29     sixth     92     No
35     vff     53     No
33     oll     36     No
38     koole     86     No

For example, When i write “3” in textfield, my JTable should display this three lines on own:

35     vff     53     No
33     oll     36     No
38     koole     86     No

My Code:

public class BookPage extends JFrame implements KeyListener{

private AllBooks bookModel;
private JTable bTabel;
JTextField tf1;


public BookPage(){
    bookModel=new AllBooks();
    bTabel=new JTable(bookModel);

    tf1=new JTextField(20);
    tf1.addKeyListener(this);

    JPanel panel= new JPanel();
    JScrollPane scroolpane=new JScrollPane(bTabel);
    panel.add(tf1);
    panel.add(scroolpane);
    this.setContentPane(panel);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setBounds(300, 60, 800, 600);
    this.setVisible(true);
}


public static void main(String[] args){
    new BookPage().setVisible(true);
}

@Override
public void keyTyped(KeyEvent e) {
    String line=tf1.getText().trim();
    SearchBook(line);

}

@Override
public void keyPressed(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public void keyReleased(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

public void SearchBook(String Bid){
    File f=new File("AllBookRecords.txt");
    try{
        FileReader Bfr=new FileReader(f);
        BufferedReader Bbr=new BufferedReader(Bfr);
        String bs;
        while( (bs=Bbr.readLine()) != null ){
            String[] Ust=bs.split("     ");
            String id=Ust[0];
            String Bname=Ust[1];
            String Bdate=Ust[2];
            String borrowS=Ust[3];
            if(id.equals(Bid.trim())){
               bTabel.setValueAt(Bname, 10, 1);
            }
        }
    }
    catch (IOException ex) {

    }
}
}

Second Class:

public class AllBooks extends AbstractTableModel{
BookInformation Binfos1=new BookInformation();

String[] Bcol=new String[]{"Id","Name","Date","Borrow Status"};
ArrayList<BookInformation> Bdata=new ArrayList<BookInformation>();

public AllBooks(){
    try{
        FileReader fr=new FileReader("AllBookRecords.txt");
        BufferedReader br=new BufferedReader(fr);
        String line;

        while( (line=br.readLine()) != null){
            Bdata.add(initializeBookInfos(line));
        }
        br.close();
    }
    catch(IOException ioe){

    }
}

public static BookInformation initializeBookInfos(String myLine){
    BookInformation Binit=new BookInformation();
    String[] bookCellArray=myLine.split("     ");
    Binit.setBookID(bookCellArray[0]);
    Binit.setBookName(bookCellArray[1]);
    Binit.setBookDate(bookCellArray[2]);
    Binit.setBorrowStatus(bookCellArray[3]);
    return Binit;
}
public void RemoveMyRow(int row){
    if(RemoveBookFromFile(row)){
       Bdata.remove(row);
      fireTableRowsDeleted(row, row);
    }
}

public boolean RemoveBookFromFile(int index){

    File Mf=new File("AllBookRecords.txt");
    File Tf=new File("Boutput.txt");
    try{
        BufferedReader Ubr=new BufferedReader(new FileReader(Mf));
        PrintWriter Bpw=new PrintWriter(new FileWriter(Tf));
        String line;
        while( (line=Ubr.readLine()) != null ){
            if(line.trim().length() == 0){
                continue;
            }
            if(!line.startsWith(String.valueOf(getValueAt(index, 0)))){
                Bpw.println(line);
            }
        }
        Bpw.close();
        Ubr.close();
        Mf.delete();
        Tf.renameTo(Mf);
        return true;
    } catch(FileNotFoundException e1){
        return false;
    }
    catch(IOException ioe){
          return false;
    }
}

public void AddRow(BookInformation bookinfo){
    if(WriteBooktofile(bookinfo.toString())){
        Bdata.add(bookinfo);
        fireTableRowsInserted(Bdata.size()-1, Bdata.size()-1);
    }
    else{
        JOptionPane.showMessageDialog(null, "Unable Add To File"+bookinfo.getBookName());
    }
}

public boolean WriteBooktofile(String bookc){
    try{
        File f=new File("AllBookRecords.txt");

            FileWriter fw=new FileWriter(f.getAbsoluteFile(), true);
            BufferedWriter bw=new BufferedWriter(fw);
            bw.write(bookc);
            bw.close();
            return true;
    }
    catch(Exception e){
        return false;
    }
}

@Override
public String getColumnName(int col){
    return Bcol[col];
}

@Override
public int getRowCount() {
    if(Bdata !=null){
    return Bdata.size();
    }
    else{
        return 0;
    }
}

@Override
public int getColumnCount() {
    return Bcol.length;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    BookInformation binfo=Bdata.get(rowIndex);
    Object value;

    switch(columnIndex){

        case 0:
            value=binfo.getBookID();
            break;
        case 1:
            value=binfo.getBookName();
            break;
        case 2:
            value=binfo.getBookDate();
            break;
        case 3:
            value=binfo.getBorrowStatus();
            break;
        default :
            value="...";  
    }
    return value;
}
}

Second Class:

public class BookInformation {

private String BookName;
private String BookDate;
private String BookID;
private String BorrowStatus;

public String getBookName() {
    return BookName;
}

public void setBookName(String book_name) {
    this.BookName = book_name;
}

public String getBookDate() {
    return BookDate;
}


public void setBookDate(String book_date) {
    this.BookDate = book_date;
}


public String getBookID() {
    return BookID;
}

public void setBookID(String Book_id) {
    this.BookID = Book_id;
}

@Override
public String toString(){
    return BookID + "     " + BookName+ "     "
            + BookDate +"     "+ BorrowStatus + "\n";
}

public String getBorrowStatus() {
    return BorrowStatus;
}


public void setBorrowStatus(String borrowStat) {
    BorrowStatus = borrowStat;
}

}

thanks for help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T22:50:21+00:00Added an answer on June 18, 2026 at 10:50 pm

    I have to make some changes on your nativ code to make it works. Please note that i have not check the hole code of his functionality.

    I use

     @Override
            public void keyReleased(KeyEvent e) {
                String line = tf1.getText().trim();
                SearchBook(line);
            }
    

    instead of public void keyTyped(KeyEvent e) {} because it doesn’t transmit the first value

    Your old BookPage looks now as

    public class BookPage extends JFrame implements KeyListener {
    
        private static final long serialVersionUID = 1L;
    
        private AllBooks bookModel;
    
        private JTable bTabel;
    
        JTextField tf1;
    
        public BookPage() {
            bookModel = new AllBooks();
            bTabel = new JTable(bookModel);
    
            tf1 = new JTextField(20);
            tf1.addKeyListener(this);
    
            JPanel panel = new JPanel();
            JScrollPane scroolpane = new JScrollPane(bTabel);
            panel.add(tf1);
            panel.add(scroolpane);
            this.setContentPane(panel);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setBounds(300, 60, 800, 600);
            this.setVisible(true);
        }
    
        public static void main(String[] args) {
            new BookPage().setVisible(true);
        }
    
        @Override
        public void keyTyped(KeyEvent e) {
        }
    
        @Override
        public void keyPressed(KeyEvent e) {
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
            String line = tf1.getText().trim();
            SearchBook(line);
        }
    
        public void SearchBook(String bid) {
            List<BookInformation> filtedRows = new ArrayList<BookInformation>();
            try {
                InputStream stream = getClass().getResourceAsStream("AllBookRecords.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                String bs;
                while((bs = reader.readLine()) != null) {
                    BookInformation information = new BookInformation();
                    String[] Ust = bs.split("\\t");
                    information.setBookID(Ust[0]);
                    information.setBookName(Ust[1]);
                    information.setBookDate(Ust[2]);
                    information.setBorrowStatus(Ust[3]);
                    if(information.getBookID().equals(bid) || information.getBookID().startsWith(bid)) {
                        filtedRows.add(information);
                    }
                }
                if(!filtedRows.isEmpty()) {
                          //remove old rows
                    for(int i = bookModel.getRowCount() - 1; i >= 0; i--) {
                        bookModel.RemoveMyRow(i);
                    }
                         //add new rows
                    for(BookInformation bookInformation : filtedRows) {
                        bookModel.AddRow(bookInformation);
                    }
                }
                bookModel.fireTableDataChanged();
    
            } catch(IOException ex) {
                ex.getStackTrace();
                System.out.println(ex.getMessage());
            }
        }
    }
    

    the major changes are done in public void SearchBook(String bid) {} if some is not clear feel free to ask me.

    In your AllBooks just a little change

    public class AllBooks extends AbstractTableModel {
    
        private static final long serialVersionUID = 1L;
    
        BookInformation Binfos1 = new BookInformation();
    
        String[] bCol = new String[] { "Id", "Name", "Date", "Borrow Status" };
    
        ArrayList<BookInformation> bData = new ArrayList<BookInformation>();
    
        public AllBooks() {
            try {
                InputStream stream = getClass().getResourceAsStream("AllBookRecords.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                String line;
    
                while((line = reader.readLine()) != null) {
                    bData.add(initializeBookInfos(line));
                }
                reader.close();
            } catch(IOException ioe) {
    
            }
        }
    
        public static BookInformation initializeBookInfos(String myLine) {
            BookInformation Binit = new BookInformation();
            String[] bookCellArray = myLine.split("\\t");
            Binit.setBookID(bookCellArray[0]);
            Binit.setBookName(bookCellArray[1]);
            Binit.setBookDate(bookCellArray[2]);
            Binit.setBorrowStatus(bookCellArray[3]);
            return Binit;
        }
    
        public void RemoveMyRow(int row) {
            if(RemoveBookFromFile(row)) {
                bData.remove(row);
                fireTableRowsDeleted(row, row);
            }
        }
    
        public boolean RemoveBookFromFile(int index) {
    
            File Mf = new File("AllBookRecords.txt");
            File Tf = new File("Boutput.txt");
            try {
                BufferedReader Ubr = new BufferedReader(new FileReader(Mf));
                PrintWriter Bpw = new PrintWriter(new FileWriter(Tf));
                String line;
                while((line = Ubr.readLine()) != null) {
                    if(line.trim().length() == 0) {
                        continue;
                    }
                    if(!line.startsWith(String.valueOf(getValueAt(index, 0)))) {
                        Bpw.println(line);
                    }
                }
                Bpw.close();
                Ubr.close();
                Mf.delete();
                Tf.renameTo(Mf);
                return true;
            } catch(FileNotFoundException e1) {
                return false;
            } catch(IOException ioe) {
                return false;
            }
        }
    
        public void AddRow(BookInformation bookinfo) {
            if(WriteBooktofile(bookinfo.toString())) {
                bData.add(bookinfo);
                fireTableRowsInserted(bData.size() - 1, bData.size() - 1);
            } else {
                JOptionPane.showMessageDialog(null, "Unable Add To File" + bookinfo.getBookName());
            }
        }
    
        public boolean WriteBooktofile(String bookc) {
            try {
                File f = new File("AllBookRecords.txt");
    
                FileWriter fw = new FileWriter(f.getAbsoluteFile(), true);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(bookc);
                bw.close();
                return true;
            } catch(Exception e) {
                return false;
            }
        }
    
        @Override
        public String getColumnName(int col) {
            return bCol[col];
        }
    
        @Override
        public int getRowCount() {
            if(bData != null) {
                return bData.size();
            } else {
                return 0;
            }
        }
    
        @Override
        public int getColumnCount() {
            return bCol.length;
        }
    
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            BookInformation binfo = bData.get(rowIndex);
            Object value;
    
            switch(columnIndex) {
    
                case 0:
                    value = binfo.getBookID();
                    break;
                case 1:
                    value = binfo.getBookName();
                    break;
                case 2:
                    value = binfo.getBookDate();
                    break;
                case 3:
                    value = binfo.getBorrowStatus();
                    break;
                default:
                    value = "...";
            }
            return value;
        }
    
    }
    

    Now your AllBookRecords.txt is with tab separated (\t)

    26  thired  62  Yes
    29  sixth   92  No
    35  vff 53  No
    33  oll 36  No
    38  koole   86  No
    

    There is a several way to deal with this issue but i don’t want to write every on my way but try to make your code works with little changes

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a program that uses three JTextField fields as the main data entry
I have a a table that show all book list from a txt file
I have jFrame2 which contains jTable with 4 columns (the jTable taking data from
i want to draw line, i have two textfiled in which i enter some
I want to display a text above a JTable cell when someone is editing
I have a JTable that am Filtering in relation to JTextField input. It is
I have a JTextField and I want to add a label next to it,
I have a JTextField in my Swing application that holds the file path of
I have a JTextField that I want to be limited to fifteen characters. The
i have a frame that contain a button and textfield. my porpuse is read

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.