How to make a Java Canvas look raised from its container

By : Clayton

I have a simple GUI component written in Java. The class draws an analog clock in a java.awt.canvas.
This canvas is then contained in a JFrame - What I want to do is give the canvas a 3d "raised" effect - almost like adding a drop shadow to a photo. Is there a simple way to do this?

By : Clayton


If you were using a Swing element, you'd use the createRaisedBevelBorder() method of the BorderFactory and set the canvas' border to the resulting border. Canvas is an AWT component, so you'll need to wrap it in a Swing component to which you can set the border.

If you are using a JFrame, then you have two options:

  1. Add your own component to a JPanel first and then add this to the JFrame.

  2. Instead of inheriting from java.awt.Canvas, you can inherit from JComponent. Then you would have to do all your painting in the paintComponent() Method instead of just paint() (you can just rename your current paint method).

In both cases you can now set a border with the setBorder() Method (on the JPanel or your component) you can get from BorderFactory.

See also: How to Use Borders

This video can help you solving your question :)
By: admin