简体   繁体   中英

Make Graphics from JPanel visible outside JPanel

I have a rectangle which I move along the JPanel using repaint() . When the position of the rectangle reaches a position outside the JPanel it is not visible anymore. How can I make it visible outside the 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. The JPanels represent Lanes in a Street and the rectangles cars. The reason to make the rectangles visible outside their JPanel is to have the cars change lanes. The JPanel seemed suitable to me, to set the first position of a car.

Is there a better solution for this problem?

You state:

I have a rectangle which I move along the JPanel using repaint(). When the position of the rectangle reaches a position outside the JPanel it is not visible anymore. How can I make it visible outside the JPanel?

If the JPanel is drawing it, the short answer is: "you can't".

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.


Edit
You now state:

I have multiple JPanels in the JFrame which I positioned using the GridBagLayout. The JPanels represent Lanes in a Street and the rectangles cars. The reason to make the rectangles visible outside their JPanel is to have the cars change lanes. The JPanel seemed suitable to me, to set the first position of a car.

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. It could exist in its own JPanel that encompasses your entire map, as long as this JPanel is not opaque. Then you could move the car any which way you'd like.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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