0

我有一个 JTable。我想当我按下或按下键盘时,JTable 中的行排序器也会改变。

4

1 回答 1

4
  • 必须添加KeyBindingJTableHeader

  • 有三种状态ASCENDINGDESCENDINGUNSORTED

RowSorter关于和 KeyStroke来自的简单示例F8

在此处输入图像描述 在此处输入图像描述

import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.RowSorter.SortKey;

class SelectedColumnTest {

    private JPopupMenu popup = new JPopupMenu();
    private JTableHeader header;
    private Object selectedColumn = null;
    private String[] columnNames = {"String", "Integer", "Boolean"};
    private Object[][] data = {{"aaa", 12, true}, {"bbb", 5, false}, {"CCC", 92, true}};
    private TableModel model = new DefaultTableModel(data, columnNames) {

        private static final long serialVersionUID = 1L;

        @Override
        public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };
    private JTable table = new JTable(model);

    public JComponent makeUI() {
        table.setRowSorter(new TableRowSorter<TableModel>(model) {

            @Override
            public void toggleSortOrder(int column) {
            }
        });
        header = table.getTableHeader();
        header.getActionMap().put("toggleSortOrder2", new AbstractAction() {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                e.setSource(table);
                table.getActionMap().get("focusHeader").actionPerformed(e);
                if (selectedColumn != null) {
                    int i = header.getColumnModel().getColumnIndex(selectedColumn);
                    SortOrder order = SortOrder.ASCENDING;
                    List<SortKey> keys = new ArrayList<SortKey>(table.getRowSorter().getSortKeys());
                    if (!keys.isEmpty()) {
                        SortKey sortKey = keys.get(0);
                        if (sortKey.getColumn() == i && sortKey.getSortOrder() == SortOrder.ASCENDING) {
                            order = SortOrder.DESCENDING;
                        }
                    }
                    table.getRowSorter().setSortKeys(Arrays.asList(new SortKey(i, order)));
                }
                header.repaint();
            }
        });
        InputMap im = header.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0), "toggleSortOrder2");
        header.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                int i = h.columnAtPoint(e.getPoint());
                Object o = h.getColumnModel().getColumn(i).getHeaderValue();
                /*if (SwingUtilities.isRightMouseButton(e) && e.getClickCount() == 1) {
                    if (i < 0 || o == selectedColumn) {
                        selectedColumn = null;
                        popup.show(e.getComponent(), e.getX(), e.getY());
                        return;
                    }
                    selectedColumn = o;
                } else*/ if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1) {
                    if (i < 0 || o == selectedColumn) {
                        selectedColumn = null;
                        return;
                    }
                    selectedColumn = o;
                    h.requestFocusInWindow();
                }
            }
        });
        final TableCellRenderer hr = table.getTableHeader().getDefaultRenderer();
        header.setDefaultRenderer(new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable t, Object v,
                    boolean isS, boolean hasF, int row, int col) {
                return (v == selectedColumn) ? hr.getTableCellRendererComponent(
                        t, v, true, true, row, col) : hr.getTableCellRendererComponent(
                        t, v, false, false, row, col);
            }
        });
        header.setToolTipText("Sorting by F8");
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(table));
        createPopupMenu();
        return p;
    }

    private void createPopupMenu() {
        popup = new JPopupMenu();
        JMenuItem myMenuItem1 = new JMenuItem("cccccccccccccccccccccc");
        JMenuItem myMenuItem2 = new JMenuItem("bbbbbbbbbbbbbbbbbbbbbb");
        popup.add(myMenuItem1);
        popup.add(myMenuItem2);
        MouseListener popupListener = new PopupListener(popup);
        header.addMouseListener(popupListener);
    }

    private class PopupListener extends MouseAdapter {

        private JPopupMenu popup;

        PopupListener(JPopupMenu popupMenu) {
            popup = popupMenu;
        }

        @Override
        public void mousePressed(MouseEvent e) {
            maybeShowPopup(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new SelectedColumnTest().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}
于 2012-11-18T07:17:42.807 回答