I have design issue here. There two options which sound possible to implement but I don't like neither one.
I need to provide two functionality in my JPanel.
- draw several lines
- draw several strings
ads
- Approach extend twice
If I would need only to draw lines then I can just copy-past solution from the following answer.
Draw a line in a JPanel with button click in Java
public class LinePanel extends JPanel {
...
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
...
But since I need to add second functionality I would need to do something like this
public class LineStringPanel extends JPanel {
which would leave LinePanel just useless intermediate class.
- Create two classes LineDrawer and StringDrawer and pass JPanel as parameter to some method which would perform drawing. The problem here that I would need to call which is not recommended.
Graphics g = panel.getGraphics();
What do you think and can recommend?
UPD: Inside the JPanel there are numerious JLabels as child which represent units and traits.
The lines are relation between some traits of units and Strings are kind of notifications for some actions.
So I want to show String on the top(front) of child JLabels.
Also JPanel is inside JScrollPane.
If you need to draw strings, you can do so directly in the
paintComponent
method (and assuming you don't need anything too fancy, it's pretty easy):Then you could use your trashgod's solution with hardly any changes.
Remember that the coordinates are of the baseline of the text - so if you used
0,0
it wouldn't display on screen.