Search code examples
javaswingjpaneljlabelgraphics2d

Draw lines on JLabel


I am trying to make an rpg using swing (yes it is stupid I agree, but I am doing this for learning rather than actual working product). And currently I am working on each character stat.

I have a JPanel, and I would like to draw a line.

My intention is to have something similar to this
The middle part is JPanel

The left side is a JPanel that has two components, table 1, and JLabel. Right side is also JPanel that has it's own elements but that is another story.

My question is that I would like to create a jpanel that would only have an image, and that image will be two lines going to the corners in relation to the selected element in the table.

But unfortunately I do not know how to go about drawing custom image on the JLabel. Can anyone suggest a way of going about drawing my own lines and everything on a JLabel? I have looked at a lot of questions, but they show how to draw already created image onto the JLabel, but I would liek to draw my own stuff (just the two lines).


Solution

  • Can anyone suggest a way of going about drawing my own lines and everything on a JLabel?

    Draw to the Graphics2D of a BufferedImage. Display the image (in an ImageIcon) in the label.

    E.G.

    1. Drawing text to an image.
    2. Drawing a border (animated).
    3. Another text demo., this one using scaling & fading.
    4. Oh, and here's one with simple lines (..and dots, ..and it is animated).

    I am trying to make an rpg using swing (yes it is stupid I agree, but I am doing this for learning ..

    I don't think it is stupid at all. Swing components are the only way to go if the choice is Swing or AWT. Not only is the toolkit much richer (show me the AWT equivalent of ImageIcon, JTree, JTable,..) but has double buffering by default, and is directly built on the AWT. I stressed that last part because it is often the case with games, where we override paint and 'go for it' - paint every pixel.

    Once that is done, it is typically 'all AWT'. The examples I posted use no AWT Components, yet all use a BufferedImage, some use GlyphVector or AffineTransform, either Graphics (when I' feeling lazy) or Graphics2D (for those wonderful rendering hints..).

    But taking it a step even further and a 'Swing' splash screen or full screen window is also pure AWT.

    For the clickable/editable components, use Swing. For custom rendering, and corner cases like the splash or FSW, reach for the AWT classes.