Setting Variables to be Recognized by Other Methods
this is my first post, and I am very new to programming (teaching myself).
Please forgive me if my terminology is not exactly up to par or I make any
other faux pas. I am trying to write a program that uses two classes in
order to take a user input and use that input to draw a simple rectangle
on the screen. I have gotten everything to work, but I cannot get the user
generated content to be recognized. I have defined an 'x' variable, and
the user inputs a value for that, but that value gets passed through as
'0' every time. The user is prompted to put in an integer value that will
be used as the 'x' value when creating a fillrectangle. When run, though,
the x value is always '0'. Somehow the variable 'x' is not getting changed
to the user inputted value.
Below is my code, as poor as it might be. Hopefully someone can give me a
couple ideas.
MAIN CLASS
import javax.swing.JFrame;
import java.awt.*;
import java.util.*;
public class first {
public static void main(String[] args) {
second p = new second();
p.setValues();
p.getX();
JFrame j = new JFrame("New Rectangle");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
second t = new second();
j.add(t);
j.setSize(500,500);
j.setVisible(true);
}
}
SECOND CLASS
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class second extends JPanel{
int x;
public void setValues()
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the X value");
x = s.nextInt();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
System.out.println(x);
g.setColor(Color.BLUE);
g.fillRect(x, 20, 50, 50);
}
}
No comments:
Post a Comment