JTable 의 정렬 과 필터

2486 단어 자바
package com.yunshouhu.demo;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JTableTester {
    static String data[][] = {
            {"China","Beijing","Chinese"},
            {"America","Washington","English"},
            {"Korea","Seoul","Korean"},
            {"Japan","Tokyo","Japanese"},
            {"France","Paris","French"},
            {"England","London","English"},
            {"Germany","Berlin","German"},
    };
    static String titles[] = {"Country","Capital","Language"};
    public static void main(String[] args) {
        DefaultTableModel model = new DefaultTableModel(data,titles);
        JTable jTable = new JTable(model);
        final TableRowSorter sorter = new TableRowSorter(model);
        jTable.setRowSorter(sorter); // JTable     

        JScrollPane sPane = new JScrollPane();
        sPane.setViewportView(jTable);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
        JLabel label = new JLabel("Criteria:");
        final JTextField jTextField = new JTextField();
        JButton button = new JButton("Do Filter");
        panel.add(label);
        panel.add(jTextField);
        panel.add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(jTextField.getText().length()==0){
                    sorter.setRowFilter(null);
                }else{
                    sorter.setRowFilter(RowFilter.regexFilter(jTextField.getText()));// JTable              
                }
            }
        });

        JFrame f = new JFrame("JTable Sorting and Filtering");
        f.getContentPane().add(sPane, BorderLayout.CENTER);
        f.getContentPane().add(panel,BorderLayout.SOUTH);
        f.setSize(400,300);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}
//      ,  JTable    title,  title          /      ;    Criteria      "ese",  "Do Filter"  ,JTable      "ese"     ,   China Japan  ,            ,  "Do Filter"  ,  JTable       。

좋은 웹페이지 즐겨찾기