1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/* ListDemo.java requires no other files. */
public class ListDemo extends JPanel
implements AdjustmentListener {
private JList list;
private DefaultListModel listModel;
private JScrollPane listScrollPane;
private JScrollBar listScrollBar;
private String cache[]=new String[40];
private int oldrow=0;
public ListDemo() {
super(new BorderLayout());
for (int i=0;i<40;i++)cache[i]="xx"+i;
listModel = new DefaultListModel();
list = new JList(listModel);
for (int i=0;i<40;i++)listModel.addElement(".");
listModel.setElementAt(cache[2], 2);
listModel.setElementAt(cache[3], 3);
listModel.setElementAt(cache[4], 4);
listModel.setElementAt(cache[5], 5);
listModel.setElementAt(cache[6], 6);
listModel.setElementAt(cache[7], 7);
listScrollPane = new JScrollPane(list);
listScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
listScrollBar=listScrollPane.getVerticalScrollBar();
add(listScrollPane, BorderLayout.CENTER);
list.setVisibleRowCount(10);
listScrollBar.addAdjustmentListener(this);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ListDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ListDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void adjustmentValueChanged(AdjustmentEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == listScrollBar){
int newrow=e.getValue()/18;
if (newrow>oldrow && newrow+7<40){
for (int i=oldrow+1;i<=newrow;i++){
listModel.setElementAt(cache[i+7], i+7);
listModel.setElementAt(".", i+1);
}
}
if (newrow<oldrow && newrow>=0){
for (int i=oldrow-1;i>=newrow;i--){
listModel.setElementAt(cache[i+2], i+2);
listModel.setElementAt(".", i+8);
}
}
System.out.println("Adjusted: " +oldrow+"_"+ newrow);
oldrow=newrow;
}
}
} |
Partager