How to draw a point in Java

How to draw a point with code example


When working with graphics in JAVA there will most certain be situations when one would like to draw a single point (or pixel) on the screen. However when checking the API for the help class of drawing 2D objects: Graphics2D one finds no apparent method for drawing just a single pixel. Most likely has this method been considered superfluous by Oracle (or SUN) since it exists many ways of drawing a point by the methods implemented in the Graphics class.

Here follows a snippet where a point is drawn, this is done by using the Graphics object of the component we are painting on, e.g. a JPanel. Note that this kind of “free painting” is in general done in an overridden paintComponent() method. In a swing program you should be careful with overriding the paint() method since it takes care of, for instance, painting of borders and children as well.

...
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); //clears previous painted stuff and draws background
int x = 10;
int y = 15;
g.setColor(new Color(255, 0, 0)); //set color to red (r, g, b)
g.drawLine(x, y, x, y);
}
...

This does the trick of drawing a red point at position (x, y). If you rather want to use the Graphics2D class which is an extension of the ordinary Graphics class this is of course also possible. The Graphics2D class is in some cases more convenient to use and has greater possibilities of, for instance, drawing curved shapes and 3D rectangles. Here is a snippet on how to draw a point using Graphics2D:

...
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); //clears previous painted stuff and draws background
Graphics2D g2 = (Graphics2D) g;
int x = 10;
int y = 15;
g2.setColor(new Color(255, 0, 0)); //set color to red (r, g, b)
g2.draw(new Line2D.Double(x, y, x, y));
}
...
Laddar kommentarer...