Help!! Trying to write a program that make a square move with keyboard and mouse.
Hi! I need help with my program, i typed the codes but it is not functioning the way i wanted. Right now, i can move the square with my keyboard arrows keys. But i dont know why my mouse cant drag the square. This is a school project. I was trying to merge 2 project together.
Here is my code:
Code:
package helloworld;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/*
* This applet demonstrates Focus events and Key events. A colored square
* is drawn on the applet. By pressing the arrow keys, the user can move
* the square up, down, left, or right. By pressing the keys
* R, G, B, or K, the user can change the color of the square to red,
* green, blue, or black, respectively. Of course, none of the keys
* will have any effect if the applet does not have the keyboard input
* focus. The applet changes appearance when it has the input focus.
* A cyan-colored border is drawn around it. When it does not have
* the input focus, the message "Click to activate" is displayed
* and the border is gray.
* This class contains a main() routine; when it is run as a stand-alone
* application, the same JPanel that is used in the applet is shown in a
* window instead.
*/
public class ShapeMover extends JApplet {
private int x1, y1; // Coords of top-left corner of the red square.
/**
* The main program just opens a window that shows an object of type
* ContentPanel -- a nested class that is defined in this class.
*/
public static void main(String[] args) {
JFrame window = new JFrame("ShapeMover");
window.setContentPane( new ContentPanel() );
window.setSize(500,500);
window.setLocation(100,100);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
public ShapeMover() {
Dragger listener = new Dragger(); // Listening object, belonging to a nested
// class that is defined below.
addMouseListener(listener); // Set up listening.
addMouseMotionListener(listener);
}
private class Dragger implements MouseListener, MouseMotionListener {
/* Some variables used during dragging */
boolean dragging; // Set to true when a drag is in progress.
boolean dragRedSquare; // True if red square is being dragged, false
// if blue square is being dragged.
int offsetX, offsetY; // Offset of mouse-click coordinates from the
// top-left corner of the square that was
// clicked.
public void mouseClicked(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void mousePressed(MouseEvent evt) {
if (dragging) // Exit if a drag is already in progress.
return;
int x = evt.getX(); // Location where user clicked.
int y = evt.getY();
if (x >= x1 && x < x1+30 && y >= y1 && y < y1+30) {
// It's the red square.
dragging = true;
dragRedSquare = true;
offsetX = x - x1; // Distance from corner of square to (x,y).
offsetY = y - y1;
}
}
/**
* Dragging stops when user releases the mouse button.
*/
public void mouseReleased(MouseEvent evt) {
dragging = false;
}
/**
* Respond when the user drags the mouse. If a square is
* not being dragged, then exit. Otherwise, change the position
* of the square that is being dragged to match the position
* of the mouse. Note that the corner of the square is placed
* in the same relative position with respect to the mouse that i
* had when the user started dragging it.
*/
public void mouseDragged(MouseEvent evt) {
if (dragging == false)
return;
int x = evt.getX();
int y = evt.getY();
if (dragRedSquare) { // Move the red square.
x1 = x - offsetX;
y1 = y - offsetY;
}
repaint(); // (Calls the repaint() method in the DragTwoSquaresPanel class.)
}
public void mouseEntered(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void mouseExited(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void mouseMoved(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Respond when the user presses the mouse on the panel.
* Check which square the user clicked, if any, and start
* dragging that square.
*/
/**
* The init() method of the applet just sets the content pane
* of the applet to be a panel of type ContentPanel, a nested class
* that is defined in this class and which does all the work.
*/
}
public void init() {
setContentPane( new ContentPanel() );
}
public static class ContentPanel extends JPanel
implements KeyListener, FocusListener, MouseListener {
// (Note: MouseListener is implemented only so that
// the applet can request the input focus when
// the user clicks on it.)
private static final int SQUARE_SIZE = 40; // Length of side of square.
private Color squareColor; // The color of the square.
private int x1, y1; // Coordinates corner of square.
/**
* The constructor sets the initial position and color of the square
* and registers itself to act as a listener for Key, Focus, and
* Mouse events.
*/
public ContentPanel() {
y1 = 200; // Initial position of top-left corner of square.
x1 = 200;
squareColor = Color.RED; // Initial color of square.
setBackground(Color.WHITE);
addKeyListener(this); // Set up event listening.
addFocusListener(this);
addMouseListener(this);
} // end init();
/**
* Draws a border, square, and message in the panel. The message and
* the color of the border depend on whether or not the pane has
* the input focus.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g); // Fills the panel with its
// background color, which is white.
/* Draw a 3-pixel border, colored cyan if the applet has the
keyboard focus, or in light gray if it does not. */
if (hasFocus())
g.setColor(Color.BLACK);
else
g.setColor(Color.LIGHT_GRAY);
int width = getSize().width; // Width of the applet.
int height = getSize().height; // Height of the applet.
g.drawRect(0,0,width-1,height-1);
g.drawRect(1,1,width-3,height-3);
g.drawRect(2,2,width-5,height-5);
/* Draw the square. */
g.setColor(squareColor);
g.fillRect(x1, y1, SQUARE_SIZE, SQUARE_SIZE);
/* Print a message that depends on whether the panel has the focus. */
g.setColor(Color.BLUE);
if (hasFocus()) {
g.drawString("Arrow Keys Move Square",7,20);
g.drawString("Y, R, G, B Change Color",7,40);
}
else
g.drawString("Click to activate",7,20);
} // end paintComponent()
// ------------------- Event handling methods ----------------------
/**
* This will be called when the panel gains the input focus. It just
* calls repaint(). The panel will be redrawn with a cyan-colored border
* and with a different message.
*/
public void focusGained(FocusEvent evt) {
repaint(); // redraw with cyan border
}
/**
* This will be called when the panel loses the input focus. It just
* calls repaint(). The panel will be redrawn with a gray-colored border
* and with the message "Click to activate."
*/
public void focusLost(FocusEvent evt) {
repaint(); // redraw without cyan border
}
/**
* This method is called when the user types a character on the keyboard
* while the panel has the input focus. If the character is R, G, B, or K
* (or the corresponding lower case characters), then the color of the
* square is changed to red, green, blue, or black, respectively.
*/
public void keyTyped(KeyEvent evt) {
char ch = evt.getKeyChar(); // The character typed.
if (ch == 'B' || ch == 'b') {
squareColor = Color.BLUE;
repaint(); // Redraw panel with new color.
}
else if (ch == 'G' || ch == 'g') {
squareColor = Color.GREEN;
repaint();
}
else if (ch == 'R' || ch == 'r') {
squareColor = Color.RED;
repaint();
}
else if (ch == 'Y' || ch == 'y') {
squareColor = Color.YELLOW;
repaint();
}
} // end keyTyped()
/**
* This is called each time the user presses a key while the panel has
* the input focus. If the key pressed was one of the arrow keys,
* the square is moved (except that it is not allowed to move off the
* edge of the panel).
*/
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode(); // keyboard code for the pressed key
if (key == KeyEvent.VK_LEFT) {
x1 -= 8;
if (x1 < 3)
x1 = 3;
repaint();
}
else if (key == KeyEvent.VK_RIGHT) {
x1 += 8;
if (x1 > getWidth() - 3 - SQUARE_SIZE)
x1 = getWidth() - 3 - SQUARE_SIZE;
repaint();
}
else if (key == KeyEvent.VK_UP) {
y1 -= 8;
if (y1 < 3)
y1 = 3;
repaint();
}
else if (key == KeyEvent.VK_DOWN) {
y1 += 8;
if (y1 > getHeight() - 3 - SQUARE_SIZE)
y1 = getHeight() - 3 - SQUARE_SIZE;
repaint();
}
} // end keyPressed()
/**
* This is called each time the user releases a key while the panel
* has the input focus. In this class, it does nothing, but it is
* required to be here by the KeyListener interface.
*/
public void keyReleased(KeyEvent evt) {
}
/**
* This is called when the user clicks the panel with the mouse.
* It just requests that the input focus be given to the panel.
*/
public void mousePressed(MouseEvent evt) {
requestFocus();
}
public void mouseEntered(MouseEvent evt) { } // Required by the
public void mouseExited(MouseEvent evt) { } // MouseListener
public void mouseReleased(MouseEvent evt) { } // interface.
public void mouseClicked(MouseEvent evt) { }
} // end nested class ContentPanel
}
// end class KeyboardAndFocusDemo