当前位置: 首页 > 知识库问答 >
问题:

在JTable单元格编辑器中自动完成JComboBox

裴楚青
2023-03-14
  package test;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author W.A.R.R.Wijesinghe
 */
public class DetailedComboBox extends JComboBox {

    public static enum Alignment {

        LEFT, RIGHT
    }
    private List<List<? extends Object>> tableData;
    private String[] columnNames;
    private int[] columnWidths;
    private int displayColumn;
    private Alignment popupAlignment = Alignment.LEFT;

    /**
     * Construct a TableComboBox object
     */
    public DetailedComboBox(String[] colNames, int[] colWidths, int displayColumnIndex) {
        super();
        this.columnNames = colNames;
        this.columnWidths = colWidths;
        this.displayColumn = displayColumnIndex;

        setUI(new TableComboBoxUI());
        setEditable(true);
        this.setSelectedIndex(-1);

    }

    /**
     * Set the type of alignment for the popup table
     */
    public void setPopupAlignment(Alignment alignment) {
        popupAlignment = alignment;
    }

    /**
     * Populate the combobox and drop-down table with the supplied data. If the
     * supplied List is non-null and non-empty, it is assumed that the data is a
     * List of Lists to be used for the drop-down table. The combobox is also
     * populated with the column data from the column defined by
     * <code>displayColumn</code>.
     */
    public void setTableData(List<List<? extends Object>> tableData) {
        this.tableData = (tableData == null
                ? new ArrayList<List<? extends Object>>() : tableData);

        // even though the incoming data is for the table, we must also
        // populate the combobox's data, so first clear the previous list.
        removeAllItems();

        // then load the combobox with data from the appropriate column
        Iterator<List<? extends Object>> iter = this.tableData.iterator();
        while (iter.hasNext()) {
            List<? extends Object> rowData = iter.next();
            addItem(rowData.get(displayColumn));
        }
    }

    public List<? extends Object> getSelectedRow() {
        return tableData.get(getSelectedIndex());
    }

    public List<? extends Object> getRowAt(int row) {
        return tableData.get(row);
    }

    /**
     * The handler for the combobox's components
     */
    private class TableComboBoxUI extends MetalComboBoxUI {

        /**
         * Create a popup component for the ComboBox
         */
        @Override
        protected ComboPopup createPopup() {
            return new TableComboPopup(comboBox, this);
        }

        /**
         * Return the JList component
         */
        public JList getList() {
            return listBox;
        }
    }

    /**
     * The drop-down of the combobox, which is a JTable instead of a JList.
     */
    private class TableComboPopup extends BasicComboPopup implements ListSelectionListener, ItemListener {

        private final JTable table;
        private TableComboBoxUI comboBoxUI;
        private PopupTableModel tableModel;
        private JScrollPane scroll;
//    private JList list = new JList();
//    private ListSelectionListener selectionListener;
//    private ItemListener itemListener;

        /**
         * Construct a popup component that's a table
         */
        public TableComboPopup(JComboBox combo, TableComboBoxUI ui) {
            super(combo);
            this.comboBoxUI = ui;

            tableModel = new PopupTableModel();
            table = new JTable(tableModel);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table.getTableHeader().setReorderingAllowed(false);

            TableColumnModel tableColumnModel = table.getColumnModel();
            tableColumnModel.setColumnSelectionAllowed(false);

            for (int index = 0; index < table.getColumnCount(); index++) {
                TableColumn tableColumn = tableColumnModel.getColumn(index);
                tableColumn.setPreferredWidth(columnWidths[index]);
            }

            scroll = new JScrollPane(table);
            scroll.setHorizontalScrollBarPolicy(
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

            ListSelectionModel selectionModel = table.getSelectionModel();
            selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            selectionModel.addListSelectionListener(this);
            combo.addItemListener(this);

            table.addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent event) {
                    Point p = event.getPoint();
                    int row = table.rowAtPoint(p);

                    comboBox.setSelectedIndex(row);
                    hide();
                }
            });

            table.setBackground(UIManager.getColor("ComboBox.listBackground"));
            table.setForeground(UIManager.getColor("ComboBox.listForeground"));
        }

        /**
         * This method is overridden from BasicComboPopup
         */
        @Override
        public void show() {
            if (isEnabled()) {
                super.removeAll();

                int scrollWidth = 200;//table.getPreferredSize().width
                      //  + ((Integer) UIManager.get("ScrollBar.width")).intValue() + 1;
                int scrollHeight = 100;//comboBoxUI.getList().
                       // getPreferredScrollableViewportSize().height;
                scroll.setPreferredSize(new Dimension(scrollWidth, scrollHeight));

                super.add(scroll);

                ListSelectionModel selectionModel = table.getSelectionModel();
                selectionModel.removeListSelectionListener(this);
                selectRow();
                selectionModel.addListSelectionListener(this);

                int scrollX = 0;
                int scrollY = 25;//comboBox.getBounds().height;
/*
                if (popupAlignment == Alignment.RIGHT) {
                    scrollX = comboBox.getBounds().width - scrollWidth;
                }

* */
                show(comboBox, scrollX, scrollY);

            }
        }

        /**
         * Implemention of ListSelectionListener
         */
        @Override
        public void valueChanged(ListSelectionEvent event) {
            comboBox.setSelectedIndex(table.getSelectedRow());
        }

        /**
         * Implemention of ItemListener
         */
        @Override
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() != ItemEvent.DESELECTED) {
                ListSelectionModel selectionModel = table.getSelectionModel();
                selectionModel.removeListSelectionListener(this);
                selectRow();
                selectionModel.addListSelectionListener(this);
            }
        }

        /**
         * Sync the selected row of the table with the selected row of the
         * combo.
         */
        private void selectRow() {
            int index = comboBox.getSelectedIndex();

            if (index != -1) {
                table.setRowSelectionInterval(index, index);
                table.scrollRectToVisible(table.getCellRect(index, 0, true));
            }
        }
    }

    /**
     * A model for the popup table's data
     */
    private class PopupTableModel extends AbstractTableModel {

        /**
         * Return the # of columns in the drop-down table
         */
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        /**
         * Return the # of rows in the drop-down table
         */
        @Override
        public int getRowCount() {
            return tableData == null ? 0 : tableData.size();
        }

        /**
         * Determine the value for a given cell
         */
        @Override
        public Object getValueAt(int row, int col) {
            if (tableData == null || tableData.isEmpty()) {
                return "";
            }

            return tableData.get(row).get(col);
        }

        /**
         * All cells in the drop-down table are uneditable
         */
        @Override
        public boolean isCellEditable(int row, int col) {
            return false;
        }

        /**
         * Pull the column names out of the tableInfo object for the header
         */
        @Override
        public String getColumnName(int column) {
            String columnName = null;

            if (column >= 0 && column < columnNames.length) {
                columnName = columnNames[column].toString();
            }

            return (columnName == null) ? super.getColumnName(column) : columnName;
        }
    }
}

class ComboKeyHandler extends KeyAdapter {

    private final DetailedComboBox comboBox;
    //  private final Vector<String> list = new Vector<String>();
    private final List<List<?>> list = new ArrayList<>();

    public ComboKeyHandler(DetailedComboBox combo) {

        this.comboBox = combo;

        for (int i = 0; i < comboBox.getItemCount(); i++) {

            List<? extends Object> rowData = combo.getRowAt(i);
            // name.setText(rowData.get(1).toString());
            //  capital.setText(rowData.get(2).toString());
            list.add(rowData);
            System.out.println("List Create: " + list);
            // list.addElement((String) comboBox.getItemAt(i));
        }
    }
    private boolean shouldHide = false;

    @Override
    public void keyTyped(final KeyEvent e) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                String text = ((JTextField) e.getSource()).getText();
                System.out.println(text);
                if (text.length() == 0) {
                    setSuggestionModel(comboBox, list, "");
                    comboBox.hidePopup();
                } else {
                    List<List<?>> m = getSuggestedModel(list, text);
                    if (m.isEmpty() || shouldHide) {
                        comboBox.hidePopup();
                    } else {
                        setSuggestionModel(comboBox, m, text);
                        comboBox.showPopup();
                    }
                }
            }
        });
    }

    @Override
    public void keyPressed(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        shouldHide = false;
        switch (e.getKeyCode()) {
            case KeyEvent.VK_RIGHT:


                    if (!list.isEmpty()) {

                    }


                break;
            case KeyEvent.VK_ENTER:
                if (list.isEmpty()) {
                    //list.add(new ArrayList<>(Arrays.asList(text, "a", "a")));
                    //  setSuggestionModel(comboBox, getSuggestedModel(list, text), text);
                }
                shouldHide = true;
                break;
            case KeyEvent.VK_ESCAPE:
                shouldHide = true;
                break;
            default:
                break;
        }
    }

    private static void setSuggestionModel(DetailedComboBox comboBox, List<List<?>> newList, String str) {
        comboBox.setTableData(newList);
        comboBox.setSelectedIndex(-1);
        ((JTextField) comboBox.getEditor().getEditorComponent()).setText(str);
    }

    private static List<List<?>> getSuggestedModel(List<List<?>> list, String text) {

        List<List<?>> BacktableData = new ArrayList<>();
        System.out.println("List before: " + list);

        for (int i = 0; i < list.size(); i++) {
            List<List<?>> Innerlist = new ArrayList<>();
            Innerlist = (List<List<?>>) list.get(i);

            String[] toArray = Innerlist.toArray(new String[Innerlist.size()]);
            List<String> Stringlist = new ArrayList<>(Arrays.asList(toArray));
            System.out.println("String List ::::::: " + Stringlist);
            boolean isSearch = false;
            for (Iterator<String> it = Stringlist.iterator(); it.hasNext();) {
                isSearch = false;

                if (it.next().contains(text)) {
                    //it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
                    isSearch = true;
                    if (isSearch) {
                        break;
                    }
                }

            }

            if (isSearch) {
                BacktableData.add(new ArrayList<>(Innerlist));

            }
            System.out.println("BackList : " + BacktableData);
        }
        System.out.println("Filter Text: " + text);
        System.out.println("List After: " + list);
        return BacktableData;

        /*
         * for (String s : list) { if (s.startsWith(text)) { m.addElement(s); }
         * } return m;
         *
         */
    }
}

/////测试TBL

package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JTextField;
import javax.swing.table.TableColumn;


public class TestTbl extends javax.swing.JFrame {

    JTextField field;
    private DetailedComboBox combo;

    public TestTbl() {
        initComponents();
        List<List<?>> tableData = new ArrayList<>();
        tableData.add(new ArrayList<>(Arrays.asList("MD", "Maryland", "Annapolis")));

        tableData.add(new ArrayList<>(
                Arrays.asList("NH", "New Hampshire", "Concord")));
        tableData.add(new ArrayList<>(
                Arrays.asList("NJ", "New Jersey", "Trenton")));
        tableData.add(new ArrayList<>(
                Arrays.asList("NM", "New Mexico", "Santa Fe")));
        tableData.add(new ArrayList<>(
                Arrays.asList("ND", "North Dakota", "Bismark")));

        String[] columns = new String[]{"State", "Name", "Capital"};
        int[] widths = new int[]{50, 100, 100};

        combo = new DetailedComboBox(columns, widths, 0);
        System.out.println(tableData);
        combo.setTableData(tableData);
        combo.setSelectedIndex(0);
        combo.setPopupAlignment(DetailedComboBox.Alignment.LEFT);
        field = (JTextField) combo.getEditor().getEditorComponent();
        field.setText("");
        field.addKeyListener(new ComboKeyHandler(combo));

        combo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (field.getText().trim().length() != 0) {
                    showDetails();
                }
            }
        });

        name = new JTextField(10);
        capital = new JTextField(10);
        name.setEditable(true);
        capital.setEditable(false);


        TableColumn Item = jTable1.getColumnModel().getColumn(0);
        Item.setCellEditor(new DefaultCellEditor(combo));
    }

    private void showDetails() {
        List<? extends Object> rowData = combo.getSelectedRow();
        name.setText(rowData.get(1).toString());
        capital.setText(rowData.get(2).toString());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        name = new javax.swing.JTextField();
        capital = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setRowHeight(25);
        jScrollPane1.setViewportView(jTable1);

        name.setText("jTextField1");

        capital.setText("jTextField2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(82, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(68, 68, 68))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(capital, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(110, 110, 110))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(capital, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestTbl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestTbl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestTbl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestTbl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTbl().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTextField capital;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField name;
    // End of variables declaration
}

共有1个答案

索正豪
2023-03-14

不要推倒重来,没有问题

>

  • 在SwingX中自动完成装饰器

    自动完成JComboBox/JTextField

  •  类似资料:
    • 问题内容: 我需要在jTable中显示数字,精确到小数点后两位。为此,我创建了一个自定义单元格编辑器,如下所示: 该单元格编辑器非常适合将点用作小数点的英语语言环境。但是在德语语言环境中,它不接受逗号作为小数点的值。请让我知道我的代码中有问题的地方。提前致谢。 编辑:这是我如何使其工作: 问题答案: 使用语言环境来发挥您的优势:

    • 设计定制JTable我已经知道DefaultCellEditor在其构造函数中允许使用JComboBox。单击此JComboBox以显示列表项时,它显示在JTable的其他单元格上方。问题是,我需要一个更复杂的行为,就像JComboBox提供的那样,这样我就用一个JList和一个JButton实现了一个JTextField,当点击JButton(或者用户在JTextField中输入文本)时,JLi

    • 我想要一个有4列的jtable。一列必须是组合框。其他列是字符串。 只要找到问题:在注释语句jcb.seteditable(true)时;,如果我在comboxcell上单击一次,它就会打开这个单元格。但我不知道为什么效果更好。此外,我希望combox可编辑。 我怎么能对其他细胞有同样的行为。 再次您好,我已经更新了代码,以便使-如果我通过重写方法在单元格上单击一次,单元格可以编辑-如果我通过重写

    • 我有一个JTable,它应该是2列(String,JComboBox)。当我初始化表时,一切看起来都很好。只要一个I在表中选择了一个值,JComboBox单元格就会获取所选项的数据类型。 我想保持JCOmboBox在那里,让它触发数据更改事件,表忽略该列中的数据更改,并保持ComboBox填充。 我的表将此作为覆盖

    • 我的JTable有一个单元编辑器,作为DefaultCellEditor(JComboBox)类的实例实现。我尝试了几种不同的方法(为Swing组合框添加自动完成支持),但仍然不起作用。 1: 2: 3: 我面临的问题是,一旦用户开始在组合框中输入,它就会退出编辑模式,从而有效地防止输入任何值。

    • 我创建了一个带有自定义表格呈现和自定义单元格编辑器的JTable,它在图像中给出结果 我使用一个扩展JPanel的单独类创建了第一个表格单元格中显示的面板。并将表值添加为, 这是我的表格自定义类来创建这个表格, 我的问题是认为面板如我预期的那样显示,我不能在文本字段中键入或更改复选框或单击按钮。请告诉我如何解决这个问题。