Since Java only supports single inheritance
, I desire to paint
directly on an instance of a JPanel
that is a member of the class Panel
. I grab an instance of Graphics
from the member and then paint whatever I desire onto it.
How can I not inherit from JComponent
or JPanel
and still utilize getGraphics()
for painting on this
without overriding public void paintComponent(Graphics g)
?
private class Panel
{
private JPanel panel;
private Grahics g;
public Panel()
{
panel = new JPanel();
}
public void draw()
{
g = panel.getGraphics();
g.setColor(Color.CYAN);
g.draw(Some Component);
panel.repaint();
}
}
The panel is added to a JFrame
that is made visible prior to calling panel.draw()
. This approach is not working for me and, although I already know how to paint custom components by inheriting from JPanel
and overriding public void paintComponent(Graphics g)
, I did not want to inherit from JPanel
.
then you can do the following get the SomeComponent instance in the panel and modify it
V is a class that extends JFrame and contains the panel in it AND i is instance of SomeComponent
Here are some very simple examples which show how to paint outside
paintComponent
.The drawing actually happens on a
java.awt.image.BufferedImage
, and we can do that anywhere, as long as we're on the Event Dispatch Thread. (For discussion of multithreading with Swing, see here and here.)Then, I'm overriding
paintComponent
, but only to paint the image on to the panel. (I also paint a little swatch in the corner.)This way the drawing is actually permanent, and Swing is able to repaint the panel if it needs to without causing a problem for us. We could also do something like save the image to a file easily, if we wanted to.
It's also possible to set up a
JLabel
with anImageIcon
, although personally I don't like this method. I don't thinkJLabel
andImageIcon
are required by their specifications to see changes we make to the image after we've passed it to the constructors.This way also doesn't let us do stuff like painting the swatch. (For a slightly more complicated paint program, on the level of e.g. MSPaint, we'd want to have a way to select an area and draw a bounding box around it. That's another place we'd want to be able to paint directly on the panel, in addition to drawing to the image.)