Java Reference
In-Depth Information
Most custom components need to overwrite two additional methods that are important for the
appropriate layout of the component. The methods
getMinimumSize()
and
getPreferredSize()
are used by layout managers to query the size information of the component.
Overwriting these methods with custom implementations makes sure that the component is displayed
in an appropriate size.
Listing 4.6
ProgressBar.java
import java.awt.*;
public class ProgressBar extends Component {
int currentValue = 0;
final int MAX_VALUE = 100;
public ProgressBar() {
}
public void setValue (int currentValue) {
if (currentValue >= 0
&& currentValue <= MAX_VALUE) {
this.currentValue = currentValue;
}
}
public Dimension getPreferredSize() {
return new Dimension (100, 20);
}
public Dimension getMinimumSize() {
return new Dimension (10, 10);
}
public void paint (Graphics g) {
Dimension dim = getSize();
int progressPosition = (dim.width-4) * currentValue /
MAX_VALUE;
g.setColor (Color.black);
g.drawRect (0, 0, dim.width-1, dim.height-1);
g.setColor (Color.white);
g.drawRect (1, 1, dim.width-3, dim.height-3);
g.setColor (SystemColor.activeCaption);
g.fillRect (2, 2, progressPosition, dim.height-4);
g.setColor (Color.white);
g.fillRect (progressPosition + 2, 2,
dim.width - progressPosition - 4, dim.height-4);
}
}
For testing purposes, we provide a small application shown in
Listing 4.7
to show how the
ProgressBar
can be integrated into a MIDlet; the application is shown in
Figure 4.8
.
The
application just provides a
Scrollbar
for setting the current progress value and the
ProgressBar
Search WWH ::
Custom Search