JTable显示JTextFiled搜索结果

时间:2013-02-17 19:14:02

标签: java swing jtable

我有一个从文本文件中读取数据的JTextFiled和JTable。

我想在我的JTextFiled中添加一个keyListener,当输入一个数字时,程序应该搜索我的文本文件并在我的JTable上显示以该数字开头的行。

我的文字档案:

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

例如,当我在textfield中写“3”时,我的JTable应该自己显示这三行:

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

我的代码:

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) {

    }
}
}

第二课:

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

第二课:

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

}

感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

将所有数据加载到JTable中。然后使用表过滤功能仅显示所需的行。来自Swing教程的Sorting and Filtering部分的 TableFilterDemo 是一个可以做到这一点的工作示例。

答案 1 :(得分:2)

我必须对您的nativ代码进行一些更改才能使其正常工作。请注意,我没有检查他的功能的漏洞代码。

我用

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

而不是public void keyTyped(KeyEvent e) {}因为它不传输第一个值

您的旧BookPage现在看起来是

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

主要更改在public void SearchBook(String bid) {}进行,如果有些不明确的话请随时问我。

在AllBooks中稍作修改

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

}

现在你的AllBookRecords.txt与制表符分开(\ t)

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

有几种方法可以解决这个问题,但我不想在我的路上写下每一个但是试着让你的代码稍作改动