Java AWT Scrollbar Insets
Three scrollbar objects redScroll, greenScroll, blueScroll and three labels redLabel, greenLabel, blueLabel are created.
p1.setLayout(new GridLayout(3, 2, 5, 5));
Panel p1 is created and layout is set to GridLayout with 3 rows and 2 columns to accommodate three scrollbars and three labels. Horizontal and vertical gaps are given each with 5 pixels.
redScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 0, 0, 255);
redScroll scrollbar is created and properties are set through the constructor.
First 0: It is for initial value where to place the scroll box
Second 0: It is the scroll box size; 0 gives minimum size
Third 0: Gives minimum value
255: Gives the maximum value
The scrollbar moves in between the values 0 to 255.
redScroll.setUnitIncrement(5); //default is 1
redScroll.setBlockIncrement(15); //default is 10
p1.add(redLabel = new Label(“RED”));
setUnitIncrement(5): Sets the value to be jumped when clicked on the arrows of the scroll bar. It is set to 5 and if not set, the default is 1.
setBlockIncrement(15): Sets the value to be jumped when clicked in the space between the arrow and scroll box. It is set to 15 and if not set, the default is 10.
The third scroll bar blueScroll is created in a different way. The default constructor is used to create the object and the values are set later using Scrollbar methods.
blueScroll = new Scrollbar();
The setValue() gives the position of the scroll box on the scrollbar when the frame is created. The setVisibleAmount() gives the scroll box size and 0 gives the minimum size. setMinimum() and setMaximum() methods set the minimum and maximum values in between which the scroll box moves; other way, they give the scrollable values of the scroll bar).
Insets is1 = new Insets(5, 8, 10, 25);
getInsets() is the method of Frame which return an object of Insets class. Insets class gives the margin between the border of the frame and the components inside it. An object of Insets is created with top gap as 5, left gap as 8, bottom gap as 10 and right gap as 25. The Insets object is1 is returned which sets the gap.
int rv = redScroll.getValue();
redLabel.setText(“RED: ” + rv);
The getValue() method of Scrollbar returns the scroll box position on the scroll bar; other way, the scrollbar value. This value rv is displayed as a label redLabel with setText() method.
A Color object clr1 is created by taking the latest values of the three scrollbars and applied to frame with setBackground(clr1) method. Now, as the scrollbars are disturbed the color of the frame changes.
Note: For simplicity, the window closing code is not included. For closing the frame, 4 styles exist and you can apply any one to this program to close the frame. The styles are discussed in " Java Frame Closing – WindowListener".