在行排序后选择JTable中的行

时间:2011-12-16 14:39:52

标签: java swing jtable

我希望在列排序后以编程方式选择JTable中的第一行。我能怎么做? 我编写了自己的类来监听JTable标题上的鼠标事件。在这个类中,我在表中分配或不分配TableRowSorter。例如:首先单击升序排序,然后单击第二次降序等等;如果我把选择放在这个类的末尾,结果是不可预测的。

class ClickHeader extends MouseAdapter {

JTable table;
static int headerClickCount;
TableRowSorter sorter = new TableRowSorter();
static int lastColumn = -1;


ClickHeader(JTable t) {
    table = t;
    headerClickCount=0;
    lastColumn=-1;
}

@Override
public void mousePressed(MouseEvent e) {       
    TableModel model = table.getModel();
    int vColIndex = table.getTableHeader().getColumnModel().getColumnIndexAtX(e.getX());
    if (vColIndex == -1) {
        return;
    }

    vColIndex = table.convertColumnIndexToModel(vColIndex);

    if(lastColumn != vColIndex){
        lastColumn = vColIndex;
        headerClickCount=0;
    }
    //
    headerClickCount++;
    if (headerClickCount == 3) {
        table.setRowSorter(null);
        sorter = new TableRowSorter();
        headerClickCount = 0;
    } else {
        if (table.getRowSorter() == null) {
            sorter.setModel(model);

        }

        table.setRowSorter(sorter);
    }

    table.getTableHeader().repaint();
}

}

2 个答案:

答案 0 :(得分:2)

如果你需要选择1st。然后您可以使用JTablechangeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend),例如

myTable.changeSelection(row, column, false, false);

enter image description here enter image description here enter image description here enter image description here enter image description here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableWithGradient extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable myTable;
    public int columnIndex = 0;
    public boolean columnIndexAble = false;

    public TableWithGradient() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
        Object[][] data = {
            {"Kathy", "Smith", "Snowboarding", new Integer(5), false},
            {"John", "Doe", "Rowing", new Integer(3), true},
            {"Sue", "Black", "Knitting", new Integer(2), false},
            {"Jane", "White", "Speed reading", new Integer(20), true},
            {"Joe", "Brown", "Pool", new Integer(10), false},
            {"Kathy", "Smith", "Snowboarding", new Integer(5), false}};
        myTable = new TableBackroundPaint(data, columnNames);
        myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        myTable.setGridColor(Color.gray);
        final TableCellRenderer tcrOs = myTable.getTableHeader().getDefaultRenderer();
        myTable.getTableHeader().setDefaultRenderer(new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel lbl = (JLabel) tcrOs.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
                lbl.setForeground(Color.black);
                lbl.setBorder(BorderFactory.createCompoundBorder(
                        lbl.getBorder(), BorderFactory.createEmptyBorder(0, 5, 0, 0)));
                lbl.setHorizontalAlignment(SwingConstants.LEFT);
                if (columnIndex == column && columnIndexAble) {
                    lbl.setForeground(Color.red);
                    lbl.setBackground(Color.yellow);
                } else {
                    lbl.setForeground(Color.black);
                    lbl.setBackground(Color.orange);
                }
                return lbl;
            }
        });
        myTable.setPreferredScrollableViewportSize(new Dimension(
                myTable.getPreferredSize().width + 100, myTable.getPreferredSize().height));
        final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(myTable.getModel());
        myTable.setRowSorter(sorter);
        JTableHeader header = myTable.getTableHeader();
        header.addMouseListener(new OsPanelImportColumnHeaderListener(this));
        add(new JScrollPane(myTable), BorderLayout.CENTER);
        setLocation(100, 100);
        pack();
        setVisible(true);
    }

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

            @Override
            public void run() {
                TableWithGradient tableWithGradient = new TableWithGradient();
            }
        });
    }
}

class OsPanelImportColumnHeaderListener extends MouseAdapter {

    private TableWithGradient osPanelImport;

    public OsPanelImportColumnHeaderListener(TableWithGradient osPanelImport) {
        this.osPanelImport = osPanelImport;
    }

    @Override
    public void mouseClicked(MouseEvent evt) {
        osPanelImport.columnIndexAble = true;
        JTable table = ((JTableHeader) evt.getSource()).getTable();
        TableColumnModel colModel = table.getColumnModel();
        osPanelImport.columnIndex = colModel.getColumnIndexAtX(evt.getX());
        table.changeSelection(0, 0, false, false);
        return;
    }
}

class TableBackroundPaint extends JTable {

    private static final long serialVersionUID = 1L;

    TableBackroundPaint(Object[][] data, Object[] head) {
        super(data, head);
        setOpaque(false);
        ((JComponent) getDefaultRenderer(Object.class)).setOpaque(false);
    }

    @Override
    public void paintComponent(Graphics g) {
        Color background = new Color(168, 210, 241);
        Color controlColor = new Color(230, 240, 230);
        int width = getWidth();
        int height = getHeight();
        Graphics2D g2 = (Graphics2D) g;
        Paint oldPaint = g2.getPaint();
        g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
        g2.fillRect(0, 0, width, height);
        g2.setPaint(oldPaint);
        for (int row : getSelectedRows()) {
            Rectangle start = getCellRect(row, 0, true);
            Rectangle end = getCellRect(row, getColumnCount() - 1, true);
            g2.setPaint(new GradientPaint(start.x, 0, controlColor,
                    (int) ((end.x + end.width - start.x) * 1.25), 0, Color.orange));
            g2.fillRect(start.x, start.y, end.x + end.width - start.x, start.height);
        }
        super.paintComponent(g);
    }
}

答案 1 :(得分:2)

要做到这一点,只需使用:

setRowSelectionInterval(int index0, int index1);

JTable上,更具体地说是第一行:

table.setRowSelectionInterval(0,0);
表已经排序后