Home Segments Top Top Previous Next

1113: Mainline

It is easy to adapt an existing program, such as the meter program shown in Segment 748, to work with the Graphics2D class, instead of with the Graphics class. Because the Graphics2D class is a subclass of the Graphics class, all the methods in the Graphics class still work. All you need to do is to cast the Graphics instance supplied as the paint method's argument into an instance of the Graphics2D class, and then to work with that instance of the Graphics2D class.

import java.awt.*;
import javax.swing.*;
public class Meter extends JComponent implements MeterInterface {
 String title = "Title to Be Supplied";
 int minValue, maxValue, value;
 public Meter (int x, int y) {
  minValue = x; maxValue = y; value = (y + x) / 2;
 }
 public void setValue(int v) {value = v; repaint();}
 public void setTitle(String t) {title = t; repaint();}
 public void paint(Graphics x) {                        
  Graphics2D g = (Graphics2D) x;                        
// Rest of paint as in Segment 748 
 } 
 public Dimension getMinimumSize() {return new Dimension(150, 100);}  
 public Dimension getPreferredSize() {return new Dimension(150, 100);}  
} 

Note that there is no getValueAtCoordinates method, as defined in Segment 748, as that method is not relevent to the explanation of the methods of the Graphics2D clas.