Java Non-Static Variable Referenced from Static Context Error - java

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

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.

Change ball color when colliding

I'm making an java app (for exercise) where there must be a panel and 2 buttons.
Each time you press the start button a ball must be displayed and it moves based on thread. The user can display all the way up to 10 independent balls.
By pressing the stop button, 1 ball must be removed with each time the stop button is pressed (example, when there is 4 balls, the user must press 4 times stop button to remove all the balls independently)
All the x- and y coordinates of the balls must be stored in a Matrix
When 1 or more ball(s) are colliding with each other, only the colliding balls must change color from red to blue
Ok I'm almost done with it completely ( from point 1 to 4 ), but here comes my problem. When a ball is colliding with another, instead of changing the colors of the colliding balls to blue, my code is changing all the balls color from red to blue. I know that my error lies at the new Balls().setColor(Color.Blue), but I have no idea how to change only the colliding balls.
Below follows a screen shot of the java app and the code.
Can anyone help me with this headache?
Printscreen:
source code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;`
public class BouncingBalls extends JPanel implements ActionListener {
protected List<Ball> balls = new ArrayList<Ball>(10);
private final Container container;
private final DrawCanvas canvas;
private int canvasWidth;
private int canvasHeight;
public JButton start, stop;
int [][] coords= new int[11][2];
int ammountOfBalls = 0;
static Color clr= Color.RED;
public static int random(int maxRange) {
return (int) Math.round((Math.random() * maxRange));
}
public BouncingBalls(int width, int height) {
setLayout(new FlowLayout());
start= new JButton("start");
start.addActionListener(this);
stop= new JButton("stop");
stop.addActionListener(this);
add(start);
add(stop);
add(new JLabel(""));
container = new Container();
canvasWidth = width;
canvasHeight = height;
canvas = new DrawCanvas();
this.setLayout(new FlowLayout());
this.add(canvas);
start();
}
public void start() {
Thread t = new Thread() {
#Override
public void run() {
while (true) {
update();
getPositions();
collisionDetection();
repaint();
try {
Thread.sleep(30);
} catch (InterruptedException e) {
}
}
}
private void collisionDetection() {
// The algorithm that detects collision
for(int i=0;i<ammountOfBalls;i++){
for(int j=i+1; j<ammountOfBalls; j++){
if(collisionMethod(i,j)){ // my collision method
//HOW DO I CHANGE ONLY THE COLLIDING BALLS COLOR HERE????
new Ball().setColor(Color.BLUE); // this line here changes the color of all the balls on the panel
System.out.println("Its a hit");
}
}
}
}
private void getPositions() {
int row=0;
for (Ball ball : balls) {
int x =ball.getXPosition();
int y =ball.getYPosition();
coords[row][0]=x;
coords[row][1]=y;
row++;
}
}
private boolean collisionMethod(int i, int j) {
float xd = coords[i][0]-coords[j][0];
float yd=coords[i][1]-coords[j][1];
float radius= new Ball().ballRadius;
float sqrRadius= radius * radius;
float distSqr= (xd * xd) + (yd * yd);
if(distSqr <= sqrRadius)
return true;
return false;
}
};
t.start();
}
public void update() {
for (Ball ball : balls) {
ball.move(container);
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == start){
if(ammountOfBalls < 10){
// to limit the ammount of balls to 10
balls.add(new Ball());
ammountOfBalls++;
}
}
else if( e.getSource() == stop){
if(ammountOfBalls > 0){
ammountOfBalls --;
balls.remove(ammountOfBalls);
}
}
}
class DrawCanvas extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
container.draw(g);
for (Ball ball : balls) {
ball.draw(g);
}
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(700, 400));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Bouncing Balls");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(800,500));
f.setContentPane(new BouncingBalls(800,800));
f.pack();
f.setVisible(true);
}
public static class Ball {
public int random(int maxRange) {
return (int) Math.round(Math.random() * maxRange);
}
int x = random(700); // method to get random coords for the x-value
int y = random(400); // method to get random coords for the y-value ...... these are used to get random positions for the balls instead of only static
int xMovement = 10;
int yMovement = 10;
int ballRadius = 20;
int i = 0;
public Color getColor(){
return clr;
}
public Color setColor(Color color){
clr=color;
return clr;
}
public void draw(Graphics g) {
g.setColor(getColor());
g.fillOval(x,y,ballRadius,ballRadius);
}
public int getXPosition(){
return x;
}
public int getYPosition(){
return y;
}
public void move(Container container) {
x += xMovement;
y += yMovement;
if (x - ballRadius < 0) {
xMovement = -xMovement;
x = ballRadius;
}
else if (x + ballRadius > 700) {
xMovement = -xMovement;
x = 700 - ballRadius;
}
if (y - ballRadius < 0) {
yMovement = -yMovement;
y = ballRadius;
}
else if (y + ballRadius > 400) {
yMovement = -yMovement;
y = 400 - ballRadius;
}
}
}
public static class Container {
private static final int hightPanel = 800;
private static final int widthPanel= 800;
public void draw(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, widthPanel, hightPanel);
}
}
}
`
You have defined clr as a static field of your application. When your Ball class calls setColor() you are changing the value of clr to blue... and then any Ball that calls getColor() will see that clr is blue.
Solution: Don't make clr an application-wide static field. Define it in the Ball class as a non-static field, so each Ball has its own color.

How to return Instance Variables for objects in an array

I am new to graphics in java and I am currently working on a game. Essentially, there are rising bubbles, and the user has to pop them by moving the mouse over them.
I have already made the bubbles but now for the collision detection, I need to be able to find the x and coordinates as well as the diameter of the circle. How can I return the instance variables for each bubble (from the Bubbles object array). You can see my code below. If you find coding errors, please let me know.
Game Class:
public class Game extends JPanel{
public static final int WINDOW_WIDTH = 600;
public static final int WINDOW_HEIGHT = 400;
private boolean insideCircle = false;
private static boolean ifPaused = false;
private static JPanel mainPanel;
private static JLabel statusbar;
private static int clicks = 0;
//Creates a Bubbles object Array
Bubbles[] BubblesArray = new Bubbles[5];
public Game() {
//initializes bubble objects
for (int i = 0; i < BubblesArray.length; i++)
BubblesArray[i] = new Bubbles();
}
public void paint(Graphics graphics) {
//makes background white
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
//paints square objects to the screen
for (Bubbles aBubblesArray : BubblesArray) {
aBubblesArray.paint(graphics);
}
}
public void update() {
//calls the Square class update method on the square objects
for (Bubbles aBubblesArray : BubblesArray) aBubblesArray.update();
}
public static void main(String[] args) throws InterruptedException {
statusbar = new JLabel("Default");
Game game = new Game();
game.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
statusbar.setText(String.format("Your mouse is at %d, %d", e.getX(), e.getY()));
}
public void mouseExited(MouseEvent e){
ifPaused = true;
}
public void mouseEntered(MouseEvent e){
ifPaused = false;
}
});
JFrame frame = new JFrame();
frame.add(game);
frame.add(statusbar, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Bubble Burst");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
while (true) {
if (!ifPaused){
game.update();
game.repaint();
Thread.sleep(5);
}
}
}
}
Bubbles Class:
public class Bubbles{
private int circleXLocation;
private int circleSize;
private int circleYLocation = Game.WINDOW_WIDTH + circleSize;
private int fallSpeed = 1;
private int color = (int) (4 * Math.random() + 1);
Random rand = new Random();
private int whereMouseX;
private int whereMouseY;
public int generateRandomXLocation(){
return circleXLocation = (int) (Game.WINDOW_WIDTH * Math.random() - circleSize);
}
public int generateRandomCircleSize(){
return circleSize = (int) (50 * Math.random() + 30);
}
public int generateRandomFallSpeed(){
return fallSpeed = (int) (5 * Math.random() + 1);
}
public void paint(Graphics g){
if (color == 1) g.setColor(new Color(0x87CEEB));
if (color == 2) g.setColor(new Color(0x87CEFF));
if (color == 3) g.setColor(new Color(0x7EC0EE));
if (color == 4) g.setColor(new Color(0x6CA6CD));
g.fillOval (circleXLocation, circleYLocation, circleSize, circleSize);
}
public Bubbles(){
generateRandomXLocation();
generateRandomCircleSize();
generateRandomFallSpeed();
}
public void update(){
if (circleYLocation <= - circleSize){
generateRandomXLocation();
generateRandomFallSpeed();
generateRandomCircleSize();
circleYLocation = Game.WINDOW_HEIGHT + circleSize;
}
if (circleYLocation > - circleSize){
circleYLocation -= fallSpeed;
}
}
public int getX(){
return circleXLocation;
}
public int getY(){
return circleYLocation;
}
public int getCircleSize(){
return circleSize;
}
}
Set your bubbles to include x and y values in it's constructor.
Public Bubble(float x, float y, int circleSize){
// initialize variables here
}
Then check to see if they are colliding with your current mouse location, something like...
if(e.getX() == this.getX() && e.getY() == this.getY()){
// do something
}
Loop through each Bubble in the array and access the public get methods you have created in the Bubble class:
Example:
for (Bubble b : BubblesArray)
{
int x = b.getX();
int y = b.getY();
}

Java - boolean set to false with nothing telling it to do so

My boolean drawFlag is being set to false in my code with nothing visible actually telling it to change value to false. This is preventing the code inside method mouseDragged(mouseEvent) to execute. If someone could point out what's making the flag become false so this would stop happening? Thanks.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DrawAndDrag {
public static void main(String[] args) throws InterruptedException {
GraphicsFrame window = new GraphicsFrame("Draw Rectangle");
window.init();
}
}
class GraphicsFrame extends JFrame {
public GraphicsFrame(String title) {
super(title);
}
public void init() {
Container pane = this.getContentPane();
pane.add(new GraphicsContent().init());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 600);
this.setVisible(true);
}
}
class GraphicsContent extends JPanel {
private int xStart, yStart;
private int width, height;
public JPanel init() {
this.setBackground(Color.WHITE);
this.addMouseListener(new MouseDrag());
this.addMouseMotionListener(new MouseDrag());
return this;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(xStart, yStart, width, height);
}
class MouseDrag implements MouseListener, MouseMotionListener {
private boolean drawFlag;
public void mousePressed(MouseEvent e) {
if(isOutside(e)) {
this.drawFlag = true;
xStart = e.getX();
yStart = e.getY();
width = 0; height = 0;
System.out.println(drawFlag);
}else {
// this.drawFlag = false;
}
}
public void mouseDragged(MouseEvent e) {
System.out.println(drawFlag);
if(drawFlag) {
width = e.getX() - xStart;
height = e.getY() - yStart;
repaint();
}
}
public boolean isOutside(MouseEvent e) {
int xMin = Math.min(xStart, xStart + width); int yMin = Math.min(yStart, yStart + height);
int xMax = Math.max(xStart, xStart + width); int yMax = Math.max(yStart, yStart + height);
if((e.getX() < xMin || e.getX() > xMax)
|| (e.getY() < yMin || e.getY() > yMax)) {
return true;
}else {
return false;
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
}
}
Try to move drawFlag attribute from the inner class MouseDrag to the outer class GraphicsContent as follow
class GraphicsContent extends JPanel {
private int xStart, yStart;
private int width, height;
private volatile boolean drawFlag;
// other code
}
However as you drag, the value is constantly being reported as being false
You've got two listeners. One is a motion listener:
this.addMouseListener(new MouseDrag());
this.addMouseMotionListener(new MouseDrag());
mousePressed will not be called on a motion listener, so it will always be false in the drag event.
I expect what you meant is this:
MouseDrag listener = new MouseDrag();
this.addMouseListener(listener);
this.addMouseMotionListener(listener);
Are you sure you need two MouseDrag elements? I.e. using something like
public JPanel init() {
this.setBackground(Color.WHITE);
MouseDrag md = new MouseDrag();
this.addMouseListener(md);
this.addMouseMotionListener(md);
return this;
}
I can at least plot a blue square....

Cannot get mouse position in 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
/* ...*/
}

Categories