Design: extend JPanel twice or pass JPanel as para

2019-09-08 18:00发布

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

  1. 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.

  1. 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.

Performing Custom Painting

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.

1条回答
对你真心纯属浪费
2楼-- · 2019-09-08 18:35

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):

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    ...
    g.drawLine(p1.x, p1.y, p2.x, p2.y);
    ...
    g.setColor(Color.black);
    g.drawString("My Text", 0, 20);
}

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.

查看更多
登录 后发表回答