You are here:Home » Java Swing » Painting in Java Swing

Painting in Java Swing

Painting in Swing

Painting is used, when we want to change or enhance an existing widget. Or if we are creating a custom widget from scratch. To do the painting, we use the painting API provided by the Swing toolkit.
The painting is done within the paintComponent() method. In the painting process, we use the Graphics2D object.

2D Vector Graphics

There are two different computer graphics. Vector and raster graphics. Raster graphics represents images as a collection of pixels. Vector graphics is the use of geometrical primitives such as points, lines, curves or polygons to represent images. These primitives are created using mathematical equations.
Both types of computer graphics have advantages and disadvantages. The advantages of vector graphics over raster are:
  • smaller size
  • ability to zoom indefinitely
  • moving, scaling, filling or rotating does not degrade the quality of an image

Types of primitives

  • points
  • lines
  • polylines
  • polygons
  • circles
  • ellipses
  • Splines

Points

The most simple graphics primitive is point. It is a single dot on the window. There is no method to draw a point in Swing. To draw a point, we use the drawLine() method. We use one point twice.
package zetcode;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


class DrawPanel extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.blue);

for (int i = 0; i <= 1000; i++) {
Dimension size = getSize();
Insets insets = getInsets();

int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;

Random r = new Random();
int x = Math.abs(r.nextInt()) % w;
int y = Math.abs(r.nextInt()) % h;
g2d.drawLine(x, y, x, y);
}

}
}

public class PointsExample extends JFrame {

public PointsExample() {
initUI();
}

public final void initUI() {

DrawPanel dpnl = new DrawPanel();
add(dpnl);

setSize(250, 200);
setTitle("Points");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {
PointsExample ex = new PointsExample();
ex.setVisible(true);
}
});
}
}
One point is difficult to observe. Why not paint 1000 of them. In our example, we do so. We draw 1000 blue points on the panel.
class DrawPanel extends JPanel {
We are drawing on a custom drawing panel, which is a JPanel component. The drawing panel will later be added to a JFrame component.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
The painting is performed inside the paintComponent()method.
Graphics2D g2d = (Graphics2D) g;
Painting in Swing is done on the Graphics2D object.
g2d.setColor(Color.blue);
We will paint our points in blue color.
Dimension size = getSize();
Insets insets = getInsets();
The size of the window includes borders and titlebar. We don't paint there.
int w =  size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;
Here we calculate the area, where we will effectively paint our points.
Random r = new Random();
int x = Math.abs(r.nextInt()) % w;
int y = Math.abs(r.nextInt()) % h;
We get a random number in range of the size of area, that we computed above.
g2d.drawLine(x, y, x, y);
Here we draw the point. As I already said, we use a drawLine() method. We specify the same point twice.
Points
Figure: Points

Lines

A line is a simple graphics primitive. It is drawn using two points.
package zetcode;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;



class DrawPanel extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

float[] dash1 = { 2f, 0f, 2f };
float[] dash2 = { 1f, 1f, 1f };
float[] dash3 = { 4f, 0f, 2f };
float[] dash4 = { 4f, 4f, 1f };

g2d.drawLine(20, 40, 250, 40);

BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f );

BasicStroke bs2 = new BasicStroke(1, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 1.0f, dash2, 2f );

BasicStroke bs3 = new BasicStroke(1, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 1.0f, dash3, 2f );

BasicStroke bs4 = new BasicStroke(1, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 1.0f, dash4, 2f );

g2d.setStroke(bs1);
g2d.drawLine(20, 80, 250, 80);

g2d.setStroke(bs2);
g2d.drawLine(20, 120, 250, 120);

g2d.setStroke(bs3);
g2d.drawLine(20, 160, 250, 160);

g2d.setStroke(bs4);
g2d.drawLine(20, 200, 250, 200);

}
}

public class LinesExample extends JFrame {

public LinesExample() {
initUI();
}

public final void initUI() {

DrawPanel dpnl = new DrawPanel();
add(dpnl);

setSize(280, 270);
setTitle("Lines");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {
LinesExample ex = new LinesExample();
ex.setVisible(true);
}
});
}
}
In the example, we draw five lines. The first line is drawn using the default values. Other will have a different stroke. The stroke is created using the BasicStroke class. It defines a basic set of rendering attributes for the outlines of graphics primitives.
float[] dash1 = { 2f, 0f, 2f };
Here we create a dash, that we use in the stroke object.
BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT, 
BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f )
This code creates a stroke. The stroke defines the line width, end caps, line joins, miter limit, dash and the dash phase.
Lines
Figure: Lines

Rectangles

To draw rectangles, we use the drawRect() method. To fill rectangles with the current color, we use the fillRect() method.
package zetcode;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


class DrawPanel extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(new Color(212, 212, 212));
g2d.drawRect(10, 15, 90, 60);
g2d.drawRect(130, 15, 90, 60);
g2d.drawRect(250, 15, 90, 60);
g2d.drawRect(10, 105, 90, 60);
g2d.drawRect(130, 105, 90, 60);
g2d.drawRect(250, 105, 90, 60);
g2d.drawRect(10, 195, 90, 60);
g2d.drawRect(130, 195, 90, 60);
g2d.drawRect(250, 195, 90, 60);

g2d.setColor(new Color(125, 167, 116));
g2d.fillRect(10, 15, 90, 60);

g2d.setColor(new Color(42, 179, 231));
g2d.fillRect(130, 15, 90, 60);

g2d.setColor(new Color(70, 67, 123));
g2d.fillRect(250, 15, 90, 60);

g2d.setColor(new Color(130, 100, 84));
g2d.fillRect(10, 105, 90, 60);

g2d.setColor(new Color(252, 211, 61));
g2d.fillRect(130, 105, 90, 60);

g2d.setColor(new Color(241, 98, 69));
g2d.fillRect(250, 105, 90, 60);

g2d.setColor(new Color(217, 146, 54));
g2d.fillRect(10, 195, 90, 60);

g2d.setColor(new Color(63, 121, 186));
g2d.fillRect(130, 195, 90, 60);

g2d.setColor(new Color(31, 21, 1));
g2d.fillRect(250, 195, 90, 60);
}
}

public class RectanglesExample extends JFrame {

public RectanglesExample() {
initUI();
}

public final void initUI() {

DrawPanel dpnl = new DrawPanel();
add(dpnl);

setSize(360, 300);
setTitle("Rectangles");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {
RectanglesExample ex = new RectanglesExample();
ex.setVisible(true);
}
});
}
}
In the example we draw nine colored rectangles.
g2d.setColor(new Color(212, 212, 212));
g2d.drawRect(10, 15, 90, 60);
...
We set the color of the outline of the rectangle to a soft gray color, so that it does not interfere with the fill color. To draw the outline of the rectangle, we use the drawRect() method. The first two parameters are the x and y values. The third and fourth are width and height.
g2d.fillRect(10, 15, 90, 60);
To fill the rectangle with a color, we use the fillRect() method.
Rectangles
Figure: Rectangles

Textures

A texture is a bitmap image applied to the surface in computer graphics. Besides colors and gradients, we can fill our graphics shapes with textures.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;


public class Textures extends JPanel {


public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(new Color(212, 212, 212));
g2d.drawRect(10, 15, 90, 60);
g2d.drawRect(130, 15, 90, 60);
g2d.drawRect(250, 15, 90, 60);
g2d.drawRect(10, 105, 90, 60);
g2d.drawRect(130, 105, 90, 60);
g2d.drawRect(250, 105, 90, 60);

BufferedImage bimage1 = null;
BufferedImage bimage2 = null;
BufferedImage bimage3 = null;
BufferedImage bimage4 = null;
BufferedImage bimage5 = null;
BufferedImage bimage6 = null;

URL url1 = ClassLoader.getSystemResource("texture1.png");
URL url2 = ClassLoader.getSystemResource("texture2.png");
URL url3 = ClassLoader.getSystemResource("texture3.png");
URL url4 = ClassLoader.getSystemResource("texture4.png");
URL url5 = ClassLoader.getSystemResource("texture5.png");
URL url6 = ClassLoader.getSystemResource("texture6.png");

try {
bimage1 = ImageIO.read(url1);
bimage2 = ImageIO.read(url2);
bimage3 = ImageIO.read(url3);
bimage4 = ImageIO.read(url4);
bimage5 = ImageIO.read(url5);
bimage6 = ImageIO.read(url6);
} catch (IOException ioe) {
ioe.printStackTrace();
}

Rectangle rect1 = new Rectangle(0, 0,
bimage1.getWidth(), bimage1.getHeight());

Rectangle rect2 = new Rectangle(0, 0,
bimage2.getWidth(), bimage2.getHeight());

Rectangle rect3 = new Rectangle(0, 0,
bimage3.getWidth(), bimage3.getHeight());

Rectangle rect4 = new Rectangle(0, 0,
bimage4.getWidth(), bimage4.getHeight());

Rectangle rect5 = new Rectangle(0, 0,
bimage5.getWidth(), bimage5.getHeight());

Rectangle rect6 = new Rectangle(0, 0,
bimage6.getWidth(), bimage6.getHeight());

TexturePaint texture1 = new TexturePaint(bimage1, rect1);
TexturePaint texture2 = new TexturePaint(bimage2, rect2);
TexturePaint texture3 = new TexturePaint(bimage3, rect3);
TexturePaint texture4 = new TexturePaint(bimage4, rect4);
TexturePaint texture5 = new TexturePaint(bimage5, rect5);
TexturePaint texture6 = new TexturePaint(bimage6, rect6);

g2d.setPaint(texture1);
g2d.fillRect(10, 15, 90, 60);

g2d.setPaint(texture2);
g2d.fillRect(130, 15, 90, 60);

g2d.setPaint(texture3);
g2d.fillRect(250, 15, 90, 60);

g2d.setPaint(texture4);
g2d.fillRect(10, 105, 90, 60);

g2d.setPaint(texture5);
g2d.fillRect(130, 105, 90, 60);

g2d.setPaint(texture6);
g2d.fillRect(250, 105, 90, 60);
}

public static void main(String[] args) {

Textures rects = new Textures();
JFrame frame = new JFrame("Textures");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(rects);
frame.setSize(360, 210);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

}
}
In our example, we will draw six rectangles filled with different textures. To work with textures, Java Swing has a TexturePaint class.
BufferedImage bimage1 = null;
...
URL url1 = ClassLoader.getSystemResource("texture1.png");
...
bimage1 = ImageIO.read(url1);
We read an image into the memory.
Rectangle rect1 = new Rectangle(0, 0,
bimage1.getWidth(), bimage1.getHeight());
We get the size of the texture image.
TexturePaint texture1 = new TexturePaint(bimage1, rect1);
Here we create a TexturePaint object. The parameters are a buffered image and a rectangle of the image. The rectangle is used to anchor and replicate the image. The images are tiled.
g2d.setPaint(texture1);
g2d.fillRect(10, 15, 90, 60);
Here we apply the texture and fill the rectangle with it.
Textures
Figure: Textures

Gradients

In computer graphics, gradient is a smooth blending of shades from light to dark or from one color to another. In 2D drawing programs and paint programs, gradients are used to create colorful backgrounds and special effects as well as to simulate lights and shadows. (answers.com)
package zetcode;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawPanel extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;
GradientPaint gp1 = new GradientPaint(5, 5,
Color.red, 20, 20, Color.black, true);

g2d.setPaint(gp1);
g2d.fillRect(20, 20, 300, 40);

GradientPaint gp2 = new GradientPaint(5, 25,
Color.yellow, 20, 2, Color.black, true);

g2d.setPaint(gp2);
g2d.fillRect(20, 80, 300, 40);

GradientPaint gp3 = new GradientPaint(5, 25,
Color.green, 2, 2, Color.black, true);

g2d.setPaint(gp3);
g2d.fillRect(20, 140, 300, 40);

GradientPaint gp4 = new GradientPaint(25, 25,
Color.blue, 15, 25, Color.black, true);

g2d.setPaint(gp4);
g2d.fillRect(20, 200, 300, 40);

GradientPaint gp5 = new GradientPaint(0, 0,
Color.orange, 0, 20, Color.black, true);

g2d.setPaint(gp5);
g2d.fillRect(20, 260, 300, 40);
}
}

public class GradientsExample extends JFrame {

public GradientsExample() {
initUI();
}

public final void initUI() {

DrawPanel dpnl = new DrawPanel();
add(dpnl);

setSize(350, 350);
setTitle("Gradients");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {
GradientsExample ex = new GradientsExample();
ex.setVisible(true);
}
});
}
}
Our code example presents five rectangles with gradients.
GradientPaint gp4 = new GradientPaint(25, 25, 
Color.blue, 15, 25, Color.black, true);
To work with gradients, we use Java Swing's GradientPaint class. By manipulating the color values and the starting end ending points, we can get interesting results.
g2d.setPaint(gp5);
The gradient is activated calling the setPaint() method.
Gradients
Figure: Gradients

Drawing text

Drawing is done with the drawString() method. We specify the string we want to draw and the position of the text on the window area.
import java.awt.Font;
package zetcode;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawPanel extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);

Font font = new Font("URW Chancery L", Font.BOLD, 21);
g2d.setFont(font);

g2d.drawString("Not marble, nor the gilded monuments", 20, 30);
g2d.drawString("Of princes, shall outlive this powerful rhyme;", 20, 60);
g2d.drawString("But you shall shine more bright in these contents",
20, 90);
g2d.drawString("Than unswept stone, besmear'd with sluttish time.",
20, 120);
g2d.drawString("When wasteful war shall statues overturn,", 20, 150);
g2d.drawString("And broils root out the work of masonry,", 20, 180);
g2d.drawString("Nor Mars his sword, nor war's quick "
+ "fire shall burn", 20, 210);
g2d.drawString("The living record of your memory.", 20, 240);
g2d.drawString("'Gainst death, and all oblivious enmity", 20, 270);
g2d.drawString("Shall you pace forth; your praise shall still "
+ "find room", 20, 300);
g2d.drawString("Even in the eyes of all posterity", 20, 330);
g2d.drawString("That wear this world out to the ending doom.", 20, 360);
g2d.drawString("So, till the judgment that yourself arise,", 20, 390);
g2d.drawString("You live in this, and dwell in lovers' eyes.", 20, 420);
}
}

public class TextExample extends JFrame {

public TextExample() {
initUI();
}

public final void initUI() {

DrawPanel dpnl = new DrawPanel();
add(dpnl);

setSize(500, 470);
setTitle("Sonnet55");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {
TextExample ex = new TextExample();
ex.setVisible(true);
}
});
}
}
In our example, we draw a sonnet on the panel component.
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);
This code is to make our text look better. We apply a technique called antialiasing.
Font font = new Font("URW Chancery L", Font.BOLD, 21);
g2d.setFont(font);
We choose a nice font for our text.
g2d.drawString("Not marble, nor the gilded monuments", 20, 30);
This is the code, that draws the text.

Images

On of the most important capabililies of a toolkit is the ability to display images. An image is an array of pixels. Each pixel represents a color at a given position. We can use components like JLabel to display an image, or we can draw it using the Java 2D API.
package zetcode;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawPanel extends JPanel {

Image img;

public DrawPanel(Image img) {
this.img = img;
Dimension dm = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(dm);
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.drawImage(this.img, 0, 0, null);
}
}

public class ImageExample extends JFrame {

public ImageExample() {
initUI();
}

public final void initUI() {

Image img = new ImageIcon("slanec.png").getImage();

DrawPanel dpnl = new DrawPanel(img);
add(dpnl);

setTitle("Image");
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {
ImageExample ex = new ImageExample();
ex.setVisible(true);
}
});
}
}
This example will draw an image on the panel. The image will fit the JFrame window.
public DrawPanel(Image img) {
this.img = img;
Dimension dm = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(dm);
}
We determine the image dimensions and set the preffered size of the panel component. This will together with the pack()method display the image to fit exactly the window.
g2d.drawImage(this.img, 0, 0, null);
The image is drawn using the drawImage() method.
Image img = new ImageIcon("slanec.png").getImage();
We load the image using the ImageIcon class. This class simplyfies the work with the images in Java Swing.
In this chapter, we did some painting.

0 comments:

Post a Comment