Hi im making a Gui programme using a null layout and a setBounds() method for lay out . In the programme I want 25 strings printed out on the screen in random locations . I know that i could do this with a for loop however i have been trying this to no avail.
public void paint(Graphics g){ super.paint(g); for(i=0;i<25;i++){ g.drawString("string name",Math.random()*250,Math.random()*250); g.setColor(Color.RED); } }
I have been trying this and it has not been working so my question is is there some better way to do this or am i making some sort of obvious mistake.
Advertisement
Answer
You are not using the Math.random() part correctly try this instead:
import java.awt.Color; import java.awt.Container; import java.awt.EventQueue; import java.awt.Graphics; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; /** * * @author David */ public class JavaApplication142 extends JFrame { private int width = 300, height = 300; public JavaApplication142() { createAndShowUI(); } /** * @param args the command line arguments */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JavaApplication142 jApp = new JavaApplication142(); } }); } private void createAndShowUI() { setTitle("Painting"); setSize(width, height); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); addComponentsToContentPane(getContentPane()); setVisible(true); } private void addComponentsToContentPane(Container contentPane) { Panel panel1 = new Panel(); contentPane.add(panel1); } class Panel extends JPanel { private Random rand; public Panel() { rand = new Random(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < 25; i++) { g.drawString("string name", (int) rand.nextInt(width), (int) rand.nextInt(height)); g.setColor(Color.RED); } } } }
This will help to get all the strings drawn within the region of the panel, although strings with varying length might go offscreen, just add some extra code to check the length of the string and set its co-ords appropriately