Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you want to do is <strong>drawing some random circles</strong> on the <code>drawPanel</code> when <strong>button clicked</strong>. I write you a <strong>simplified version</strong> to show how things work.</p> <p><img src="https://i.stack.imgur.com/qi2F6.jpg" alt="sample"></p> <p>I only keep the <code>drawButton</code> and <code>paintPanel</code> to keep things simple.</p> <pre><code>public class PaintFrame extends JFrame { private JPanel content = new JPanel(); private JButton drawButton = new JButton("Draw"); private PaintPanel paintPanel = new PaintPanel(); public PaintFrame() { getContentPane().add(content); content.setLayout(new BorderLayout()); drawButton.setSize(100, 500); drawButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // drawButton is fired, repaint the paintPanel paintPanel.repaint(); } }); content.add(drawButton, BorderLayout.WEST); content.add(paintPanel, BorderLayout.CENTER); } } </code></pre> <p>You need a new class extending the JPanel and override the <code>paintComponent</code> method to do the paint job for you. This <strong>makes sure you are drawing on the panel</strong>. </p> <pre><code>class PaintPanel extends JPanel { public PaintPanel() { setSize(500, 500); setBackground(Color.BLACK); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Random random = new Random(); g.setColor(Color.WHITE); // draw 5 random circles int count = 5; for (int i = 0; i &lt; count; i++) { g.drawOval(random.nextInt(250), random.nextInt(250), random.nextInt(250), random.nextInt(250)); } } } </code></pre> <p>Main class</p> <pre><code>public class DrawMain { public static void main(String[] args) { JFrame frame = new PaintFrame(); frame.setDefaultCloseOperation(PaintFrame.EXIT_ON_CLOSE); frame.setSize(600, 500); frame.setVisible(true); } } </code></pre>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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