问题描述
我在这里有设计问题.听起来有两种方法可以实现,但我都不喜欢.
I have design issue here. There two options which sound possible to implement but I don't like neither one.
我需要在我的JPanel中提供两个功能.
I need to provide two functionality in my JPanel.
- 画几行
- 画几串
广告
- 方法扩展了两次
如果我只需要画线,那么我可以从以下答案中复制粘贴解决方案.
If I would need only to draw lines then I can just copy-past solution from the following answer.
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 {
这会使LinePanel变成无用的中间类.
which would leave LinePanel just useless intermediate class.
- 创建两个类LineDrawer和StringDrawer,并将JPanel作为参数传递给将执行绘制的某些方法.我不建议在这里打电话的问题.
Graphics g = panel.getGraphics();
您如何看待并可以推荐?
What do you think and can recommend?
UPD:在JPanel中,有许多JLabel作为子代,代表了单位和特征.
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.
所以我想在子JLabel的顶部(前面)显示String.
So I want to show String on the top(front) of child JLabels.
JPanel也位于JScrollPane中.
Also JPanel is inside JScrollPane.
推荐答案
如果需要绘制字符串,您可以直接在paintComponent
方法中这样做(并假设您不需要任何花哨的东西,这都很容易):
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.
请记住,坐标是文本的基线-因此,如果使用0,0
,它将不会显示在屏幕上.
Remember that the coordinates are of the baseline of the text - so if you used 0,0
it wouldn't display on screen.
这篇关于设计:两次扩展JPanel或将JPanel作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!