当按下向上或向下时,SelectedRow更改,JTable

时间:2012-11-18 07:03:31

标签: java swing jtable jframe tablerowsorter

我有一个JTable。我希望当我按下或向上按键盘时,JTable中的roworter也会改变。

1 个答案:

答案 0 :(得分:4)

  • 必须将KeyBinding添加到JTableHeader

  • 有三种状态ASCENDINGDESCENDINGUNSORTED

来自RowSorter

KeyStrokeF8的简单示例

enter image description here enter image description here

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);
    }
}