Note that there are some explanatory texts on larger screens.

plurals
  1. POKeep paint within JPanel border
    primarykey
    data
    text
    <p>So here is the problem: My program so far works okay, but this snippet of code does not work as intended:</p> <pre><code>pane2 = (new JPanel(){ private static final long serialVersionUID = 1L; @Override public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; Ellipse2D.Double circle = new Ellipse2D.Double(randomX, randomY, randomW, randomH); g2d.fill(circle); } }); pane2.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10,10,10,10), new LineBorder(Color.BLACK))); </code></pre> <p>So what the program is supposed to do is basically repaint the contents of the panel, basically randomizing where the Ellipse is painted each time with each press of the Paint button. It works, but it does not keep the ellipses within the borders of the panel. Is it possible to make that work without adding some sort extra layer like a Container or something and adding padding to the container, or is that the only way (is it even viable to do that)?</p> <p>The button code:</p> <pre><code>bpaint.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { randomX = Math.random() * pane2.getHeight(); randomY = Math.random() * pane2.getWidth(); randomW = Math.random() * 100; randomH = Math.random() * 100; pane2.validate(); pane2.repaint(); } }); </code></pre> <p>I apologize if there is a duplicate of this question somewhere. If there was, it certainly wasn't worded in a way where I would have known it was a duplicate.</p> <p>I <em>did</em> also try to add a global padding variable, but since the EmptyBorder(units) are not based on the same size that Ellipse2D(units) use, adding a global padding variable is a shifty solution at best, and I can only approximate what the ratio may be. I think (or at least hope) that there is a much simpler way I can keep them within the border -- <strong><em>accurately</em></strong>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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