Java Swing多列自动完成组合框

Java Swing多列自动完成组合框,第1张

Java Swing多列自动完成组合框

这是一个JComboBox,它使用JTable而不是JList进行下拉。您需要为其提供表数据列表列表),而不是通常的表数据。抱歉,没有自动完成功能。

我已经使用了多年了。它有效,但我没有承诺。哎呀,实验甚至还剩下一些死代码。多年来,我只是从不同的代码示例中汲取了不同的想法,这简直就是一团糟。我敢肯定还有改进的余地。

详细的组合框:

import java.awt.*;import java.awt.event.*;import java.util.*;import java.util.List;import javax.swing.*;import javax.swing.event.*;import javax.swing.plaf.basic.*;import javax.swing.plaf.metal.*;import javax.swing.table.*;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;    public DetailedComboBox(String[] colNames, int[] colWidths,    int displayColumnIndex)  {    super();    this.columnNames = colNames;    this.columnWidths = colWidths;    this.displayColumn = displayColumnIndex;    setUI(new TableComboBoxUI());    setEditable(false);  }    public void setPopupAlignment(Alignment alignment)  {    popupAlignment = alignment;  }    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());  }    private class TableComboBoxUI extends metalComboBoxUI  {        @Override    protected ComboPopup createPopup()    {      return new TableComboPopup(comboBox, this);    }        public JList getList()    {      return listBox;    }  }    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;        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"));    }        @Override    public void show()    {      if (isEnabled())      {        super.removeAll();        int scrollWidth = table.getPreferredSize().width + ((Integer) UIManager.get("ScrollBar.width")).intValue() + 1;        int scrollHeight = 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 = comboBox.getBounds().height;        if (popupAlignment == Alignment.RIGHT)        {          scrollX = comboBox.getBounds().width - scrollWidth;        }        show(comboBox, scrollX, scrollY);      }    }        public void valueChanged(ListSelectionEvent event)    {      comboBox.setSelectedIndex(table.getSelectedRow());    }        public void itemStateChanged(ItemEvent event)    {      if (event.getStateChange() != ItemEvent.DESELECTED)      {        ListSelectionModel selectionModel = table.getSelectionModel();        selectionModel.removeListSelectionListener(this);        selectRow();        selectionModel.addListSelectionListener(this);      }    }        private void selectRow()    {      int index = comboBox.getSelectedIndex();      if (index != -1)      {        table.setRowSelectionInterval(index, index);        table.scrollRectToVisible(table.getCellRect(index, 0, true));      }    }  }    private class PopupTableModel extends AbstractTableModel  {        public int getColumnCount()    {      return columnNames.length;    }        public int getRowCount()    {      return tableData == null ? 0 : tableData.size();    }        public Object getValueAt(int row, int col)    {      if (tableData == null || tableData.size() == 0)      {        return "";      }      return tableData.get(row).get(col);    }        @Override    public boolean isCellEditable(int row, int col)    {      return false;    }        @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;    }  }}

司机:

import java.awt.*;import java.awt.event.*;import java.util.*;import java.util.List;import javax.swing.*;public class DetailedComboBoxDemo implements Runnable{  private DetailedComboBox combo;  private JTextField name;  private JTextField capital;  public void run()  {    List<List<?>> tableData = new ArrayList<List<?>>();    tableData.add(new ArrayList<String>(       Arrays.asList("MD", "Maryland", "Annapolis")));    tableData.add(new ArrayList<String>(       Arrays.asList("NH", "New Hampshire", "Concord")));    tableData.add(new ArrayList<String>(       Arrays.asList("NJ", "New Jersey", "Trenton")));    tableData.add(new ArrayList<String>(       Arrays.asList("NM", "New Mexico", "Santa Fe")));    tableData.add(new ArrayList<String>(       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);    combo.setTableData(tableData);    combo.setSelectedIndex(-1);    combo.setPopupAlignment(DetailedComboBox.Alignment.LEFT);    combo.addActionListener(new ActionListener()    {      public void actionPerformed(ActionEvent e)      {        showDetails();      }    });    name = new JTextField(10);    capital = new JTextField(10);    name.setEditable(false);    capital.setEditable(false);    JPanel p = new JPanel(new FlowLayout());    p.add(new JLabel("State"));    p.add(combo);    p.add(new JLabel("Name"));    p.add(name);    p.add(new JLabel("Capital"));        p.add(capital);    Jframe frame = new Jframe("DetailedComboBox Demo");    frame.getContentPane().add(p, BorderLayout.CENTER);    frame.pack();    frame.setLocationRelativeTo(null);    frame.setVisible(true);  }  private void showDetails()  {    List<? extends Object> rowData = combo.getSelectedRow();    name.setText(rowData.get(1).toString());    capital.setText(rowData.get(2).toString());  }  public static void main(String[] args)  {    SwingUtilities.invokeLater(new DetailedComboBoxDemo());  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5586618.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存