Java Reference
In-Depth Information
new JScrollBar(JScrollBar.HORIZONTAL);
8
9
private JScrollBar jscbVert =
vertical scroll bar
new JScrollBar(JScrollBar.VERTICAL);
10
11
12
// Create a MessagePanel
13
private MessagePanel messagePanel =
14
new MessagePanel( "Welcome to Java" );
15
16 public static void main(String[] args) {
17 ScrollBarDemo frame = new ScrollBarDemo();
18 frame.setTitle( "ScrollBarDemo" );
19 frame.setLocationRelativeTo( null ); // Center the frame
20 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
21 frame.pack();
22 frame.setVisible( true );
23 }
24
25 public ScrollBarDemo() {
26 // Add scroll bars and message panel to the frame
27 setLayout( new BorderLayout());
28 add(messagePanel, BorderLayout.CENTER);
29 add(jscbVert, BorderLayout.EAST);
30 add(jscbHort, BorderLayout.SOUTH);
31
32
create frame
create UI
add scroll bar
// Register listener for the scroll bars
33
34 @Override
35 public void adjustmentValueChanged(AdjustmentEvent e) {
36 // getValue() and getMaximumValue() return int, but for better
37 // precision, use double
38 double value = jscbHort.getValue();
39 double maximumValue = jscbHort.getMaximum();
40 double newX = (value * messagePanel.getWidth() /
41 maximumValue);
42 messagePanel.setXCoordinate(( int )newX);
43 }
44 });
45
46 @Override
47 public void adjustmentValueChanged(AdjustmentEvent e) {
48 // getValue() and getMaximum() return int, but for better
49 // precision, use double
50 double value = jscbVert.getValue();
51 double maximumValue = jscbVert.getMaximum();
52 double newY = (value * messagePanel.getHeight() /
53 maximumValue);
54 messagePanel.setYCoordinate(( int )newY);
55 }
56 });
57 }
58 }
jscbHort.addAdjustmentListener( new AdjustmentListener() {
adjustment listener
jscbVert.addAdjustmentListener( new AdjustmentListener() {
adjustment listener
The program creates two scroll bars ( jscbVert and jscbHort ) (lines 7-10) and an instance
of MessagePanel ( messagePanel ) (lines 13-14). messagePanel is placed in the center of
the frame (line 28); jscbVert and jscbHort are placed in the east and south sections of the
frame (lines 29-30), respectively.
You can specify the orientation of the scroll bar in the constructor or use the
setOrientation method. By default, the property value is 100 for maximum , 0 for
minimum , 10 for blockIncrement , and 10 for visibleAmount .
 
Search WWH ::




Custom Search