Cannot get mouse position in Java - java

Paint class:
public class Paint extends JPanel implements ActionListener {
Image swimmingpool;
Mouse swim = new Mouse();
Timer tm = new Timer(7, this);
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println(swim.getdistance()); //prints out 0 ?!?
ImageIcon swimminghold = new ImageIcon(render.class.getResource("resources/Swimmingpoolns.png"));
swimmingpool = swimminghold.getImage();
g.drawImage(swimmingpool, 0,-40,null);
if (swim.getdistance() >= 3) {
System.out.println("test works");
}
}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
Mouse class
public class Mouse implements MouseMotionListener {
private int x1 = 200;
private int y1 = 165;
double distance;
public void mouseMoved(MouseEvent e) {
double distance1 = Math.pow((e.getX() - x1), 2);
double distance2 = Math.pow((e.getY() - y1), 2);
setdistance(Math.sqrt(distance1 + distance2));
// The below prints, and has been
// tested to print the correct distance
System.out.println(getdistance());
}
public void setdistance(double distance) {
this.distance = distance;
}
public double getdistance() {
return distance;
}
}
When I execute System.out.println(getdistance()) in the Mouse class it prints the correct distance whereas if I execute System.out.println(swim.getdistance()); in the paint class prints 0.
Everything I've tried to do still results in distance = 0, in the class public void paintComponent(Graphics g).
What am I not understanding?

As pointed out by #Hunter-mcmillen: you are confused about java operators.
public void mouseMoved(MouseEvent e) {
double distance1 = Math.pow((e.getX() - x1),2);
double distance2 = Math.pow((e.getY() - y1),2); // Math.pow(a,b) == a^b (in a calculator)
setdistance(Math.sqrt(distance1 + distance2));
System.out.println(getdistance());
}
I really recommend that you read more carefully the Java operators before assuming how they work on the language.
EDIT 2:
I recommend also that you create a JPanel or JLabel for this picture, and then load such picture inside this new Jpanel or Label or other component.
public class Paint extends JPanel implements ActionListener {
Mouse swim = new Mouse();
Timer tm = new Timer(7, this);
public void paintComponent(Graphics g) {
// Try this:
ImageIcon swimminghold = new ImageIcon(render.class.getResource("resources/Swimmingpoolns.png"));
swimmingpool = swimminghold.getImage();
JLabel label = new JLabel();
label.setIcon(swimminghold);
label.addMouseMotionListener(swim);
addMouseMotionListener(swim);
label.addMouseMotionListener(swim);
addMouseMotionListener(swim);
//Do something
/* ...*/
}

Related

Globally Modify a global variable within a method Java

I am making Conways Game of Life. In the mouse listener I want the cell to appear/disappear on the screen when I click once. I use a 40x40 boolean array (gameState) of 20x20 pixel cells. I want to paint the squares in my paint method using the co-ordinates of my mouse which i get in its clicked method. However, I am getting a null-pointer exception at line 71 and do not know what to do to solve it.
Main
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
public class mainApplication extends JFrame implements Runnable, MouseListener {
private static final Dimension windowsize = new Dimension(80, 600);
private BufferStrategy strategy;
private Graphics offscreenGraphics;
private static boolean isGraphicsInitialised = false;
private static int rows = 40;
private static int columns = 40;
private static int height = windowsize.height;
private static int width = windowsize.width;
private static Cells cells;
private int xArrayElement,yArrayElement, xPosition, yPosition;
private static boolean gameState[][] = new boolean[rows][columns];
public mainApplication() {
System.out.println(System.getProperty("user.dir"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width / 2 - windowsize.width / 2;
int y = screensize.height / 2 - windowsize.height / 2;
setBounds(x, y, screensize.width, screensize.height);
setVisible(true);
createBufferStrategy(2);
strategy = getBufferStrategy();
offscreenGraphics = strategy.getDrawGraphics();
isGraphicsInitialised = true;
// MouseEvent mouseEvent = new MouseEvent();
addMouseListener(this);
// addMouseMotionListener(MouseEvent);
Thread t = new Thread(this);
t.start();
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 1){
xPosition = e.getX();
yPosition = e.getY();
cells.setPosition(xPosition,yPosition);
xArrayElement = (xPosition/20);
yArrayElement = (yPosition/20);
if(gameState[xArrayElement][yArrayElement]){
gameState[xArrayElement][yArrayElement] = false;
}
else if (!gameState[xArrayElement][yArrayElement]) {
gameState[xArrayElement][yArrayElement] = true;
}
}
}
#Override
public void run() {
while (true) {
try { //threads entry point
Thread.sleep(20); //forces us to catch exception
}
catch (InterruptedException e) {
}
}
}
public void paint(Graphics g) {
if (isGraphicsInitialised) {
g = strategy.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 800);
if (gameState[xArrayElement][yArrayElement]) {
g.setColor(Color.WHITE);
cells.paint(g);
}
else if (!gameState[xArrayElement][yArrayElement]) {
g.setColor(Color.BLACK);
g.fillRect(xPosition, yPosition, 20, 20);
}
strategy.show();
}
}
public static void main(String[]args){
mainApplication test = new mainApplication();
}
}
Cells class
import java.awt.*;
public class Cells {
int x;
int y;
public Cells(){
}
public void setPosition(int xi, int xj){
x = xi;
y = xi;
System.out.println(xi);
System.out.println("sjdkgffdjv" + y);
}
public boolean cellState(boolean visible){
return visible;
}
public void paint(Graphics g){
g.drawRect(x, y, 20,20);
}
}
It's because you haven't initialized your cells variable in Main class..
So try this
private static Cells cells = new Cells();
As #nullPointer has pointed out (sorry, dad joke) you're getting a NPE because you haven't initialized the class member Cells. There are also a few other points to make that might unrelated to the question.
Don't create that thread
Swing already uses a thread to handle UI events and drawing so creating another thread is dangerous.
Make Cells immutable
Cells should be immutable. At no point should you need to set the position of a cell. If you need to change where a Cell is at, just dispose of the object and create a new one at that position.

Java JFrame Bouncing Ball Physics Simulation- Ball Motion Conflicts Upon Creation of Creation

So, right now, I'm able to create multiple balls and update them all properly through a Vector of objects and a for loop to update each object independently. The problem is that for every ball after the first, the ball that is created seems to affect the momentum and position of the other balls, causing all the balls to abruptly change their flight paths.
Code for creating frame and managing ball creation based on mouselistener:
public class FrameCreation extends JFrame{
static Vector<BallCreate> ballObjects = new Vector<BallCreate>();
static Timer timer;
Point m1;
Point m2;
static JFrame frame1;
static mouseHandler mouse;
public static void main(String args[]){
FrameCreation frame = new FrameCreation();
frame1 = new JFrame("Phyiscs Test");
frame1.setVisible(true);
frame1.setSize(520,530);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
mouse = frame.new mouseHandler();
frame1.addMouseListener(mouse);
}
public class mouseHandler extends JPanel implements MouseListener{
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
m1 = e.getPoint();
System.out.println("Mouse pressed");
}
#Override
public void mouseReleased(MouseEvent e) {
m2 = e.getPoint();
Thread queryThread = new Thread(){
double vX = m2.getX() - m1.getX();
double vY = m2.getY() - m1.getY();
public void run(){
createBall(m1.getX(),m1.getY(),vX,vY);
}
};
queryThread.start();
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
public void createBall(double posX, double posY, double vX, double vY){
BallCreate newBall = new BallCreate(posX,posY,50,vX,vY);
ballObjects.add(newBall);
frame1.add(newBall);
frame1.revalidate();
newBall.repaint();
}
}
Code for drawing and updating balls:
public class BallCreate extends JPanel {
Timer timer;
int diam;
Color color;
double vX, vY, posX, posY;
final double G = 30;
public BallCreate(double posX, double posY, int diam, double vX, double vY){
this.posX = posX;
this.posY = posY;
this.vX = vX;
this.vY = vY;
this.diam = diam;
color = getRandomColor();
timer = new Timer(100, new MovementUpdate());
timer.start();
}
public void drawing(){
repaint();
}
public void motionUpdate(){
for(BallCreate ball : FrameCreation.ballObjects){
double t = 0.1;
double dX = ball.vX*t;
double dY = (ball.vY + G*t)*t;
double v2Y = G*t + ball.vY;
System.out.println("Ball v2y: " + ball.vY);
ball.posX = ball.posX + dX;
ball.posY = ball.posY + dY;
vY = v2Y;
drawing();
wallCollisionCheck();
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for(BallCreate ball : FrameCreation.ballObjects){
g.setColor(ball.color);
//System.out.println("pos X: " + posX);
//System.out.println("pos Y: " + posY);
g.fillOval((int)ball.posX, (int)ball.posY,
ball.diam ,ball.diam);
}
}
public void wallCollisionCheck(){
for(BallCreate ball : FrameCreation.ballObjects){
double botBound = 500-(ball.posY + ball.diam);
if((botBound <=0 && vY>=0)|| (ball.posY <=0 && ball.vY <=0 )){
//System.out.println("Collision Noted");
//System.out.println("Prev vY: " + ball.vY);
ball.vY = ball.vY * -0.65;
//System.out.println("Post vY: " + ball.vY);
ball.posY = 460;
}
if((ball.posX <= 0 && ball.vX <= 0) || ((Math.abs(500 - ball.posX) <= 40)&& ball.vX >=0)){
ball.vX = ball.vX * -0.65;
}
drawing();
}
}
public Color getRandomColor(){
int R = (int)(255*Math.random());
int G = (int)(255*Math.random());
int B = (int)(255*Math.random());
Color c = new Color(R, G , B);
return c;
}
public class MovementUpdate implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
for(BallCreate ball : FrameCreation.ballObjects){
ball.motionUpdate();
}
}
}
}
I realize that the problem is slightly vague, but it's simply hard to describe without being able to show an image of what is happening. Any help is appreciated, and clarification of code can be done if necessary. Thanks.

Java Non-Static Variable Referenced from Static Context Error

I'd like to state that this question is very possibly a duplicate, but I'm not sure exactly what the issue is: I'm unable to do a proper search because of this.
I'm currently working on a painting program in Java. I'm trying to store the instructions for drawing the shapes in an ArrayList of Shape objects. I'm also using a MouseListener to get the coordinates.
The goal is that when the mouse is pressed, it keeps a record of that point. When it is released, it keeps record of that second point, then sends the two coordinates to the constructor, in the line history.add(new Shape(x, y, x2, y2)).
The relevant code is the following:
// Create an ArrayList for the History
static ArrayList history = new ArrayList(0);
.
.
.
// Co-ordinates for rectangle painting
static int x = 0;
static int y = 0;
static int x2 = 0;
static int y2 = 0;
.
.
.
/**
* A class for handling mouse input
*
* All methods within the MouseHandler class MUST be there
* If not, the code will not compile.
*/
private static class MouseHandler implements MouseListener
{
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
//repaint() is a special method that must be called to "repaint"
//your shapes on the screen.
canvas.repaint();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
// Create a new shape on the button unclick
history.add(new Shape(x, y, x2, y2));
}
}
This code throws an exception at the line history.add(new Shape(x, y, x2, y2)); : "Non-static method this cannot be referenced from a static context." The error seems to specifically reference (new Shape(x, y, x2, y2)). I don't understand why this method would be non-static.
Any help is greatly appreciated in advance,
Placowdepuss
Edit: Here is my full code:
//Import packages needed
// For the GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// For the ArrayList
import java.util.*;
/**
* A simple drawing application.
*
* #author (Massimo A. Lipari)
* #version (1.0.0)
*/
public class PaintProgram
{
// Create the frame and the panels for the GUI
static JFrame frame = new JFrame("PaintIt");
static JPanel panel = new JPanel();
static JPanel buttonPanel = new JPanel();
static MyPanel canvas = new MyPanel();
static JLabel sampleText = new JLabel("Label");
// Create an array for the buttons
static JButton[] buttonArray = new JButton[12];
// Create an ArrayList for the History
static ArrayList<Shape> history = new ArrayList<Shape>();
// Co-ordinates for rectangle painting
static int x, y, x2, y2;
// Create a variable for keeping track of the active tool
static String activeTool;
// Variables for holding the current colour and fill settings
static boolean currentFill;
static Color currentColour;
public static void main(String[] args)
{
// Set the frame size
frame.setSize(1920,1040);
// Create the mouse listeners
canvas.addMouseListener(new MouseHandler());
// Set the size for the canvas portion of the screen
canvas.setSize(1920, 880);
// Add panels to frame
// Set layout for panel
panel.setLayout(new BorderLayout());
createButtonPanel();
panel.add(buttonPanel, BorderLayout.NORTH);
panel.add(canvas, BorderLayout.CENTER);
frame.getContentPane().add(panel);
// Set frame to visible and allows it to exit on closing of the frame
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void createButtonPanel()
{
// Set the buttonPanel size, and creates a grid layout for it
buttonPanel.setSize(1920, 160);
buttonPanel.setLayout(new GridLayout(1, 12));
// Initialize the buttons
for (int i = 0; i < buttonArray.length; i++) {
buttonArray[i] = new JButton("Button " + (i + 1));
// Create and add a button handler
buttonArray[i].addActionListener(new ButtonHandler());
buttonArray[i].setIcon(new ImageIcon("icon" + i + ".png"));
buttonArray[i].setBackground(Color.WHITE);
buttonPanel.add(buttonArray[i]);
}
}
/**
* A class for handling button input (the tools)
*/
private static class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == buttonArray[0]) {
buttonArray[0].setBackground(JColorChooser.showDialog(null, "Choose a Color", sampleText.getForeground()));
} else if (e.getSource() == buttonArray[1]) {
currentFill = true;
buttonArray[1].setBackground(Color.LIGHT_GRAY);
buttonArray[2].setBackground(null);
} else if (e.getSource() == buttonArray[2]) {
currentFill = false;
buttonArray[1].setBackground(null);
buttonArray[2].setBackground(Color.LIGHT_GRAY);
} else if (e.getSource() == buttonArray[3]) {
activeTool = "paint";
} else if (e.getSource() == buttonArray[4]) {
activeTool = "rectangle";
} else if (e.getSource() == buttonArray[5]) {
activeTool = "triangle";
} else if (e.getSource() == buttonArray[6]) {
activeTool = "circle";
} else if (e.getSource() == buttonArray[7]) {
activeTool = "line";
} else if (e.getSource() == buttonArray[8]) {
activeTool = "text";
} else if (e.getSource() == buttonArray[9]) {
} else if (e.getSource() == buttonArray[10]) {
} else if (e.getSource() == buttonArray[11]) {
}
}
}
/**
* A class for handling mouse input
*
* All methods within the MouseHandler class MUST be there
* If not, the code will not compile.
*/
private static class MouseHandler implements MouseListener
{
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
//repaint() is a special method that must be called to "repaint"
//your shapes on the screen.
canvas.repaint();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
// Create a new shape on the button unclick
history.add(new Shape(x, y, x2, y2));
}
}
/**
* A class for painting the shapes
*/
private static class MyPanel extends JPanel
{
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
setBackground(Color.white);
}
public Dimension getPreferredSize() {
return new Dimension(600,600);
}
// ALL drawing of shapes must be done in the paintComponent method
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Drawing a basic rectangle from top left corner to bottom right on canvas
if (x2 >= x && y2 >= y)
g.drawRect(x, y, x2 - x, y2 - y);
else if (x2 >= x && y2 <= y)
g.drawRect(x, y2, x2 - x, y - y2);
else if (x2 <= x && y2 >= y)
g.drawRect(x2, y, x - x2, y2 - y);
else if (x2 <= x && y2 <= y)
g.drawRect(x2, y2, x - x2, y - y2);
}
}
/**
* A class that creates a colour picker
*
* This code is the property of Oracle Systems Inc. It is copyrighted.
*/
static class ColorChooser_01 extends JFrame
{
public static void main(String[] args) {
new ColorChooser_01();
}
public ColorChooser_01() {
this.setSize(300, 100);
JPanel panel1 = new JPanel();
sampleText.setBackground(null);
panel1.add(sampleText);
this.add(panel1);
this.setVisible(true);
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(null, "Choose a Color", sampleText.getForeground());
if (c != null){
sampleText.setForeground(c);
buttonArray[0].setBackground(c);
}
else{
sampleText.setForeground(Color.WHITE);
}
}
}
}
/**
* A class for creating objects of type Shape
*/
public class Shape
{
// Variable for storing the type of shape
String type;
// Initialize variables for storing points for shape creation
int xcoord;
int ycoord;
int xcoord2;
int ycoord2;
// Boolean variable to control whether the shape is filled or not -- defaults to false
boolean fill = false;
// Variable to hold the coulour
Color colour;
public Shape(int newX, int newY, int newX2, int newY2)
{
type = activeTool;
xcoord = newX;
ycoord = newY;
xcoord2 = newX2;
ycoord2 = newY2;
fill = currentFill;
colour = currentColour;
}
public String getType()
{
return type;
}
public int getX()
{
return xcoord;
}
public int getY()
{
return ycoord;
}
public int getX2()
{
return xcoord2;
}
public int getY2()
{
return ycoord2;
}
public boolean getFill()
{
return fill;
}
public Color getColour()
{
return colour;
}
}
}
You need to move the shape class to another file because you cannot have two public classes in the same file

Stop pause on key hold with KeyBindings Java

I'm trying to write a Pong applet in Java. When the user holds down either up or down, their paddle should move smoothly, but this isn't the case. It moves, then pauses, then starts moving again. Is there a way to stop this short pause from happening?
Main Class:
public class Main extends JApplet {
public DrawPanel dp = new DrawPanel(400, 400);
public void init(){
add(dp);
setSize(400, 400);
requestFocusInWindow();
Action moveDown = new AbstractAction(){
public void actionPerformed(ActionEvent e){
dp.player.y += 10;
dp.repaint();
}
};
dp.getInputMap().put(KeyStroke.getKeyStroke("pressed DOWN"), "move down");
dp.getActionMap().put("move down", moveDown);
}
}
DrawPanel Class:
public class DrawPanel extends JPanel {
public Paddle player;
public Paddle opponent;
public DrawPanel(int height, int width){
int y = (height / 2) - (height / 10);
int w = 15;
int h = height / 5;
player = new Paddle(2, y, 15, h, Color.white);
opponent = new Paddle(width - (w+2), y, 15, h, Color.white);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(player.color);
g.fillRect(player.x, player.y, player.width, player.height);
g.setColor(opponent.color);
g.fillRect(opponent.x, opponent.y, opponent.width, opponent.height);
}
}
Paddle Class:
public class Paddle {
public int x, y, width, height;
public Color color;
public Paddle(int _x_, int _y_, int w, int h, Color c){
x = _x_;
y = _y_;
width = w;
height = h;
color = c;
}
}
The underlying issue is an impedance mismatch between the "instance" notion of a keyPressed and the "duration" notion of the movement.
Instead of trying to smooth that over in the view (which shouldn't have anything to do with the details of the game logic anyway), enhance the game model with api that's a better fit. F.i. add start/stop logic and bind those methods to keyPressed/keyReleased:
public class Paddle {
public void startMoveDown() {
// here goes the logic, f.i. starting a timer
// in the actionPerformed of that timer:
... moveUnitDown();
}
public void stopMoveDown() {
//...
}
protected void moveUnitDown() {
y+=unit;
// ideally, have listeners and notify them the change of y
}
}
// in the view:
Action startMoveDown = new AbstractAction(){
public void actionPerformed(ActionEvent e){
player.startMoveDown();
}
};
dp.getInputMap().put(KeyStroke.getKeyStroke("pressed DOWN"), "start move down");
dp.getActionMap().put("start move down", startMoveDown);
// in the view:
Action stopMoveDown = new AbstractAction(){
public void actionPerformed(ActionEvent e){
player.stopMoveDown();
}
};
dp.getInputMap().put(KeyStroke.getKeyStroke("released DOWN"), "stop move down");
dp.getActionMap().put("stop move down", stopMoveDown);

animation using repaint()

I am trying to create a simple animation which draws random rectangles when a button is pressed. So far I managed to create rectangle on the press of a button. I want to further develop the code so that when I press the button, more than multiple random rectangles are created. I tried to create a for loop which asks the inner class to repaint itself but it still didn't work. can anyone help me please.
public class TwoButtonsRandomRec {
JFrame frame;
private int width = 500;
private int height = 500;
private DrawPanel dp;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public static void main (String[] args)
{
TwoButtonsRandomRec test = new TwoButtonsRandomRec();
test.go();
}
public void go()
{
dp = new DrawPanel();
JButton start = new JButton("Start");
start.addActionListener(new startListener());
JButton stop = new JButton("Stop");
stop.addActionListener(new stopListener());
frame = new JFrame();
frame.setSize(getWidth(), getHeight());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.NORTH, start);
frame.getContentPane().add(BorderLayout.SOUTH, stop);
}
class startListener implements ActionListener{
public void actionPerformed(ActionEvent event){
frame.getContentPane().add(BorderLayout.CENTER, dp);
frame.repaint();
frame.getRootPane().revalidate();
for(int i=0; i<10; i++){
dp.repaint();
}
}
}
class stopListener implements ActionListener{
public void actionPerformed(ActionEvent event){
System.out.println("stop");
}
}
class DrawPanel extends JPanel{
public void paintComponent(Graphics g){
int w = 5+(int)(Math.random() * width-5);
int h = 5+(int)(Math.random() * height-5);
int maxX = width-w; // diffX & diffY are used to ensure that rectangle is
int maxY = width-h; // draw completely inside the window
int x = (int)(Math.random() * maxX);
int y = (int)(Math.random() * maxY);
Color color = new Color((int) (Math.random()*256), // random red
(int) (Math.random()*256), // random green
(int) (Math.random()*256));// random blue
g.setColor(color);
g.fillRect(x,y,w,h);
}
}
}
repaint() simply tells Swing "when you'll have time, please repaint this area". So if you add rectangles in a loop and call repaint at each iteration, all the rectangles will only appear after the loop has finished, and the action event has been handled.
To have an animation, you need to loop in a separate thread. The easiest way to do that is to use a Swing Timer. When the Start button is started, start a timer which adds a random rectangle and calls repaint() every X milliseconds. When the Stop button is pressed, stop the timer.
What you should do is to put the loop inside paintComponent method and not call repaint in the loop.
So your paintComponent method should look like this:
public void paintComponent(Graphics g){
for (int i = 0; i < 10; i++) {
int w = 5+(int)(Math.random() * width-5);
int h = 5+(int)(Math.random() * height-5);
int maxX = width-w; // diffX & diffY are used to ensure that rectangle is
int maxY = width-h; // draw completely inside the window
int x = (int)(Math.random() * maxX);
int y = (int)(Math.random() * maxY);
Color color = new Color((int) (Math.random()*256), // random red
(int) (Math.random()*256), // random green
(int) (Math.random()*256));// random blue
g.setColor(color);
g.fillRect(x,y,w,h);
}
}
And your action performed should look like this:
public void actionPerformed(ActionEvent event){
frame.getContentPane().add(BorderLayout.CENTER, dp);
frame.repaint();
frame.getRootPane().revalidate();
dp.repaint();
}
Well,here I have done a short EG for you.It displays random rectangles, random times on random screen location.
(You can set your own value of randomization, and the screen location max bound,as per your requirements.)
And also note
int i=(int)(Math.random()*10);
int j=(int)(Math.random()*10);
for(;i<j;i++)
Where at times i may be > than j.So,loop may not work on one or two cliks.Change as per your need.
Here is the working code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleStamper extends JApplet {
public void init() {
Display display = new Display();
setContentPane(display);
}
class Display extends JPanel implements MouseListener {
Display() {
setBackground(Color.black);
addMouseListener(this);
}
public void mousePressed(MouseEvent evt) {
if ( evt.isShiftDown() ) {
repaint();
return;
}
int x = evt.getX();
int y = evt.getY();
Graphics g = getGraphics();
//***MODIFY THE FOLLOWING LINES****//
int i=(int)(Math.random()*10);
int j=(int)(Math.random()*10);
for(;i<j;i++)
{ g.setColor(Color.red);
x=(int)(Math.random()*100);
y=(int)(Math.random()*100);
g.fillRect( x , y , 60, 30 );
g.setColor(Color.black);
g.drawRect(x , y , 60, 30 );}
g.dispose();
}
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }
}
}

Categories