Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing Argument from JPanel into JFrame
    primarykey
    data
    text
    <p>I had a problem which I didn't figure out how to solve it. I'm reading now (JAVA how to program 9th edition). My application (Chapter 9, page 390) needs to create a random number of different shapes with different colors, then layout (JFrame) contains a JPanel - which has shapes - and a JLabel - which has numbers of these different shapes. I created the random shapes with random colors, but the number of shapes cannot be passed correctly to main method. It always show me 0.</p> <blockquote> <p>RandomShapes.java</p> </blockquote> <pre><code>import java.awt.Color; import java.awt.Graphics; import java.util.Random; import javax.swing.JPanel; public class RandomShapes extends JPanel{ public int counter; private Random random = new Random(); @Override public void paintComponent(Graphics g){ super.paintComponent(g); drawLines(g); } public void drawLines(Graphics g){ for(int i = 0 ; i &lt; random.nextInt(20) ; i++){ g.setColor(generateColor()); g.drawLine(random.nextInt(getWidth()), random.nextInt(getHeight()), random.nextInt(getWidth()), random.nextInt(getHeight())); counter++; } } private Color generateColor(){ Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); return color; } @Override public String toString(){ return String.format("%d",counter); } } </code></pre> <blockquote> <p>RandomShapesTest.java</p> </blockquote> <pre><code>import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JLabel; public class RandomShapesTest{ public static void main(String[] args){ RandomShapes shapes = new RandomShapes(); JFrame application = new JFrame(); JLabel status = new JLabel(shapes.toString()); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.add(shapes); application.setSize(600,600); application.add(status, BorderLayout.NORTH); application.setVisible(true); } } </code></pre> <p>By the way, a little trick may be more helpful than full answer :)</p> <p>Regards,,,</p>
    singulars
    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