Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to see if a something in Graphics2D is off the frame
    text
    copied!<p>I have a <code>paint</code> method that I have draw a rectangle and move it across the screen and what I want it to do I when the rectangle goes off the screen to move it back to the start of the JFrame. I assume it would be something like <code>if(rectangle.isoffthescreen){ put it back on the screen }</code> but I don't know how to do that. Also, I want to know if you can do something to the rect like <code>JFrame frame = new JFrame();</code>, but for obviously for the rectangle. I'm sorry if this is confusing. </p> <p>@MadProgrammer Here is where I am at so far</p> <pre><code>public class main extends JPanel { public static int place = -350; public Rectangle rect; public int xDelta; public main() { rect = new Rectangle(0, 75, 50, 50); xDelta = 4; Timer timer = new Timer(40, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { rect.x += xDelta; if (rect.x + rect.width &gt; getWidth() - 1) { rect.x = getWidth() - rect.width; xDelta *= -1; } else if (rect.x &lt; 0) { rect.x = 0; xDelta *= -1; } repaint(); } }); timer.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D) g.create(); Random r = new Random(); int r1; r1 = r.nextInt(5); if (r1 == 0) { g2d.setColor(Color.WHITE); } else if (r1 == 1) { g2d.setColor(Color.BLUE); } else if (r1 == 2) { g2d.setColor(Color.RED); } else if (r1 == 3) { g2d.setColor(Color.GREEN); } else if (r1 == 4) { g2d.setColor(Color.PINK); } else { g2d.setColor(Color.CYAN); } place += 50; rect = new Rectangle(place, 100, 300, 200); g2d.draw(rect); g2d.fill(rect); g2d.dispose(); try { Thread.sleep(400); } catch (Exception e) { } repaint(); } } </code></pre> <p>and</p> <pre><code>public class frame { public static JFrame frame; public static void main(String args[]){ frame = new JFrame(); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //frame.setResizable(false); frame.setVisible(true); frame.setLocationRelativeTo(null); main m = new main(); m.setBackground(Color.BLACK); frame.add(m); } } </code></pre> <p>I still can't get it to work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload