How can I draw simplest eyes in Java's swing ? I would like to get something like that :
+3
A:
Use Graphics class methods:
- fillRect
- fillOval
And similar methods to accomplish what you are trying to on a JPanel.
Example:
public class Eyes extends JPanel
{
// override paint
@Override
protected void paintComponent(Graphics g)
{
super(g);
// use fillRect, fillOval and color methods
// on "g" to draw what you want
}
}
Then, of course, you will place Eyes object inside a JInternalFrame, other JPanel or container as you need.
Pablo Santa Cruz
2010-05-10 00:10:20
+1 Also, "Swing programs should override `paintComponent()` instead of overriding paint()." http://java.sun.com/products/jfc/tsc/articles/painting/index.html
trashgod
2010-05-10 03:29:45
@trashgod: thanks. changed the code sample to reflect what you suggested.
Pablo Santa Cruz
2010-05-10 11:38:12
+1
A:
To draw a filled circle with a outline in a different color, you can use drawOval
in addition to fillOval
(don't forget to change the color on the Graphics
context before drawing the outline).
You should also investigate the Grahpics2D
class, which has a lot more functionality than the regular Graphics
object. (You can simply cast a Graphics
instance as a Graphics2D
).
In particular, to make the circles look "nice", you may want to set the anti-aliasing rendering hint. You can do this as follows:
Graphics2D g2d = (Graphics2D)g;
// Turn anti-aliasing on.
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Draw everything you want...
// Turn anti-aliasing off again.
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Ash
2010-05-10 10:37:48