import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScrollDemo extends JPanel
{
public ScrollDemo()
{
initUI();
}
private void initUI()
{
String []tmp = new String[] {"one", "two", "three", "four", "five"};
String data[] = new String[50];
for(int i=0; i<data.length; i++)
{
data[i] = tmp[i%5];
}
JList list1 = new JList(data);
JList list2 = new JList(data);
final JScrollPane scroll1 = new JScrollPane(list1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
final JScrollPane scroll2 = new JScrollPane(list2, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
class MyAdjustmentListener implements AdjustmentListener
{
Adjustable b1;
Adjustable b2;
boolean adjusting=false;
public MyAdjustmentListener(Adjustable b1, Adjustable b2)
{
this.b1 = b1;
this.b2 = b2;
b1.addAdjustmentListener(this);
b2.addAdjustmentListener(this);
}
// either by the user or programmatically.
public void adjustmentValueChanged(AdjustmentEvent e)
{
if(!adjusting)
{
adjusting = true;
Adjustable target = (e.getAdjustable()==b1)?b2:b1;
target.setValue(e.getAdjustable().getValue());
adjusting = false;
}
}
}
new MyAdjustmentListener(scroll1.getVerticalScrollBar(), scroll2.getVerticalScrollBar());
setLayout(new GridLayout(1,2));
add(scroll1);
add(scroll2);
}
public static void main(String[] args)
{
try
{
final JFrame f = new JFrame("ScrollBar Demo");
f.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.setVisible(false);
System.exit(0);
}
}
);
f.setSize(800, 600);
f.getContentPane().add(new ScrollDemo());
f.setLocationRelativeTo(null);
f.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}