argius note

プログラミング関連

2つのJTableを同時にスクロール

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.table.*;

public final class Test extends JFrame implements AdjustmentListener {

    private JScrollBar scrollbar1;
    private JScrollBar scrollbar2;

    public Test() {
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JTable table1 = new JTable(500, 1);
        JTable table2 = new JTable(500, 1);
        for (int i = 0; i < 500; i++) {
            String s = String.valueOf(i + 1);
            table1.setValueAt(s, i, 0);
            table2.setValueAt(s, i, 0);
        }
        JScrollPane pane1 = new JScrollPane(table1);
        JScrollPane pane2 = new JScrollPane(table2);
        this.scrollbar1 = pane1.getVerticalScrollBar();
        this.scrollbar2 = pane2.getVerticalScrollBar();
        pane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        pane2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        pane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        pane2.getVerticalScrollBar().addAdjustmentListener(this);
        JPanel p = new JPanel(new GridLayout(1, 2));
        p.add(pane1);
        p.add(pane2);
        getContentPane().add(p);
    }

    public void adjustmentValueChanged(AdjustmentEvent e) {
        scrollbar1.setValue(scrollbar2.getValue());
    }

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

            public void run() {
                JFrame f = new Test();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }

        });
    }

}