简体   繁体   English

在JPanel外部可以看到JPanel中的图形

[英]Make Graphics from JPanel visible outside JPanel

I have a rectangle which I move along the JPanel using repaint() . 我有一个矩形,我使用repaint()沿着JPanel移动。 When the position of the rectangle reaches a position outside the JPanel it is not visible anymore. 当矩形的位置到达JPanel外部的位置时,它不再可见。 How can I make it visible outside the JPanel? 如何在JPanel外部显示它?

This my paint method: 这是我的绘画方法:

public void paintComponent (Graphics g) {
    g.setColor(Color.red);
    g.fillRect(dist, 0, 10, 10);
    dist++;
}

Update: 更新:

I have multiple JPanels in the JFrame which I positioned using the GridBagLayout. 我在JFrame中有多个JPanel,我使用GridBagLayout定位。 The JPanels represent Lanes in a Street and the rectangles cars. JPanels代表街道上的车道和矩形车。 The reason to make the rectangles visible outside their JPanel is to have the cars change lanes. 在JPanel外部显示矩形的原因是让汽车改变车道。 The JPanel seemed suitable to me, to set the first position of a car. JPanel似乎适合我,设置汽车的第一个位置。

Is there a better solution for this problem? 这个问题有更好的解决方案吗?

You state: 你说:

I have a rectangle which I move along the JPanel using repaint(). 我有一个矩形,我使用repaint()沿着JPanel移动。 When the position of the rectangle reaches a position outside the JPanel it is not visible anymore. 当矩形的位置到达JPanel外部的位置时,它不再可见。 How can I make it visible outside the JPanel? 如何在JPanel外部显示它?

If the JPanel is drawing it, the short answer is: "you can't". 如果JPanel正在绘制它,简短的答案是:“你不能”。

The longer answer will depend on just where you're trying to draw the JPanel and how the rest of your GUI is set up. 更长的答案取决于您尝试绘制JPanel的位置以及GUI的其余部分是如何设置的。


Edit 编辑
You now state: 你现在说:

I have multiple JPanels in the JFrame which I positioned using the GridBagLayout. 我在JFrame中有多个JPanel,我使用GridBagLayout定位。 The JPanels represent Lanes in a Street and the rectangles cars. JPanels代表街道上的车道和矩形车。 The reason to make the rectangles visible outside their JPanel is to have the cars change lanes. 在JPanel外部显示矩形的原因是让汽车改变车道。 The JPanel seemed suitable to me, to set the first position of a car. JPanel似乎适合我,设置汽车的第一个位置。

If I coded the way you were doing it, I wouldn't have these local JPanels draw the car but rather would have the car be its own sprite that exists on a different layer from the streets, perhaps using a JLayeredPane. 如果我按照你的方式进行编码,我不会让这些本地JPanels绘制汽车,而是让汽车成为自己的精灵,存在于街道的不同层上,可能使用JLayeredPane。 It could exist in its own JPanel that encompasses your entire map, as long as this JPanel is not opaque. 只要此JPanel不是不透明的,它就可以存在于自己的JPanel中,它包含整个地图。 Then you could move the car any which way you'd like. 然后你可以按照自己喜欢的方式移动汽车。

如前所述,如果你想让它占据更大的区域,你应该使JPanel更大或者将paintComponent放在父组件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM