I'm a coding newb and want to learn some more java. I'm currently taking an introductory programming course in high school and am just trying to play around outside of class. This program I'm creating is supposed to print out a few instructions and questions in the console, to which I want to retrieve user input using a scanner and variable. The goal of the program is for the user to be able to create a 'drawing' based on pure instinct, then this drawing is displayed after the fact.
Here's my problem. I'm asking the user and storing the information in variables that are native to the main method, but I need to use this information in the paintComponent method.
I tried adding static in front of the variable such as:
static int emptyRectW1 = kboard.nextInt();
import java.util.Scanner;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BlindDrawing extends JPanel {
public static void main (String[] args) {
Scanner kboard = new Scanner(System.in);
System.out.println("Welcome to the Blind Drawing Game!");
System.out.println("In this game, you will be asked questions about how to construct an image using rectangles and ovals. You will be asked the shape's dimensions and position. The origin (0,0) is the top left corner.");
System.out.println("First you're making an empty rectangle, how wide do you want it to be?");
int emptyRectW1 = kboard.nextInt();
System.out.println("What about the height?");
int emptyRectH1 = kboard.nextInt();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0,0,emptyRectW1, emptyRectH1);
}
}
Actually, a variable declared inside a method is a local variable.
Please extend the scope of the the two variables just before your main method. See code below.
static int emptyRectW1, emptyRectH1;
public static void main (String[] args) {
Then manipulate the latter code to avoid duplicate variable declaration as shown below.
emptyRectW1 = kboard.nextInt();
System.out.println("What about the height?");
emptyRectH1 = kboard.nextInt();
I hope this helps.