【问题标题】:How to change the jtable data by clicking the search button?如何通过单击搜索按钮更改 jtable 数据?
【发布时间】:2014-09-27 18:43:11
【问题描述】:

我这里有一个不那么短的工作代码。我的搜索按钮需要帮助。如果我输入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);
                }
            }
        });
    }
}

【问题讨论】:

  • 首先查看How to Use Tables,尤其是Sorting and Filtering
  • @MadProgrammer 啊不。我已经可以在我的原始程序中搜索了。我没有将它包含在我的代码中的唯一原因是它来自数据库并且它位于哈希图中。但是我的主要问题是我不知道如何将搜索到的项目放在表格中。
  • 假设您有数据,为什么不直接使用addRowaddRow...它接受Object[]...TableModel 形式的数据是一个非常糟糕的命名类顺便说一句,因为javax.swing.Table 包中已经有一个TableModel ;)
  • (因为它来自数据库,并且它位于哈希图 vs 并单击搜索按钮,表数据应更改为)然后这个问题问错了,你想在数据库或 JTable 中搜索,顺便说一句,不要使用HasMap,使用基于util.List的数组,
  • @MadProgrammer 对不起班级名称。我会马上编辑它。 addRow 很好,但是当我的表模型在方法中时如何添加行?我的意思是程序将如何确定单击搜索按钮并更改数据?

标签: java swing jtable refresh rowfilter


【解决方案1】:

@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; 之后一切正常。

【讨论】:

  • 1.使用基于 util.List 的数组,因为 HashMap 没有内部索引,所以在 JTables 视图中索引存在问题(行排序器/过滤器,需要将索引从视图转换为模型的渲染器)
  • 2. ArrayList> productSearch = all.posMain.getProductsSearch(search);错了,为什么reson还有一个数组包含相同的数据,值结构
  • 3. table.repaint();谈论 JTable 及其模型设置不正确,从模型到视图错过通知或使用不正确(替换,刷新到模型所需的通知),底层数组设计错误或数组类型不正确,EDT 问题
  • 4.创建一个数组(无论是什么数组,包括 HashWhatever),使用 DefaultTableModel 创建 JTable,在数组中搜索(util.List 更适合 Comparator / Collat​​or),过滤数组,重置 DefaultTableModel,添加来自 Comparator / Collat​​or 的过滤输出作为 Vestor 的新向量到 DefaultTableModel,没有闪烁,延迟,图形重绘问题,不需要 table.repaint();,只有 EDT 问题(只有 mouse hover_ove JTable 可以用一组新数据导致 reoaintg)
  • 5.又是一个错误的问题,错误的描述,在 Oracle 教程中使用了 mis_interpering 的描述 - 如何使用表,然后在你的答案中输出错误,即 kill_and_shut_up_to_@mKorbel
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 2020-12-30
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多