JTable自动滚动到底部

发布于 2024-11-05 23:33:56 字数 2214 浏览 1 评论 0 原文

我有一个包含 3 个 JScrollPanes(每个包含一个 Jtable)并添加了 boxlayout 的 JPanel,所以我在页面中看到 3 个表,并且动态加载数据,代码逻辑对于 3 个表几乎相同,只有列名称和一些单元格渲染不同的是,对于每个表,当新行添加到表中时,我希望自动滚动到表底部,前两个表工作完美,滚动条转到表底部,但是最后一个表的滚动条做了奇怪的事情!我对 3 个表使用完全相同的滚动方法,但前 2 个表有效,但不起作用!

有什么想法吗?

为了清晰起见,我删除了一些添加代码的列,但这就是想法;

private JScrollPane fillThirdTable(ArrayList<DisplayVariable> displayList) {
    DefaultTableModel model = new DefaultTableModel();

    ToolTipTable answer = new ToolTipTable(model);

            answer.setRowHeight(60);
    answer.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    answer.setSize(1300, 400);  
    DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
    dtcr.setHorizontalAlignment(SwingConstants.CENTER);
    answer.getColumn("Display Variable ID").setCellRenderer(dtcr);

    JScrollPane scrollPane = null;
    for (DisplayVariable var : displayList) {

        model.addRow(new Object[] { id, shown, name, value });
        answer.setFillsViewportHeight(true);    
    }


    TableColumn c= answer.getColumnModel().getColumn(3);
    c.setCellRenderer(new MultiLineCellRenderer());

    TableColumn c2= answer.getColumnModel().getColumn(2);
    c2.setCellRenderer(new MultiLineCellRenderer());


    scrollPane = new JScrollPane(answer);
    scrollPane.setSize(1300, 400);

//here I call the method
    scrollToVisible(answer, (displayList.size()-1), 1);

    return scrollPane;

}

这是自动滚动的方法;

public void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
    if (!(table.getParent() instanceof JViewport)) {
        return;
    }
    JViewport viewport = (JViewport)table.getParent();

    // This rectangle is relative to the table where the
    // northwest corner of cell (0,0) is always (0,0).
    Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);

    // The location of the viewport relative to the table
    Point pt = viewport.getViewPosition();

    // Translate the cell location so that it is relative
    // to the view, assuming the northwest corner of the
    // view is (0,0)
    rect.setLocation(rect.x-pt.x, rect.y-pt.y);

    // Scroll the area into view
    viewport.scrollRectToVisible(rect);
}

I have a JPanel containing 3 JScrollPanes(each contains a Jtable) added with a boxlayout, so I see 3 tables in a page and I load data dynamically, the code logic is almost same for 3 tables and only the column names and some cell rendering is different, For each tables I wanted to have auto scrolling to bottom of the table when new rows added to table, first 2 tables work perfect and scrollbar goes to bottom of table, but this last table's scroll bar do weird things! I use exactly the same scrolling method for 3 tables but first 2 works this does not work!

Any ideas?

I removed some column adding code for clearity but this is the idea;

private JScrollPane fillThirdTable(ArrayList<DisplayVariable> displayList) {
    DefaultTableModel model = new DefaultTableModel();

    ToolTipTable answer = new ToolTipTable(model);

            answer.setRowHeight(60);
    answer.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    answer.setSize(1300, 400);  
    DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
    dtcr.setHorizontalAlignment(SwingConstants.CENTER);
    answer.getColumn("Display Variable ID").setCellRenderer(dtcr);

    JScrollPane scrollPane = null;
    for (DisplayVariable var : displayList) {

        model.addRow(new Object[] { id, shown, name, value });
        answer.setFillsViewportHeight(true);    
    }


    TableColumn c= answer.getColumnModel().getColumn(3);
    c.setCellRenderer(new MultiLineCellRenderer());

    TableColumn c2= answer.getColumnModel().getColumn(2);
    c2.setCellRenderer(new MultiLineCellRenderer());


    scrollPane = new JScrollPane(answer);
    scrollPane.setSize(1300, 400);

//here I call the method
    scrollToVisible(answer, (displayList.size()-1), 1);

    return scrollPane;

}

and this is the method for autoscrolling;

public void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
    if (!(table.getParent() instanceof JViewport)) {
        return;
    }
    JViewport viewport = (JViewport)table.getParent();

    // This rectangle is relative to the table where the
    // northwest corner of cell (0,0) is always (0,0).
    Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);

    // The location of the viewport relative to the table
    Point pt = viewport.getViewPosition();

    // Translate the cell location so that it is relative
    // to the view, assuming the northwest corner of the
    // view is (0,0)
    rect.setLocation(rect.x-pt.x, rect.y-pt.y);

    // Scroll the area into view
    viewport.scrollRectToVisible(rect);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

网名女生简单气质 2024-11-12 23:33:56

据我所知,你不需要为父母工作。只需使用这个:

public void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
    table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, true));
}

我之前确实遇到过滚动问题,通过使用 SwingUtilities.invokeLater() 进行了排序,因此您可能也想尝试一下:

public void scrollToVisible(final JTable table, final int rowIndex, final int vColIndex) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, false));
        }
    });
}

As far as I know, you don't need to work on the parent. Just use this:

public void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
    table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, true));
}

I did have an issue with scrolling previously that was sorted by using SwingUtilities.invokeLater(), so you might want to try that as well:

public void scrollToVisible(final JTable table, final int rowIndex, final int vColIndex) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, false));
        }
    });
}
网白 2024-11-12 23:33:56

我看不到您在谈论的内容,这只是 (这里也有三个JTable,但又是另一个故事了)

>例如

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

public class TableSelection implements ListSelectionListener {

    private JTable[] tables;
    private boolean ignore = false;

    public TableSelection() {
        Object[][] data1 = new Object[100][5];
        Object[][] data2 = new Object[50][5];
        Object[][] data3 = new Object[50][5];
        for (int i = 0; i < data1.length; i++) {
            data1[i][0] = "Company # " + (i + 1);
            for (int j = 1; j < data1[i].length; j++) {
                data1[i][j] = "" + (i + 1) + ", " + j;
            }
        }
        for (int i = 0; i < data2.length; i++) {
            data2[i][0] = "Company # " + ((i * 2) + 1);
            for (int j = 1; j < data2[i].length; j++) {
                data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
            }
        }
        for (int i = 0; i < data3.length; i++) {
            data3[i][0] = "Company # " + (i * 2);
            for (int j = 1; j < data3[i].length; j++) {
                data3[i][j] = "" + (i * 2) + ", " + j;
            }
        }
        String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
        DefaultTableModel model1 = new DefaultTableModel(data1, headers);
        DefaultTableModel model2 = new DefaultTableModel(data2, headers);
        DefaultTableModel model3 = new DefaultTableModel(data3, headers);
        final JTable jTable1 = new JTable(model1);
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane sp1 = new JScrollPane();
        sp1.setPreferredSize(new Dimension(600, 200));
        sp1.setViewportView(jTable1);
        final JTable jTable2 = new JTable(model2);
        jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane sp2 = new JScrollPane();
        sp2.setPreferredSize(new Dimension(600, 200));
        sp2.setViewportView(jTable2);
        final JTable jTable3 = new JTable(model3);
        jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane sp3 = new JScrollPane();
        sp3.setPreferredSize(new Dimension(600, 200));
        sp3.setViewportView(jTable3);
        //TableSelection tableSelection = new TableSelection(jTable1, jTable2, jTable3);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayout(3, 0, 10, 10));
        panel1.add(sp1);
        panel1.add(sp2);
        panel1.add(sp3);
        JFrame frame = new JFrame("tableSelection");
        frame.add(panel1);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public TableSelection(JTable... tables) {
        for (JTable table : tables) {
            table.getSelectionModel().addListSelectionListener(this);
        }
        this.tables = tables;
    }

    private JTable getTable(Object model) {
        for (JTable table : tables) {
            if (table.getSelectionModel() == model) {
                return table;
            }
        }
        return null;
    }

    private void changeSelection(JTable table, String rowKey) {
        int col = table.convertColumnIndexToView(0);
        for (int row = table.getRowCount(); --row >= 0;) {
            if (rowKey.equals(table.getValueAt(row, col))) {
                table.changeSelection(row, col, false, false);
                return;
            }
        }
        table.clearSelection();
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() || ignore) {
            return;
        }
        ignore = true;
        try {
            JTable table = getTable(e.getSource());
            int row = table.getSelectedRow();
            String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
            for (JTable t : tables) {
                if (t == table) {
                    continue;
                }
                changeSelection(t, rowKey);
                JViewport viewport = (JViewport) t.getParent();
                Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
                Rectangle r2 = viewport.getVisibleRect();
                t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
                System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
            }
        } finally {
            ignore = false;
        }
    }

    public static void main(String[] args) {
        TableSelection tableSelection = new TableSelection();
    }
}

I can't see something that you talking about, that's just full copy of Example from http://www.exampledepot.com/egs/javax.swing.table/pkg.html

for example (here are three JTables too, but another story)

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

public class TableSelection implements ListSelectionListener {

    private JTable[] tables;
    private boolean ignore = false;

    public TableSelection() {
        Object[][] data1 = new Object[100][5];
        Object[][] data2 = new Object[50][5];
        Object[][] data3 = new Object[50][5];
        for (int i = 0; i < data1.length; i++) {
            data1[i][0] = "Company # " + (i + 1);
            for (int j = 1; j < data1[i].length; j++) {
                data1[i][j] = "" + (i + 1) + ", " + j;
            }
        }
        for (int i = 0; i < data2.length; i++) {
            data2[i][0] = "Company # " + ((i * 2) + 1);
            for (int j = 1; j < data2[i].length; j++) {
                data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
            }
        }
        for (int i = 0; i < data3.length; i++) {
            data3[i][0] = "Company # " + (i * 2);
            for (int j = 1; j < data3[i].length; j++) {
                data3[i][j] = "" + (i * 2) + ", " + j;
            }
        }
        String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
        DefaultTableModel model1 = new DefaultTableModel(data1, headers);
        DefaultTableModel model2 = new DefaultTableModel(data2, headers);
        DefaultTableModel model3 = new DefaultTableModel(data3, headers);
        final JTable jTable1 = new JTable(model1);
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane sp1 = new JScrollPane();
        sp1.setPreferredSize(new Dimension(600, 200));
        sp1.setViewportView(jTable1);
        final JTable jTable2 = new JTable(model2);
        jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane sp2 = new JScrollPane();
        sp2.setPreferredSize(new Dimension(600, 200));
        sp2.setViewportView(jTable2);
        final JTable jTable3 = new JTable(model3);
        jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane sp3 = new JScrollPane();
        sp3.setPreferredSize(new Dimension(600, 200));
        sp3.setViewportView(jTable3);
        //TableSelection tableSelection = new TableSelection(jTable1, jTable2, jTable3);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayout(3, 0, 10, 10));
        panel1.add(sp1);
        panel1.add(sp2);
        panel1.add(sp3);
        JFrame frame = new JFrame("tableSelection");
        frame.add(panel1);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public TableSelection(JTable... tables) {
        for (JTable table : tables) {
            table.getSelectionModel().addListSelectionListener(this);
        }
        this.tables = tables;
    }

    private JTable getTable(Object model) {
        for (JTable table : tables) {
            if (table.getSelectionModel() == model) {
                return table;
            }
        }
        return null;
    }

    private void changeSelection(JTable table, String rowKey) {
        int col = table.convertColumnIndexToView(0);
        for (int row = table.getRowCount(); --row >= 0;) {
            if (rowKey.equals(table.getValueAt(row, col))) {
                table.changeSelection(row, col, false, false);
                return;
            }
        }
        table.clearSelection();
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() || ignore) {
            return;
        }
        ignore = true;
        try {
            JTable table = getTable(e.getSource());
            int row = table.getSelectedRow();
            String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
            for (JTable t : tables) {
                if (t == table) {
                    continue;
                }
                changeSelection(t, rowKey);
                JViewport viewport = (JViewport) t.getParent();
                Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
                Rectangle r2 = viewport.getVisibleRect();
                t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
                System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
            }
        } finally {
            ignore = false;
        }
    }

    public static void main(String[] args) {
        TableSelection tableSelection = new TableSelection();
    }
}
呢古 2024-11-12 23:33:56

我刚刚删除了“scrollPane.setSize(1300, 400)”并且它起作用了

I just removed the "scrollPane.setSize(1300, 400)" and it worked

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文