I have a Java Swing question. I am currently coding the game checkers as an exercise. I created the checkers pieces as JLabels with an ImageIcon of the checkers piece. I added a MouseListener to update the x and y locations of the label on the frame, and am using an ActionListener to set the label location every 5 milliseconds based on a timer. It works except that the label jumps around the screen when I am dragging it with the mouse (instead of tracking with the mouse).
Does anybody know what is causing this? Is there an easy solution based on the code I currently have?
I am new to swing stuff so I realize I could be taking the wrong approach entirely. I am unable to attach the image, but it is just a 80 x 80 px square with a solid black circle in the foreground and the background is transparent. Thanks a lot!
package checkers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class Piece2 extends JLabel implements
ActionListener, MouseListener, MouseMotionListener{
ImageIcon checkerIcon;
String color = null;
Timer t = new Timer(5, this);
int x, y, width = 80, height = 80;
public Piece2(int initX, int initY, String color){
this.x = initX;
this.y = initY;
this.color = color;
t.start();
setLocation(x, y);
setSize(width, height);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
addMouseMotionListener(this);
addMouseListener(this);
if(color.equals("Red")){
checkerIcon = new ImageIcon("/RedChecker.png");
}
else if(color.equals("Black")){
checkerIcon = new ImageIcon("/BlackChecker.png");
}
setIcon(checkerIcon);
}
#Override
public void actionPerformed(ActionEvent e) {
setLocation(x, y);
}
/**
* Mouse Event Listeners
*
*/
#Override
public void mouseDragged(MouseEvent e) {
this.x = e.getX();
this.y = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
x = x - (x % 50);
y = y - (y % 50);
}
#Override
public void mouseMoved(MouseEvent e) {}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
//To test Piece
public static void main(String[] args){
Piece2 p1 = new Piece2(0, 0, "Black");
JFrame frame1 = new JFrame("Test");
frame1.setSize(800, 800);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(p1);
frame1.setVisible(true);
}
}
Related
I have a program that moves the buttons to the front of the screen when you click and drag them. The problem is that once the layered pane adds the component to the layer above the other layers, it moves the component back to the origin of the JFrame.
package Control;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class LayeredPaneTest {
static JLayeredPane layeredPane;
static int screenX;
static int screenY;
public static MouseListener getMouseListener(JComponent component) {
MouseListener mListener = new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
screenX = e.getXOnScreen();
screenY = e.getYOnScreen();
layeredPane.add(component, new Integer(1), 0); //this method is the one that makes the component go back to the origin
//If I delete this method, the buttons no longer go back to the origin, but the layered obviously doesn't work
//I've tried adding a setBounds method here for component, but it still goes back to the origin
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
};
return mListener;
}
public static MouseMotionListener getMouseMotionListener(JComponent component) {
MouseMotionListener mmListener = new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
int deltaX = e.getXOnScreen() - screenX;
int deltaY = e.getYOnScreen() - screenY;
component.setLocation(deltaX, deltaY);
}
#Override
public void mouseMoved(MouseEvent e) {}
};
return mmListener;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setLocation(0, 0);
frame.setSize(400, 400);
frame.setVisible(true);
layeredPane = new JLayeredPane();
JButton button1 = new JButton("JButton 1");
button1.setBackground(Color.RED);
button1.setSize(100, 50);
button1.addMouseListener(getMouseListener(button1));
button1.addMouseMotionListener(getMouseMotionListener(button1));
layeredPane.add(button1, new Integer(0), 0);
button1.setBounds(0, 0, button1.getWidth(), button1.getHeight());
JButton button2 = new JButton("JButton 2");
button2.setBackground(Color.BLUE);
button2.setSize(100, 50);
button2.addMouseListener(getMouseListener(button2));
button2.addMouseMotionListener(getMouseMotionListener(button2));
layeredPane.add(button2, new Integer(0), 0);
button1.setBounds(100, 100, button2.getWidth(), button2.getHeight());
JButton button3 = new JButton("JButton 3");
button3.setBackground(Color.GREEN);
button3.setSize(100, 50);
button3.addMouseListener(getMouseListener(button3));
button3.addMouseMotionListener(getMouseMotionListener(button3));
layeredPane.add(button3, new Integer(0), 0);
button1.setBounds(200, 200, button3.getWidth(), button3.getHeight());
frame.add(layeredPane);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I've spent many hours trying to switch methods around, testing and whatnot, but the problem relies on the method layeredPane.add(component, new Integer(1), 0);. I'm very new to JLayeredPanes, so there must be something I'm missing.
The problem is not with the layeredPane.add() method, it is in the way that you calculate the new component location.
Let's say that a button is a location so that when you click at position (200, 100) you press the button. At that moment you store screenX=200; screenY=100;.
If you now move the mouse to (210, 100) you calculate the new position as deltaX = 210-200; and deltaY = 100 - 100;, which places the component in the top left corner.
You probably should store the offset of the mouse relative to the component on the mousePressed event and adjust the component location for this offset on the mouseDragged event:
static int offsetX;
static int offsetY;
public static MouseListener getMouseListener(JComponent component) {
// [...]
#Override
public void mousePressed(MouseEvent e) {
offsetX = e.getXOnScreen() - component.getX();
offsetY = e.getYOnScreen() - component.getY();
layeredPane.add(component, new Integer(1), 0);
}
// [...]
}
public static MouseMotionListener getMouseMotionListener(JComponent component) {
MouseMotionListener mmListener = new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
int posX = e.getXOnScreen() - offsetX;
int posY = e.getYOnScreen() - offsetY;
component.setLocation(posX, posY);
}
// [...]
};
return mmListener;
}
I'm trying to create a program that lets the user move a circle in a JPanel, But I'm facing some problems.
My program:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.GridLayout;
public class SixthProgram
{
public static void main(String[] args)
{
GUI prog=new GUI("SixthProgram");
prog.setBounds(350,250,500,250);
prog.setVisible(true);
}
}
class GUI extends JFrame implements MouseListener, MouseMotionListener, ActionListener
{
JButton color1, color2, color3 ,color4 ,color5;
JPanel mainPan, colorPan;
Color color=Color.BLACK;
int x=0,y=0;
public GUI(String header)
{
super(header);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
maker();
addMouseListener(this);
addMouseMotionListener(this);
add(mainPan , BorderLayout.CENTER);
add(colorPan, BorderLayout.PAGE_END);
}
public void maker()
{
colorPan = new JPanel();
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel);
colorPan.setBorder(compound);
colorPan.setLayout(new GridLayout(1, 0));
mainPan = new JPanel(){
#Override
public void paintComponent(Graphics g)
{
//g.setColor(Color.WHITE);
//g.fillRect(0,0,getWidth(),getHeight());
super.paintComponent(g); //Do the same thing as above(Clear JPanel)
g.setColor(color);
g.fillOval(x,y,50,50);
}
};
color1 = new JButton();
color2 = new JButton();
color3 = new JButton();
color4 = new JButton();
color5 = new JButton();
color1.setBackground(Color.WHITE);
color2.setBackground(Color.GREEN);
color3.setBackground(Color.RED);
color4.setBackground(Color.BLUE);
color5.setBackground(Color.BLACK);
color1.addActionListener(this);
color2.addActionListener(this);
color3.addActionListener(this);
color4.addActionListener(this);
color5.addActionListener(this);
colorPan.add(color1);
colorPan.add(color2);
colorPan.add(color3);
colorPan.add(color4);
colorPan.add(color5);
colorPan.setBackground(Color.GREEN);
}
public void mouseExited(MouseEvent e) //MouseListener overrided methods
{
System.out.println("Exit");
}
public void mouseEntered(MouseEvent e)
{
System.out.println("Enter");
}
public void mouseReleased(MouseEvent e)
{
System.out.println("Release");
}
public void mousePressed(MouseEvent e)
{
System.out.println("Press");
if((e.getX()+50 <= getWidth()) &&
(e.getY()+50 <= (getHeight() - colorPan.getHeight()))) // Preventing out of bounds
{
x=e.getX();
y=e.getY();
repaint();
}
}
public void mouseClicked(MouseEvent e) //Press+Release=Click
{
System.out.println("Click");
}
public void mouseDragged(MouseEvent e) //MouseMotionListener overrided methods
{
//System.out.println("Dragged to ("+ e.getX() +","+ e.getY() +")");
if((e.getX()>=0 && e.getY()>=0) &&
(e.getX()+50 <= getWidth()) &&
(e.getY()+50 <= (getHeight() - colorPan.getHeight())) )
{
x=e.getX();
y=e.getY();
repaint();
}
}
public void mouseMoved(MouseEvent e)
{
//System.out.println("Moved to ("+ e.getX() +","+ e.getY() +")");
}
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
color = button.getBackground();
repaint();
}
}
The above code produces the expected output:
The problems are:
When I drag the circle around, the circle doesn't seem to be drawn at the position of the mouse:
In the above screenshot, I'm dragging the mouse , but the circle seems to be drawn at a position below the mouse.
The circle gets drawn behind the colorchooser JPanel(colorPan):
I would like the circle, not to enter colorPan's territory.
The circle get to move too far to the right:
You can observe a part of the circle being outside the JPanel(mainPan).
I'm pretty sure there is something wrong with my mouseDragged method:
public void mouseDragged(MouseEvent e)
{
//System.out.println("Dragged to ("+ e.getX() +","+ e.getY() +")");
if((e.getX()>=0 && e.getY()>=0) &&
(e.getX()+50 <= getWidth()) &&
(e.getY()+50 <= (getHeight() - colorPan.getHeight())) )
{
x=e.getX();
y=e.getY();
repaint();
}
}
but I can't seem to find the problem. Can anyone help me solve these problems?
You need to add MouseListener/MouseMotionListener to drawing panel instead of GUI like next :
mainPan.addMouseListener(this);
mainPan.addMouseMotionListener(this);
Or you can use SwingUtilities.convertPoint(...) method to convert point from one component to another, like next:
Point convertPoint = SwingUtilities.convertPoint(GUI.this, e.getPoint(), mainPan);
x=convertPoint.x;
y=convertPoint.y;
I have an assignment that I am doing where I am supposed to implement and design an application that plays a game called catch the creature. Have the creature appear at a random location then disappear and reappear somewhere else. The goal is to "catch" the creature by clicking the creature with a mouse button. Record the number of times the creature is caught.
I need help just displaying the creature which is an JPEG of a pikachu, I have tried a few things but none of them work. Any help is appreciated thank you!
Main Code:
import javax.swing.*;
public class Catch_The_Creature
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Catch the Creature");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Creature panel = new Creature();
JOptionPane.showMessageDialog(frame, "Catch Pikachu!");
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Creature Code:
import java.awt.*;
import java.util.Random;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Creature extends JPanel
{
private final int WIDTH = 400, HEIGHT = 300;
private final int DELAY=20, IMAGE_SIZE = 60;
private ImageIcon image;
private int pikachuX, pikachuY;
private int x, y;
private int catchCount=0;
private static Random generator = new Random();
private Timer time;
private ActionListener updater;
private JLabel countLabel;
public Creature()
{
image = new ImageIcon("image/pikachu.jpg");
time = new Timer(DELAY, updater);
addMouseListener ((MouseListener) new MouseClickedListener());
setBackground (Color.green);
setPreferredSize(new Dimension(1900,1000));
time.start();
}
public boolean point(int x, int y)
{
if (x == pikachuX && y == pikachuY)
{
catchCount++;
return true;
}
return false;
}
public int getCatchCount()
{
return catchCount;
}
private class MouseClickedListener extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
{
point(event.getX(), event.getY());
}
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(image.getImage(),WIDTH, HEIGHT, null);
page.drawString("Pikachus Captured: " + catchCount, 10, 35);
setFont(new Font("Arial", Font.BOLD,35));
}
public void actionPerformed(ActionEvent event)
{
time.setDelay(1000);
x += pikachuX;
y += pikachuY;
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
pikachuX = pikachuX * -1;
if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
pikachuY = pikachuY * -1;
repaint();
}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0){}
}
It doesn't look like you ever add the ImageIcon to the panel or tell it to paint in the paintComponent() method.
First solution [Preferred]: Add ImageIcon to the panel. In the constructor
super.add(image);
Make sure you use the correct layout (probably a null or absolute layout) and that you update the coordinates of the ImageIcon itself, not just some member variables.
Second solution: Paint the ImageIcon in the paintComponent() method. This is probably discouraged because it goes against the general Swing principles.
Make sure your Image file is in the right directory. If you're running from netbeans or eclipse your file structure should look like this
ProjectRoot
src
bin
image
pikachu.jpeg
Since you are using "image/pikachu.png", you image filder should be a child of the project root folder as that's where the IDE will first search fore your file path
Edit: To draw image. Instead of using ImageIcon, use BufferedImage
try {
BufferedImage image = ImageIO.read("image/pikachu.jpeg");
} catch (Exception ex){
ex.printStackTrace();
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(image, x, y, heightYouWant, widthYouWant, this);
page.drawString("Pikachus Captured: " + catchCount, 10, 35);
setFont(new Font("Arial", Font.BOLD,35));
}
All i needed to do was put values on where I wanted the picture to start at in the constructor.
public Creature()
{
image = new ImageIcon ("pikachu.png");
time = new Timer(DELAY, updater);
x = 0;
y = 50;
addMouseListener ((MouseListener) new MouseClickedListener());
setBackground (Color.green);
setPreferredSize(new Dimension(1900,1000));
time.start();
}
While still using an Image Icon and still paint the image in the paint component.
public void paintComponent(Graphics page)
{
super.paintComponent(page);
image.paintIcon (this, page, x, y);
page.drawString("Pikachus Captured: " + catchCount, 10, 35);
setFont(new Font("Arial", Font.BOLD,35));
}
I extended the toolbar on a mac using a JPanel (see image), but the part that is the actualy toolbar (not the JPanel) is the only part that you can click and drag. How do I allow the user to click and drag the JPanel to move the window, just like they would the toolbar
The top mm or so of the image is the actual toolbar (with the text), the rest is the JPanel (with buttons).
Here is the code for the UnifiedToolPanel, which is set to the north of the border layout in the JFrame:
package gui;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import com.jgoodies.forms.factories.Borders;
public class UnifiedToolbarPanel extends JPanel implements WindowFocusListener {
public static final Color OS_X_UNIFIED_TOOLBAR_FOCUSED_BOTTOM_COLOR =
new Color(64, 64, 64);
public static final Color OS_X_UNIFIED_TOOLBAR_UNFOCUSED_BORDER_COLOR =
new Color(135, 135, 135);
public static final Color OS_X_TOP_FOCUSED_GRADIENT = new Color(214+8, 214+8, 214+8);
public static final Color OS_X_BOTTOM_FOCUSED_GRADIENT = new Color(217, 217, 217);
public static final Color OS_X_TOP_UNFOCUSED_GRADIENT = new Color(240+3, 240+3, 240+3);
public static final Color OS_X_BOTTOM_UNFOCUSED_GRADIENT = new Color(219, 219, 219);
public UnifiedToolbarPanel() {
// make the component transparent
setOpaque(true);
Window window = SwingUtilities.getWindowAncestor(this);
// create an empty border around the panel
// note the border below is created using JGoodies Forms
setBorder(Borders.createEmptyBorder("3dlu, 3dlu, 1dlu, 3dlu"));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Window window = SwingUtilities.getWindowAncestor(this);
Color color1 = window.isFocused() ? OS_X_TOP_FOCUSED_GRADIENT
: OS_X_TOP_UNFOCUSED_GRADIENT;
Color color2 = window.isFocused() ? color1.darker()
: OS_X_BOTTOM_UNFOCUSED_GRADIENT;
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
#Override
public Border getBorder() {
Window window = SwingUtilities.getWindowAncestor(this);
return window != null && window.isFocused()
? BorderFactory.createMatteBorder(0,0,1,0,
OS_X_UNIFIED_TOOLBAR_FOCUSED_BOTTOM_COLOR)
: BorderFactory.createMatteBorder(0,0,1,0,
OS_X_UNIFIED_TOOLBAR_UNFOCUSED_BORDER_COLOR);
}
#Override
public void windowGainedFocus(WindowEvent e) {
repaint();
}
#Override
public void windowLostFocus(WindowEvent e) {
repaint();
}
}
How do I allow the user to click and drag the JPanel to move the window
Here is the way :
private int x;
private int y;
//.....
//On mouse pressed:
jpanel.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent ev){
x = ev.getX ();
y = ev.getY();
}
});
//....
//on mouse dragged
jpanel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
int x = evt.getXOnScreen()-this.x;
int y = evt.getYOnScreen -this.y;
this.setLocation(x,y);
}
});
this.setLocation(x,y) will moves the Frame not the panel, I thought that your class extended JFrame.
However, you can create a method that returns a point (x,y) and set it to the window.
There wasn't really an answer with the Point class so I will be adding my contribution instead of storing the x, y cords of the MouseEvent, We store the Point
Here is show you can do it, Define a global Variable of the Class java.awt.Point
private Point currentLocation;
we then store the point to currentLocation once mouse is pressed using MouseListener
panel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
currentLocation = e.getPoint();
}
});
and we set the JFrame location when mouse is dragged using MouseMotionListener
panel.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
Point currentScreenLocation = e.getLocationOnScreen();
setLocation(currentScreenLocation.x - currentLocation.x, currentScreenLocation.y - currentLocation.y);
}
});
and we put all the code together inside a HelperMethod to be used anywhere
public void setDraggable(JPanel panel) {
panel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
currentLocation = e.getPoint();
}
});
panel.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
Point currentScreenLocation = e.getLocationOnScreen();
setLocation(currentScreenLocation.x - currentLocation.x, currentScreenLocation.y - currentLocation.y);
}
});
}
I store my HelperMethod in a class that extends JFrame Hence why I have access to setLocation that belongs to JFrame without a variable.
I have my code set up to where the Boolean boxDetect will be set to true if the mouse is clicked within the Rectangle startButton. The rest is just formatting nothing special! This is the initial screen before you press inside the rectangle, and once inside the rectangle and pressed it should repaint the screen to a rectangle at points 400,400.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
public class spaceInvadersIntroScreen implements MouseListener
{
private JFrame frame;
private MyPanel panel;
private double startButtonX = 0;
private double startButtonY = 0;
private Rectangle startButton;
private Boolean boxDetect = false;
public static void main(String[] args){ new spaceInvadersIntroScreen(); }
public spaceInvadersIntroScreen()
{
frame = new JFrame("Space Invaders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
startButtonX = screenSize.getWidth() / 2; //Finds the X value of the center of the screen
startButtonY = screenSize.getHeight() / 2; //Finds the Y value of the center of the screen
frame.setSize(screenSize); //width and height
panel = new MyPanel();
frame.getContentPane().add(panel);
frame.setVisible(true);
startButton = new Rectangle((int)(startButtonX - 200), (int)(startButtonY - 75), 400, 150); //Creates Rectangle in the middle of the screen
}
class MyPanel extends JPanel
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
if(boxDetect == false)
{
Graphics2D g2d = (Graphics2D) g;
//Background
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0, 1440, 870);
//Code for an X centered title regardless of the screen length
String title = "SPACE INVADERS";
Font textFont = new Font("monospaced", Font.BOLD, 150);
FontMetrics textMetrics = g2d.getFontMetrics(textFont);
g2d.setFont(textFont);
int centeredX = (this.getWidth()/2) - (textMetrics.stringWidth(title)/2);
//Prints SPACE INVADERS to the screen
g2d.setColor(Color.WHITE);
g2d.setFont(textFont);
g2d.drawString(title, centeredX, 200);
//draw the Button
g2d.setColor(Color.white);
g2d.fill(startButton);
}
else
{
g.setColor(Color.black);
g.drawRect(400, 400, 400, 400);
}
}
}
#Override
public void mouseReleased(MouseEvent e)
{
double xCoord = e.getX();
double yCoord = e.getY();
if(startButton.contains(xCoord,yCoord) == true)
{
boxDetect = true;
}
panel.repaint();
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}
You need to add the MouseListener for it to work. Question: Where do you call addMouseListener(...)? Answer: you don't. Solution: make this method call to add the MouseListener to the component that needs it.