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.

4

2 回答 2

5

Load all of the data into a JTable. Then use the table filtering feature to display only the rows you want. The TableFilterDemo from the Sorting and Filtering section of the Swing tutorial is a working example that does this.

于 2013-02-17T20:35:35.453 回答
2

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

于 2013-02-17T21:31:36.250 回答