# Java: Antialiasing

## Antialiased versus Aliased Graphics

When lines are drawn on the screen, vertical and horizontal lines appear perfectly straight. However, when they are on a diagonal, especially near vertical or horizontal, "jaggies" appear, giving the line a step-like appearance. This can be avoided in Java 2's Graphics2D class by requesting that edges are antialiased.

    @Override public void paintComponent(Graphics g) {
        //... Downcast to a Graphics2D context.
       Graphics2D g2 = (Graphics2D)g;
       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

        //... Paint background.
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, getWidth(), getHeight());
        g2.setColor(Color.BLACK);

        //... Use g2 for all graphics operations.
        g2.drawLine(0, 0, 100, 80);
        . . .
    }

## Casting to Graphics2D

The downcast in the above example from type Graphics to Graphics2D is possible because Graphics2D is a subclass of Graphics, and the parameter of the `paintComponent` method is already a Graphics2D object, altho it is declared as its superclass, `Graphics`.

## More on antialiasing

An interesting, altho somewhat advanced, article on antialiasing can be found at Wikipedia, Anti-aliasing.