如何通过单击搜索按钮更改jtable数据?

时间:2014-08-05 07:14:30

标签: java swing jtable refresh rowfilter

我这里有一个不那么短的工作代码。我的搜索按钮需要帮助。如果我输入textfield并单击搜索按钮,则表格数据应更改为textfield中的内容。如果它没有搜索任何内容,则表格应为空白。我能在这里工作的是将新数据显示在表格中。我应该删除第一个数据然后repaint()吗?或者有更好的解决方案吗?

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class TableSearch {

    JFrame Card = new JFrame();
    static JTable table;
    JTabbedPane card_tab = new JTabbedPane(); // FOR TAB
    JPanel buttonpanel = new JPanel(); // FOR BUTTON BELOW
    FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
    Border etch = BorderFactory.createEtchedBorder(Color.white, Color.gray);
    Border margin = new EmptyBorder(10, 10, 10, 10);
    JTextField text;

    public TableSearch() throws SQLException, IOException {
        Card.setVisible(true);
        Card.setSize(821, 421);
        Card.setTitle("File Maintenance");
        Card.setResizable(false);

        final Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - Card.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - Card.getHeight()) / 2);

        Card.setLocation(x, y);
        Card.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel container = new JPanel();
        container.setLayout(new BorderLayout());
        container.setBackground(new Color(0, 128, 0));
        //container.setBorder(margin);

        JPanel labelpanel = new JPanel();
        labelpanel.setLayout(flow);
        labelpanel.setBackground(new Color(0, 128, 0));

        JLabel label_1 = new JLabel("Description:");
        label_1.setFont(new Font("Calibri", Font.BOLD, 20));
        label_1.setForeground(Color.YELLOW);
        labelpanel.add(label_1);

        text = new JTextField();
        text.setPreferredSize(new Dimension(200, 20));
        labelpanel.add(text);

        JButton btnsearch = new JButton("Search");
        btnsearch.setPreferredSize(new Dimension(90, 20));
        btnsearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String search = text.getText();
                System.out.println(search);
                //What should I put here to change the table data???
            }
        });
        labelpanel.add(btnsearch);

        JPanel jp1 = new JPanel();
        jp1.setBackground(new Color(0, 128, 0));
        //jp1.setBorder(new CompoundBorder(etch,margin));
        jp1.setLayout(new BorderLayout());

        table = new JTable(new TableModel());
        JScrollPane scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);

        JTableHeader header = table.getTableHeader();
        header.setBackground(new Color(224, 223, 227));
        header.setFont(new Font("Calibri", Font.BOLD, 20));
        table.setRowHeight(25);
        jp1.add(scrollPane);

        Card.add(container);
        container.add(labelpanel, BorderLayout.PAGE_START);
        container.add(jp1, BorderLayout.CENTER);
    }

    public static class TableModel extends DefaultTableModel {

        public TableModel() {
            super(new Object[]{"Description", "Code", "Price"}, 0);
            for (int index = 0; index < 4; index++) {
                addRow(new Object[]{index, index, index});
            }
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }
    }

    public static void main(String[] args) {
        //Use the event dispatch thread for Swing components
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new TableSearch();
                } catch (SQLException ex) {
                    Logger.getLogger(TableSearch.class.getName())
                          .log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(TableSearch.class.getName())
                          .log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

@mKorbel这是我所做的真正有用的。我将Table Model更改为AbstractModel

public static class JTableModel extends AbstractTableModel {
    private static final long serialVersionUID = 1L;
    private static final String[] COLUMN_NAMES = new String[] {"Description", "PLU Code", "Cash Price"};
    private static final Class<?>[] COLUMN_TYPES = new Class<?>[] {String.class, String.class, String.class, String.class};

    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

     public int getRowCount() {
        return products.size();
    }

    @Override public String getColumnName(int columnIndex) {

        return COLUMN_NAMES[columnIndex];
    }

    @Override public Class<?> getColumnClass(int columnIndex) {
        return COLUMN_TYPES[columnIndex];
    }

     public Object getValueAt(final int rowIndex, final int columnIndex) {
        switch (columnIndex) {
            case 0: return products.get(rowIndex).get("proddesc");
            case 1: return products.get(rowIndex).get("prodcode");
            case 2: return products.get(rowIndex).get("price");

            default: return "Error";
        }
    }   

    public void removeRow(int row)
    {
        products.remove(row);
        fireTableRowsDeleted(row, row);
    }


}

private static class JTableButtonMouseListener extends MouseAdapter {
    private final JTable table;

    public JTableButtonMouseListener(JTable table) {
        this.table = table;
    }

    public void mouseClicked(MouseEvent e) {
        int column = table.getColumnModel().getColumnIndexAtX(e.getX());
        int row    = e.getY()/table.getRowHeight(); 

        if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
            Object value = table.getValueAt(row, column);
            if (value instanceof JButton) {
                ((JButton)value).doClick();
            }
        }

    }
}

然后这就是我为搜索按钮所做的事情:

            JButton btnsearch = new JButton("Search");
            btnsearch.setPreferredSize(new Dimension(90,20));
            btnsearch.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    String search = text.getText();
                    ArrayList<HashMap<String, String>> productSearch = all.posMain.getProductsSearch(search);

                    System.out.println(productsSearch);
                    products.clear();
                    table.repaint();
                    products = productSearch;

                }
            });
            labelpanel.add(btnsearch);

由于所有内容都存储在Hashmap中,因此我只将第一个hashmap更改为第二个hashmap:products = productSearch;之后一切正常。