Search code examples
javaarraysstringgraphicsapplet

How to draw a string array into a Java Applet?


I'm amateur when it comes to java, I am trying to create an applet that randomizes the sequence "Black Screen British Guy" into a different sequence. e.x. "Screen Black Guy British"

I have got the sequence to print to console, However I am trying to print the strings into a java applet, I'm having trouble with this, and I could use some help. Thanks.

 package bsbg_gen;
import java.lang.String;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.applet.*;
import java.awt.Graphics;

public class main extends Applet {

        public void init(){
             String[] bsbg;
             String[] bsbg2;
             String[] bsbg3;
             String[] bsbg4;

             String [][] name = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};
             String [][] name2 = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};
             String [][] name3 = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};
             String [][] name4 = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};

             Random rand = new Random();

             bsbg = name [rand.nextInt(name.length)];
             bsbg2 = name2 [rand.nextInt(name2.length)];
             bsbg3 = name3 [rand.nextInt(name3.length)];
             bsbg4 = name4 [rand.nextInt(name4.length)];


             System.out.print(Arrays.toString(bsbg));
             System.out.print(Arrays.toString(bsbg2));
             System.out.print(Arrays.toString(bsbg3));
             System.out.print(Arrays.toString(bsbg4));
        }

        public void stop(){
        }

        public void paint(Graphics g){

            g.drawString((Arrays.toString(bsbg)), 150, 50);

            g.drawString((Arrays.toString(bsbg2)), 150, 50);

            g.drawString((Arrays.toString(bsbg3)), 175, 50);

            g.drawString((Arrays.toString(bsbg4)), 200, 50);
        }

}

Solution

  • You need to declare these as class members. They're currently not within the scope of the paint method. They're localized in the init method. Take them out.

    String[] bsbg;
    String[] bsbg2;
    String[] bsbg3;
    String[] bsbg4;
    

    Declare them outside

    String[] bsbg;
    String[] bsbg2;
    String[] bsbg3;
    String[] bsbg4;
    
    public void init(){