I'm new to Java graphics and threads, and I'm trying to make a game (specifically, Pong). The idea is that two people can play on the same keyboard (i.e. there are two paddles that are controlled through different keys). Currently, both players can't move their paddle at the same time.
Is there a solution to this? Are separate threads the answer?
If possible, I'd like the paddles to be able to move (at least seemingly) at the same time.
Update: It seems like using a Set<Integer> to store pressed keys is the best option. I've done that (and it works), but I'm wondering if any of this code is not on the Event Dispatching Thread (EDT) and if I need to use SwingUtilities.invokeLater();. Here's the necessary code:
private Set<Integer> keysDown = Collections.synchronizedSet(new HashSet<Integer>());
public void keyPressed(KeyEvent e)
{
keysDown.add(e.getKeyCode());
}
public void keyReleased(KeyEvent e)
{
keysDown.remove(e.getKeyCode());
}
public void updatePaddlePositions()
{
if (keysDown.contains(KeyEvent.VK_W))
paddleOne.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_S))
paddleOne.move(PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_UP))
paddleTwo.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_DOWN))
paddleTwo.move(PADDLE_MOVE_INCREMENT);
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
System.out.println("You Interrupted the game!");
}
canvas.repaint();
}
Here's the paintComponent method of the canvas object:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
paddleOne.paint(g);
paddleTwo.paint(g);
updatePaddlePositions(); // Does this need to be SwingUtilities.invokeLater(this)?
// And should updatePaddlePositions() be run() as a result?
}
And here's the paint method of the paddleOne and paddleTwo objects:
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
}
Feel free to comment on my design if anything pops out as "bad" to you. Lastly, what does Collections.synchronizedSet(new HashSet<Integer>()) mean/do?
Update #2: It seems like key bindings are the way to go (even though they take more code, in this case). What make key bindings better? Is it that they work separately from everything else (and don't need window focus like key listeners)?
Also, I understand that HashSet<Integer> is just a subclass of Set<Integer>, but what is the purpose of Collections.synchronizedSet(...)? I'm assuming it has to do with threads, but I don't know why it's needed in this program (if it is at all).
First off, use Swing KeyBindings Also I see no real need for multi-threadung unless you want your game multi-threaded.
To clarify the problem is you need to be able for 2 players to press different keys?
If so:
Solution:
Simply use booleans to flag whether or not a key is pressed down, you would than of course have to reset the flag when the key is released.
In your game logic you would check the states if the booleans and act appropriately.
See my below example (both paddles can move independently using W and S and UP and DOWN keys):
public class GameLogic {
public GameLogic() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Game Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create the gamepanel
final GamePanel gp = new GamePanel(600, 500);
//create panel to hold buttons to start pause and stop the game
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
final JButton startButton = new JButton("Start");
final JButton pauseButton = new JButton("Pause");
final JButton stopButton = new JButton("Stop");
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
//add listeners to buttons (most of the actions - excuse the pun - takes palce here :)
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//clear enitites currently in array
gp.clearEntities();
ArrayList<BufferedImage> ballEntityImages = new ArrayList<>();
ArrayList<Long> ballEntityTimings = new ArrayList<>();
ballEntityImages.add(createColouredImage("white", 50, 50, true));
ballEntityTimings.add(500l);
Entity ballEntity = new Entity(gp.getWidth() / 2, gp.getHeight() / 2, ballEntityImages, ballEntityTimings);
ballEntity.RIGHT = true;
//create images for entities
ArrayList<BufferedImage> advEntityImages = new ArrayList<>();
ArrayList<Long> advEntityTimings = new ArrayList<>();
advEntityImages.add(createColouredImage("orange", 10, 100, false));
advEntityTimings.add(500l);
advEntityImages.add(createColouredImage("blue", 10, 100, false));
advEntityTimings.add(500l);
//create entities
AdvancedSpritesEntity player1Entity = new AdvancedSpritesEntity(0, 100, advEntityImages, advEntityTimings);
ArrayList<BufferedImage> entityImages = new ArrayList<>();
ArrayList<Long> entityTimings = new ArrayList<>();
entityImages.add(createColouredImage("red", 10, 100, false));
entityTimings.add(500l);//as its the only image it doesnt really matter what time we put we could use 0l
//entityImages.add(createColouredImage("magenta", 100, 100));
//entityTimings.add(500l);
Entity player2Entity = new Entity(gp.getWidth() - 10, 200, entityImages, entityTimings);
gp.addEntity(player1Entity);
gp.addEntity(player2Entity);//just a standing still Entity for testing
gp.addEntity(ballEntity);//just a standing still Entity for testing
//create Keybingings for gamepanel
GameKeyBindings gameKeyBindings = new GameKeyBindings(gp, player1Entity, player2Entity);
GamePanel.running.set(true);
//start the game loop which will repaint the screen
runGameLoop(gp);
startButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
}
});
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
boolean b = GamePanel.paused.get();
GamePanel.paused.set(!b);//set it to the opposite of what it was i.e paused to unpaused and vice versa
if (pauseButton.getText().equals("Pause")) {
pauseButton.setText("Un-pause");
} else {
pauseButton.setText("Pause");
}
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
GamePanel.running.set(false);
GamePanel.paused.set(false);
/* if we want enitites to be cleared and a blank panel shown
gp.clearEntities();
gp.repaint();
*/
if (!pauseButton.getText().equals("Pause")) {
pauseButton.setText("Pause");
}
startButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
}
});
//add buttons to panel
buttonPanel.add(startButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
//add gamepanel to jframe and button panel
frame.add(gp);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//Simply used for testing (to simulate sprites) can create different colored images
public static BufferedImage createColouredImage(String color, int w, int h, boolean circular) {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
switch (color.toLowerCase()) {
case "green":
g2.setColor(Color.GREEN);
break;
case "magenta":
g2.setColor(Color.MAGENTA);
break;
case "red":
g2.setColor(Color.RED);
break;
case "yellow":
g2.setColor(Color.YELLOW);
break;
case "blue":
g2.setColor(Color.BLUE);
break;
case "orange":
g2.setColor(Color.ORANGE);
break;
case "cyan":
g2.setColor(Color.CYAN);
break;
case "gray":
g2.setColor(Color.GRAY);
break;
default:
g2.setColor(Color.WHITE);
break;
}
if (!circular) {
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
} else {
g2.fillOval(0, 0, img.getWidth(), img.getHeight());
}
g2.dispose();
return img;
}
//Starts a new thread and runs the game loop in it.
private void runGameLoop(final GamePanel gp) {
Thread loop = new Thread(new Runnable() {
#Override
public void run() {
gp.gameLoop();
}
});
loop.start();
}
//Code starts here
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {//attempt to set look and feel to nimbus Java 7 and up
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
GameLogic gameLogic = new GameLogic();
}
});
}
}
class GameKeyBindings {
public GameKeyBindings(JComponent gp, final Entity entity, final Entity entity2) {
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "W pressed");
gp.getActionMap().put("W pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "W released");
gp.getActionMap().put("W released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "S pressed");
gp.getActionMap().put("S pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "S released");
gp.getActionMap().put("S released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down pressed");
gp.getActionMap().put("down pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down released");
gp.getActionMap().put("down released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up pressed");
gp.getActionMap().put("up pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up released");
gp.getActionMap().put("up released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = false;
}
});
}
}
class AdvancedSpritesEntity extends Entity {
public AdvancedSpritesEntity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(x, y, images, timings);
}
void setAnimation(ArrayList<BufferedImage> images, ArrayList<Long> timings) {
reset();//reset variables of animator class
setFrames(images, timings);//set new frames for animation
}
}
class Entity extends Animator {
private int speed = 5;
public boolean UP = false, DOWN = false, LEFT = false, RIGHT = false, visible;
private Rectangle2D.Double rect;
public Entity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(images, timings);
UP = false;
DOWN = false;
LEFT = false;
RIGHT = false;
visible = true;
rect = new Rectangle2D.Double(x, y, getCurrentImage().getWidth(), getCurrentImage().getHeight());
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public HashSet<String> getMask(Entity e) {
HashSet<String> mask = new HashSet<>();
int pixel, a;
BufferedImage bi = e.getCurrentImage();//gets the current image being shown
for (int i = 0; i < bi.getWidth(); i++) { // for every (x,y) component in the given box,
for (int j = 0; j < bi.getHeight(); j++) {
pixel = bi.getRGB(i, j); // get the RGB value of the pixel
a = (pixel >> 24) & 0xff;
if (a != 0) { // if the alpha is not 0, it must be something other than transparent
mask.add((e.getX() + i) + "," + (e.getY() - j)); // add the absolute x and absolute y coordinates to our set
}
}
}
return mask; //return our set
}
// Returns true if there is a collision between object a and object b
public boolean checkPerPixelCollision(Entity b) {
// This method detects to see if the images overlap at all. If they do, collision is possible
int ax1 = (int) getX();
int ay1 = (int) getY();
int ax2 = ax1 + (int) getWidth();
int ay2 = ay1 + (int) getHeight();
int bx1 = (int) b.getX();
int by1 = (int) b.getY();
int bx2 = bx1 + (int) b.getWidth();
int by2 = by1 + (int) b.getHeight();
if (by2 < ay1 || ay2 < by1 || bx2 < ax1 || ax2 < bx1) {
return false; // Collision is impossible.
} else { // Collision is possible.
// get the masks for both images
HashSet<String> maskPlayer1 = getMask(this);
HashSet<String> maskPlayer2 = getMask(b);
maskPlayer1.retainAll(maskPlayer2); // Check to see if any pixels in maskPlayer2 are the same as those in maskPlayer1
if (maskPlayer1.size() > 0) { // if so, than there exists at least one pixel that is the same in both images, thus
return true;
}
}
return false;
}
public void move() {
if (UP) {
rect.y -= speed;
}
if (DOWN) {
rect.y += speed;
}
if (LEFT) {
rect.x -= speed;
}
if (RIGHT) {
rect.x += speed;
}
}
#Override
public void update(long elapsedTime) {
super.update(elapsedTime);
getWidth();//set the rectangles height accordingly after image update
getHeight();//set rectangles height accordingle after update
}
public boolean intersects(Entity e) {
return rect.intersects(e.rect);
}
public double getX() {
return rect.x;
}
public double getY() {
return rect.y;
}
public double getWidth() {
if (getCurrentImage() == null) {//there might be no image (which is unwanted ofcourse but we must not get NPE so we check for null and return 0
return rect.width = 0;
}
return rect.width = getCurrentImage().getWidth();
}
public double getHeight() {
if (getCurrentImage() == null) {
return rect.height = 0;
}
return rect.height = getCurrentImage().getHeight();
}
}
class Animator {
private ArrayList<BufferedImage> frames;
private ArrayList<Long> timings;
private int currIndex;
private long animationTime;
private long totalAnimationDuration;
private AtomicBoolean done;//used to keep track if a single set of frames/ an animtion has finished its loop
public Animator(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
currIndex = 0;
animationTime = 0;
totalAnimationDuration = 0;
done = new AtomicBoolean(false);
this.frames = new ArrayList<>();
this.timings = new ArrayList<>();
setFrames(frames, timings);
}
public boolean isDone() {
return done.get();
}
public void reset() {
totalAnimationDuration = 0;
done.getAndSet(false);
}
public void update(long elapsedTime) {
if (frames.size() > 1) {
animationTime += elapsedTime;
if (animationTime >= totalAnimationDuration) {
animationTime = animationTime % totalAnimationDuration;
currIndex = 0;
done.getAndSet(true);
}
while (animationTime > timings.get(currIndex)) {
currIndex++;
}
}
}
public BufferedImage getCurrentImage() {
if (frames.isEmpty()) {
return null;
} else {
try {
return frames.get(currIndex);
} catch (Exception ex) {//images might have been altered so we reset the index and return first image of the new frames/animation
currIndex = 0;
return frames.get(currIndex);
}
}
}
public void setFrames(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
if (frames == null || timings == null) {//so that constructor super(null,null) cause this to throw NullPointerException
return;
}
this.frames = frames;
this.timings.clear();
for (long animTime : timings) {
totalAnimationDuration += animTime;
this.timings.add(totalAnimationDuration);
}
}
}
class GamePanel extends JPanel {
private final static RenderingHints textRenderHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
private final static RenderingHints imageRenderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
private final static RenderingHints colorRenderHints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
private final static RenderingHints interpolationRenderHints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
private final static RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
public static AtomicBoolean running = new AtomicBoolean(false), paused = new AtomicBoolean(false);
private int width, height, frameCount = 0, fps = 0;
private ArrayList<Entity> entities = new ArrayList<>();
private final Random random = new Random();
public GamePanel(int w, int h) {
super(true);//make sure double buffering is enabled
setIgnoreRepaint(true);//mustnt repaint itself the gameloop will do that
width = w;
height = h;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
public void addEntity(Entity e) {
entities.add(e);
}
void clearEntities() {
entities.clear();
}
//Only run this in another Thread!
public void gameLoop() {
//This value would probably be stored elsewhere.
final double GAME_HERTZ = 30.0;
//Calculate how many ns each frame should take for our target game hertz.
final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
//At the very most we will update the game this many times before a new render.
//If you're worried about visual hitches more than perfect timing, set this to 1.
final int MAX_UPDATES_BEFORE_RENDER = 5;
//We will need the last update time.
double lastUpdateTime = System.nanoTime();
//Store the last time we rendered.
double lastRenderTime = System.nanoTime();
//If we are able to get as high as this FPS, don't render again.
final double TARGET_FPS = 60;
final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;
//Simple way of finding FPS.
int lastSecondTime = (int) (lastUpdateTime / 1000000000);
//store the time we started this will be used for updating map and charcter animations
long currTime = System.currentTimeMillis();
while (running.get()) {
if (!paused.get()) {
double now = System.nanoTime();
long elapsedTime = System.currentTimeMillis() - currTime;
currTime += elapsedTime;
int updateCount = 0;
//Do as many game updates as we need to, potentially playing catchup.
while (now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER) {
updateGame(elapsedTime);//Update the entity movements and collision checks etc (all has to do with updating the games status i.e call move() on Enitites)
lastUpdateTime += TIME_BETWEEN_UPDATES;
updateCount++;
}
//If for some reason an update takes forever, we don't want to do an insane number of catchups.
//If you were doing some sort of game that needed to keep EXACT time, you would get rid of this.
if (now - lastUpdateTime > TIME_BETWEEN_UPDATES) {
lastUpdateTime = now - TIME_BETWEEN_UPDATES;
}
drawGame();//draw the game by invokeing repaint (which will call paintComponent) on this JPanel
lastRenderTime = now;
//Update the frames we got.
int thisSecond = (int) (lastUpdateTime / 1000000000);
if (thisSecond > lastSecondTime) {
//System.out.println("NEW SECOND " + thisSecond + " " + frameCount);
fps = frameCount;
frameCount = 0;
lastSecondTime = thisSecond;
}
//Yield until it has been at least the target time between renders. This saves the CPU from hogging.
while (now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES) {
//allow the threading system to play threads that are waiting to run.
Thread.yield();
//This stops the app from consuming all your CPU. It makes this slightly less accurate, but is worth it.
//You can remove this line and it will still work (better), your CPU just climbs on certain OSes.
//FYI on some OS's this can cause pretty bad stuttering. Scroll down and have a look at different peoples' solutions to this.
//On my OS(Windows 7 x64 intel i3) it does not allow for time to make enityt etc move thus all stands still
try {
Thread.sleep(1);
} catch (Exception e) {
}
now = System.nanoTime();
}
}
}
fps = 0;//no more running set fps to 0
}
private void drawGame() {
//Both revalidate and repaint are thread-safe — you need not invoke them from the event-dispatching thread. http://docs.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html
repaint();
}
private void updateGame(long elapsedTime) {
updateEntityMovements(elapsedTime);
checkForCollisions();
}
private void checkForCollisions() {
if (entities.get(0).intersects(entities.get(2)) || entities.get(1).intersects(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
} /*
//This is best used when images have transparent and non-transparent pixels (only detects pixel collisions of non-transparent pixels)
if (entities.get(0).checkPerPixelCollision(entities.get(2)) | entities.get(1).checkPerPixelCollision(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
}
*/
}
private void updateEntityMovements(long elapsedTime) {
for (Entity e : entities) {
e.update(elapsedTime);
e.move();
}
}
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
applyRenderHints(g2d);
drawBackground(g2d);
drawEntitiesToScreen(g2d);
drawFpsCounter(g2d);
frameCount++;
}
public static void applyRenderHints(Graphics2D g2d) {
g2d.setRenderingHints(textRenderHints);
g2d.setRenderingHints(imageRenderHints);
g2d.setRenderingHints(colorRenderHints);
g2d.setRenderingHints(interpolationRenderHints);
g2d.setRenderingHints(renderHints);
}
private void drawEntitiesToScreen(Graphics2D g2d) {
for (Entity e : entities) {
if (e.isVisible()) {
g2d.drawImage(e.getCurrentImage(), (int) e.getX(), (int) e.getY(), null);
}
}
}
private void drawFpsCounter(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.drawString("FPS: " + fps, 5, 10);
}
private void drawBackground(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
//thanks to trashgod for lovely testing background :) http://stackoverflow.com/questions/3256269/jtextfields-on-top-of-active-drawing-on-jpanel-threading-problems/3256941#3256941
g2d.setColor(Color.BLACK);
for (int i = 0; i < 128; i++) {
g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));//random color
g2d.drawLine(getWidth() / 2, getHeight() / 2, random.nextInt(getWidth()), random.nextInt(getHeight()));
}
}
}
This may be a legitimate use case for the low-level access afforded to a KeyListener. See How to Write a Key Listener and KeyEventDemo; don't forget to requestFocusInWindow(). Also consider offering keyboard control for one player and mouse control for the other.
Addendum: #David Kroukamp has adduced an appealing counter-example using key bindings. For reference, the example cited here illustrates one approach to managing key preferences.
Related
I have a project I am working on in that I have to create two objects, I would like the big rectangle(BLUE) to move around the frame every time I press the arrow keys on my keyboard while the small rectangle(RED) is moving away, once the big square touches/tags the small rectangle, screen refreshes and I can move the big rectangle again to chase down the small rectangle. Below is my main class, and IT class where I have implemented my two shapes.
The goal is to have the two rectangles, small rectangle runs away in the frame every time the big rectangle comes close until it's tagged. Would also have to add some kind of score panel on the frame to show updated scores and a timer to count down when the player starts playing.
I need help having the two rectangles move differently and not on top of each other. I would like the second rectangle to move away every time the first rectangle comes close to it moving around the Frame
`
My class IT
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class IT extends JPanel implements ActionListener, KeyListener {
Timer shapeTimer = new Timer(5, this);
public double xPos = 0, yPos = 0, movementX = 0, movementY = 0;
public int rectSize = 50;
public int rectSize2 = 35;
public int windowWidth;
int windowHeight;
public int xBound;
public int yBound;
public IT(int w, int h){
shapeTimer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
windowWidth = w;
windowHeight = h;
xBound = (windowWidth - rectSize);
yBound = (windowHeight - rectSize);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D movableRect = new Rectangle2D.Double(xPos, yPos, rectSize, rectSize);
g2.setColor(Color.BLUE);
g2.draw(movableRect);
g2.fill(movableRect);
Rectangle2D movableRect2 = new Rectangle2D.Double(xPos, yPos, rectSize2, rectSize2);
g2.setColor(Color.RED);
g2.draw(movableRect2);
g2.fill(movableRect2);
}
public void actionPerformed(ActionEvent e){
repaint();
xPos += movementX;
yPos += movementY;
}
public void moveUp(){
if (yPos == 0){
movementY = 0;
movementX = 0;
}
movementY = -0.5;
movementX = 0;
}
public void moveDown(){
if (yPos == yBound){
movementY = 0;
movementX = 0;
}
movementY = 0.5;
movementX = 0;
}
public void moveLeft()
{
if (xPos == 0){
movementY = 0;
movementX = 0;
}
movementX = -0.5;
movementY = 0;
}
public void moveRight(){
if (xPos == xBound)
{
movementY = 0;
movementX = 0;
}
movementX = 0.5;
movementY = 0;
}
public void enlargeSquare(){
rectSize++;
rectSize2++;
}
public void shrinkSquare(){
rectSize--;
rectSize2--;
}
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP){
moveUp();
}
if (keyCode == KeyEvent.VK_DOWN){
moveDown();
}
if (keyCode == KeyEvent.VK_RIGHT){
moveRight();
}
if (keyCode == KeyEvent.VK_LEFT){
moveLeft();
}
if (keyCode == KeyEvent.VK_OPEN_BRACKET)
{
shrinkSquare();
}
if (keyCode == KeyEvent.VK_CLOSE_BRACKET)
{
enlargeSquare();
}
}
public void keyTyped(KeyEvent e){
}
public void keyReleased(KeyEvent e){
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP){
movementX = 0;
movementY = 0;
}
if (keyCode == KeyEvent.VK_DOWN){
movementX = 0;
movementY = 0;
}
if (keyCode == KeyEvent.VK_RIGHT){
movementX = 0;
movementY = 0;
}
if (keyCode == KeyEvent.VK_UP){
movementX = 0;
movementY = 0;
}
}
}
`
MainTester class
`
import javax.swing.*;
import javax.swing.JFrame;
public class MainTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
int frameWidth = 850;
int frameHeight = 650;
JFrame frmMain = new JFrame();
frmMain.setSize(frameWidth, frameHeight);
IT it = new IT(frameWidth, frameHeight);
frmMain.add(it);
frmMain.setVisible(true);
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMain.setTitle("Tag Game");
}
}
`
Use key bindings, seriously, this is going to solve a swagger of issues related to KeyListener.
Decouple and seperate your logic. Each "entity" should be a self contained unit of work. In your case, they should contain information about their color, location and size at a minimum.
For simplicity, I started out with something which could just be painted...
public interface Entity {
public void paint(Graphics2D g2d);
}
Now, you could have a lot of different interfaces which reflect this which can be painted, moved, controlled, represents effects or what ever you need - then your classes should implement the interfaces they need. Then, your engine just deals with the "concepts" it wants to - need all "paintable" entities, need all "movable" entities, etc, when it needs to.
Next I created a concept of a "player". A player is a "paintable" entity, but which can be controlled by the player in some way, so it takes the current state of the "input"s and updates itself based on those states (more about that to come)
public static class PlayerEntity implements Entity {
protected static final int DELTA = 2;
private Rectangle bounds = new Rectangle(0, 0, 35, 35);
private Color fillColor;
public PlayerEntity(Color fillColor, Point location) {
this.fillColor = fillColor;
this.bounds.setLocation(location);
}
public Color getFillColor() {
return fillColor;
}
public Rectangle getBounds() {
return bounds;
}
public Point getCenter() {
return new Point((int)getBounds().getCenterX(), (int)getBounds().getCenterY());
}
public void update(Set<PlayerAction> actions, Dimension size) {
Rectangle currentBounds = getBounds();
int x = currentBounds.x;
int y = currentBounds.y;
if (actions.contains(PlayerAction.UP)) {
y -= DELTA;
}
if (actions.contains(PlayerAction.DOWN)) {
y += DELTA;
}
if (actions.contains(PlayerAction.LEFT)) {
x -= DELTA;
}
if (actions.contains(PlayerAction.RIGHT)) {
x += DELTA;
}
if (y < 0) {
y = 0;
}
if (y + currentBounds.height > size.height) {
y = size.height - currentBounds.height;
}
if (x < 0) {
x = 0;
}
if (x + currentBounds.width > size.width) {
x = size.width - currentBounds.width;
}
getBounds().setLocation(x, y);
}
#Override
public void paint(Graphics2D g2d) {
g2d.setColor(getFillColor());
g2d.fill(getBounds());
}
}
For reference, PlayerAction represents all the valid actions which can be performed by the player, for simplicity sake, I've just stuck to movement:
public enum PlayerAction {
UP, DOWN, LEFT, RIGHT;
}
Next I created a "monster" entity, in this case, the "monster" will always try and follow the player, this implementation is loosely based on Java: Move image towards mouse position
public static class MonsterEntity implements Entity {
protected static final int DELTA = 1;
private Rectangle bounds = new Rectangle(0, 0, 15, 15);
private Color fillColor;
public MonsterEntity(Color fillColor, Point location) {
this.fillColor = fillColor;
this.bounds.setLocation(location);
}
public Color getFillColor() {
return fillColor;
}
public Rectangle getBounds() {
return bounds;
}
public Point getCenter() {
return new Point((int)getBounds().getCenterX(), (int)getBounds().getCenterY());
}
public void moveTowards(Point target) {
Rectangle bounds = getBounds();
Point center = getCenter();
int xDelta = target.x < center.x ? -DELTA : DELTA;
int yDelta = target.y < center.y ? -DELTA : DELTA;
getBounds().setLocation(bounds.x + xDelta, bounds.y + yDelta);
}
#Override
public void paint(Graphics2D g2d) {
g2d.setColor(getFillColor());
g2d.fill(getBounds());
}
}
The monster is always trying to move it's center to the target location (which will eventually be the center of the player)
Now, this is where things become complicated.
We need:
A renderable surface onto which we can paint the player and monster(s)
Input bindings
A "game loop" to update the state of the entities and schedule repaints
For simplicity, I started with a JPanel, made use of Swing Timer and the key bindings API.
public class MainPane extends JPanel {
// This represents the "input bindings", these represent
// abstract actions which can be applied to the player
// or game state.
private enum InputKey {
PRESSED_UP, PRESSED_DOWN, PRESSED_LEFT, PRESSED_RIGHT,
RELEASED_UP, RELEASED_DOWN, RELEASED_LEFT, RELEASED_RIGHT;
public KeyStroke getKeyStroke() {
switch (this) {
case PRESSED_UP: return KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false);
case PRESSED_DOWN: return KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false);
case PRESSED_LEFT: return KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false);
case PRESSED_RIGHT: return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false);
case RELEASED_UP: return KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true);
case RELEASED_DOWN: return KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true);
case RELEASED_LEFT: return KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true);
case RELEASED_RIGHT: return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true);
}
return null;
}
}
private PlayerEntity playerEntity;
private MonsterEntity monsterEntity;
private Timer timer;
private Set<PlayerAction> actions = new HashSet<PlayerAction>();
public MainPane() {
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
inputMap.put(InputKey.PRESSED_UP.getKeyStroke(), InputKey.PRESSED_UP);
inputMap.put(InputKey.PRESSED_DOWN.getKeyStroke(), InputKey.PRESSED_DOWN);
inputMap.put(InputKey.PRESSED_LEFT.getKeyStroke(), InputKey.PRESSED_LEFT);
inputMap.put(InputKey.PRESSED_RIGHT.getKeyStroke(), InputKey.PRESSED_RIGHT);
inputMap.put(InputKey.RELEASED_UP.getKeyStroke(), InputKey.RELEASED_UP);
inputMap.put(InputKey.RELEASED_DOWN.getKeyStroke(), InputKey.RELEASED_DOWN);
inputMap.put(InputKey.RELEASED_LEFT.getKeyStroke(), InputKey.RELEASED_LEFT);
inputMap.put(InputKey.RELEASED_RIGHT.getKeyStroke(), InputKey.RELEASED_RIGHT);
actionMap.put(InputKey.PRESSED_UP, new MoveAction(actions, PlayerAction.UP, true));
actionMap.put(InputKey.PRESSED_DOWN, new MoveAction(actions, PlayerAction.DOWN, true));
actionMap.put(InputKey.PRESSED_LEFT, new MoveAction(actions, PlayerAction.LEFT, true));
actionMap.put(InputKey.PRESSED_RIGHT, new MoveAction(actions, PlayerAction.RIGHT, true));
actionMap.put(InputKey.RELEASED_UP, new MoveAction(actions, PlayerAction.UP, false));
actionMap.put(InputKey.RELEASED_DOWN, new MoveAction(actions, PlayerAction.DOWN, false));
actionMap.put(InputKey.RELEASED_LEFT, new MoveAction(actions, PlayerAction.LEFT, false));
actionMap.put(InputKey.RELEASED_RIGHT, new MoveAction(actions, PlayerAction.RIGHT, false));
Dimension size = getPreferredSize();
Point center = new Point((size.width - 35) / 2, (size.height - 35) / 2);
playerEntity = new PlayerEntity(Color.BLUE, center);
monsterEntity = new MonsterEntity(Color.RED, new Point(size.width - 15, size.height - 15));
}
#Override
public void addNotify() {
super.addNotify();
if (timer != null) {
timer.stop();
}
timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
performTick();
}
});
timer.start();
}
#Override
public void removeNotify() {
super.removeNotify();
if (timer != null) {
timer.stop();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void performTick() {
playerEntity.update(actions, getSize());
monsterEntity.moveTowards(playerEntity.getCenter());
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
playerEntity.paint(g2d);
monsterEntity.paint(g2d);
g2d.dispose();
}
}
Movement (or input) is controlled through the key bindings API, this triggers a MoveAction which updates a centralised state repository (which is then passed to the PlayerEntity so it apply the state accordingly).
For simplicity, I've only used a single Action, but you could make a couple, one representing "press/activate" or "release/deactivate"
public class MoveAction extends AbstractAction {
private Set<PlayerAction> actions;
private PlayerAction action;
private boolean activate;
public MoveAction(Set<PlayerAction> directions, PlayerAction direction, boolean activate) {
this.actions = directions;
this.action = direction;
this.activate = activate;
}
#Override
public void actionPerformed(ActionEvent e) {
if (activate) {
actions.add(action);
} else {
actions.remove(action);
}
}
}
See How to Use Actions for more details about actions.
But why follow this workflow?!
It decouples and decentralises a lot of the workflows. In fact, if you really wanted to, you could also seperate out the Timer and "paint" workflows to seperate classes, further decoupling the classes.
Key bindings solve all the issues related to KeyListener weirdness. It also decouples the input - want to add touch controls/buttons, no worries, it's done via Actions. Want to add joystick/controllers, no worries, it's done via Actions.
Want more monsters?
Change:
private MonsterEntity monsterEntity;
to:
private List<MonsterEntity> monsterEntitys = new ArrayList<>(32);
Change:
monsterEntity = new MonsterEntity(Color.RED, new Point(size.width - 15, size.height - 15));
to:
monsterEntitys.add(new MonsterEntity(Color.RED, new Point(size.width - 15, size.height - 15)));
monsterEntitys.add(new MonsterEntity(Color.RED, new Point(0, 0)));
monsterEntitys.add(new MonsterEntity(Color.RED, new Point(size.width - 15, 0)));
monsterEntitys.add(new MonsterEntity(Color.RED, new Point(0, size.height - 15)));
Change:
monsterEntity.paint(g2d);
to:
for (MonsterEntity entity : monsterEntitys) {
entity.paint(g2d);
}
And now you have more monsters! Have fun with that!
Runnable example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public enum PlayerAction {
UP, DOWN, LEFT, RIGHT;
}
public class MainPane extends JPanel {
private enum InputKey {
PRESSED_UP, PRESSED_DOWN, PRESSED_LEFT, PRESSED_RIGHT,
RELEASED_UP, RELEASED_DOWN, RELEASED_LEFT, RELEASED_RIGHT;
public KeyStroke getKeyStroke() {
switch (this) {
case PRESSED_UP: return KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false);
case PRESSED_DOWN: return KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false);
case PRESSED_LEFT: return KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false);
case PRESSED_RIGHT: return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false);
case RELEASED_UP: return KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true);
case RELEASED_DOWN: return KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true);
case RELEASED_LEFT: return KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true);
case RELEASED_RIGHT: return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true);
}
return null;
}
}
private PlayerEntity playerEntity;
private MonsterEntity monsterEntity;
private Timer timer;
private Set<PlayerAction> actions = new HashSet<PlayerAction>();
public MainPane() {
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
inputMap.put(InputKey.PRESSED_UP.getKeyStroke(), InputKey.PRESSED_UP);
inputMap.put(InputKey.PRESSED_DOWN.getKeyStroke(), InputKey.PRESSED_DOWN);
inputMap.put(InputKey.PRESSED_LEFT.getKeyStroke(), InputKey.PRESSED_LEFT);
inputMap.put(InputKey.PRESSED_RIGHT.getKeyStroke(), InputKey.PRESSED_RIGHT);
inputMap.put(InputKey.RELEASED_UP.getKeyStroke(), InputKey.RELEASED_UP);
inputMap.put(InputKey.RELEASED_DOWN.getKeyStroke(), InputKey.RELEASED_DOWN);
inputMap.put(InputKey.RELEASED_LEFT.getKeyStroke(), InputKey.RELEASED_LEFT);
inputMap.put(InputKey.RELEASED_RIGHT.getKeyStroke(), InputKey.RELEASED_RIGHT);
actionMap.put(InputKey.PRESSED_UP, new MoveAction(actions, PlayerAction.UP, true));
actionMap.put(InputKey.PRESSED_DOWN, new MoveAction(actions, PlayerAction.DOWN, true));
actionMap.put(InputKey.PRESSED_LEFT, new MoveAction(actions, PlayerAction.LEFT, true));
actionMap.put(InputKey.PRESSED_RIGHT, new MoveAction(actions, PlayerAction.RIGHT, true));
actionMap.put(InputKey.RELEASED_UP, new MoveAction(actions, PlayerAction.UP, false));
actionMap.put(InputKey.RELEASED_DOWN, new MoveAction(actions, PlayerAction.DOWN, false));
actionMap.put(InputKey.RELEASED_LEFT, new MoveAction(actions, PlayerAction.LEFT, false));
actionMap.put(InputKey.RELEASED_RIGHT, new MoveAction(actions, PlayerAction.RIGHT, false));
Dimension size = getPreferredSize();
Point center = new Point((size.width - 35) / 2, (size.height - 35) / 2);
playerEntity = new PlayerEntity(Color.BLUE, center);
monsterEntity = new MonsterEntity(Color.RED, new Point(size.width - 15, size.height - 15));
}
#Override
public void addNotify() {
super.addNotify();
if (timer != null) {
timer.stop();
}
timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
performTick();
}
});
timer.start();
}
#Override
public void removeNotify() {
super.removeNotify();
if (timer != null) {
timer.stop();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void performTick() {
playerEntity.update(actions, getSize());
monsterEntity.moveTowards(playerEntity.getCenter());
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
playerEntity.paint(g2d);
monsterEntity.paint(g2d);
g2d.dispose();
}
}
public class MoveAction extends AbstractAction {
private Set<PlayerAction> actions;
private PlayerAction action;
private boolean activate;
public MoveAction(Set<PlayerAction> directions, PlayerAction direction, boolean activate) {
this.actions = directions;
this.action = direction;
this.activate = activate;
}
#Override
public void actionPerformed(ActionEvent e) {
if (activate) {
actions.add(action);
} else {
actions.remove(action);
}
}
}
public interface Entity {
public void paint(Graphics2D g2d);
}
public static class MonsterEntity implements Entity {
protected static final int DELTA = 1;
private Rectangle bounds = new Rectangle(0, 0, 15, 15);
private Color fillColor;
public MonsterEntity(Color fillColor, Point location) {
this.fillColor = fillColor;
this.bounds.setLocation(location);
}
public Color getFillColor() {
return fillColor;
}
public Rectangle getBounds() {
return bounds;
}
public Point getCenter() {
return new Point((int)getBounds().getCenterX(), (int)getBounds().getCenterY());
}
public void moveTowards(Point target) {
Rectangle bounds = getBounds();
Point center = getCenter();
int xDelta = target.x < center.x ? -DELTA : DELTA;
int yDelta = target.y < center.y ? -DELTA : DELTA;
getBounds().setLocation(bounds.x + xDelta, bounds.y + yDelta);
}
#Override
public void paint(Graphics2D g2d) {
g2d.setColor(getFillColor());
g2d.fill(getBounds());
}
}
public static class PlayerEntity implements Entity {
protected static final int DELTA = 2;
private Rectangle bounds = new Rectangle(0, 0, 35, 35);
private Color fillColor;
public PlayerEntity(Color fillColor, Point location) {
this.fillColor = fillColor;
this.bounds.setLocation(location);
}
public Color getFillColor() {
return fillColor;
}
public Rectangle getBounds() {
return bounds;
}
public Point getCenter() {
return new Point((int)getBounds().getCenterX(), (int)getBounds().getCenterY());
}
public void update(Set<PlayerAction> actions, Dimension size) {
Rectangle currentBounds = getBounds();
int x = currentBounds.x;
int y = currentBounds.y;
if (actions.contains(PlayerAction.UP)) {
y -= DELTA;
}
if (actions.contains(PlayerAction.DOWN)) {
y += DELTA;
}
if (actions.contains(PlayerAction.LEFT)) {
x -= DELTA;
}
if (actions.contains(PlayerAction.RIGHT)) {
x += DELTA;
}
if (y < 0) {
y = 0;
}
if (y + currentBounds.height > size.height) {
y = size.height - currentBounds.height;
}
if (x < 0) {
x = 0;
}
if (x + currentBounds.width > size.width) {
x = size.width - currentBounds.width;
}
getBounds().setLocation(x, y);
}
#Override
public void paint(Graphics2D g2d) {
g2d.setColor(getFillColor());
g2d.fill(getBounds());
}
}
}
Other considerations...
Right now the speed/delta is actually really high. I would consider making use of the Shape API, using things like Point2D and Rectangle2D which provide double based properties instead of int, which would give away to reduce the delta values and slow down the entities.
See Working with Geometry for some more details
I am creating a Space Invaders Game with just one Invader. The images are stuttering and are only visible ~10% of the time. What is wrong with my code?
package spaceinvader;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class spaceInvaders extends JApplet implements KeyListener, ActionListener
{
//Declare components and variables
JPanel mainPanel = new JPanel();
ImageIcon carImage = new ImageIcon("ship.png");
ImageIcon invaderImage = new ImageIcon("invader.png");
int intPosX = 240;
int intPosY = 330;
int intXAmount = 15;
boolean shipMoveLeft = false;
boolean shipMoveRight = false;
Timer shipTimer = new Timer(100,this);
int intBulletX = -50;
int intBulletY = -50;
boolean bulletMove = false;
boolean bulletActive = false;
Timer bulletTimer = new Timer(50,this);
int intInvaderX = 0;
int intInvaderY = 0;
int invaderXAmount = 10;
boolean invaderMove = true;
Timer invaderTimer= new Timer(1000,this);
public void init()
{
addKeyListener(this);
setFocusable(true);
resize(600,400);
setContentPane(mainPanel);
shipTimer.start();
bulletTimer.start();
invaderTimer.start();
}
public void actionPerformed(ActionEvent e)
{
requestFocus();
if(shipMoveLeft)
intPosX += intXAmount;
else if(shipMoveRight)
intPosX -= intXAmount;
if(bulletMove && bulletActive){
intBulletY -= 15;
if(intBulletY <= -50){
bulletMove = false;
bulletActive = false;
}
}
if(invaderMove){
intInvaderX += invaderXAmount;
if(intInvaderX > getWidth() - 60 || intInvaderX < 0){
intInvaderY += 40;
invaderXAmount *= -1;
}
}
repaint();
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == 37){
shipMoveRight = true;
}
else if (key == 39){
shipMoveLeft = true;
}
else if (key == 32){
if(bulletActive == false){
intBulletX = intPosX;
intBulletY = intPosY;
}
bulletMove = true;
bulletActive = true;
}
}
public void keyReleased(KeyEvent e)
{
shipMoveLeft = false;
shipMoveRight = false;
}
public void keyTyped(KeyEvent e)
{
}
public void paint(Graphics gr)
{
super.paint(gr);
gr.setColor(Color.red);
gr.fillOval(intBulletX, intBulletY, 10, 25);
carImage.paintIcon(this,gr, intPosX, intPosY); //Draw image in new spot
invaderImage.paintIcon(this,gr, intInvaderX, intInvaderY);
}
}
So there are a number of issues which jump out immediately...
Applets are a dead end, most browsers will actively block them and/or have dropped support for the plugin
You're adding a JPanel to the applet, but overriding the applet's paint method, because of the way painting can work, the panel can be painted independently of the applet, causing it to paint over whatever you might have painted
You don't need multiple timers, you just need to have better delta values (smaller been faster)
KeyListener is a poor choice for detecting keyboard input, it's rather low level and has focus related issues which are easily overcome by using the Key Bindings API
I'd start by having a look at Performing Custom Painting, Painting in AWT and Swing and How to Use Key Bindings for more details.
So how would you start fixing it? Start by using a JPanel as you basic container, override it's paintComponent and place all your paint logic here.
Use a single Timer to manage the updates
There are any number of approaches you can take, but I'd start with defining some contracts that define what can go on in the game
public interface GameSpace extends ImageObserver {
public Dimension getGameSpace();
public boolean hasInput(Input input);
}
public interface Entity {
public void paint(GameSpace gameSpace, Graphics2D g2d);
public boolean update(GameSpace gameSpace);
public Rectangle getBounds();
}
public abstract class AbstractEntity implements Entity {
private int x;
private int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
protected abstract int getWidth();
protected abstract int getHeight();
public Rectangle getBounds() {
return new Rectangle(getX(), getY(), getWidth(), getHeight());
}
}
public abstract class AbstractImageEntity extends AbstractEntity {
protected abstract BufferedImage getImage();
#Override
protected int getWidth() {
return getImage().getWidth();
}
#Override
protected int getHeight() {
return getImage().getHeight();
}
}
This separates some of management of key elements, allowing for a more flexible design. You might have a lot more entities, one's which could move, ones which could not, some which are painted, some which are not, but all which provide support for the core engine to get work done.
Once you have that you can start defining some core entities you need
public class ShipEntity extends AbstractImageEntity {
private BufferedImage ship;
public ShipEntity(GameSpace gameSpace) throws IOException {
ship = ImageIO.read(getClass().getResource("/resources/ship.png"));
setY(gameSpace.getGameSpace().height - getBounds().height);
setX((gameSpace.getGameSpace().width - getBounds().width) / 2);
}
#Override
public BufferedImage getImage() {
return ship;
}
#Override
public void paint(GameSpace gameSpace, Graphics2D g2d) {
g2d.drawImage(ship, getX(), getY(), gameSpace);
}
#Override
public boolean update(GameSpace gameSpace) {
int x = getX();
if (gameSpace.hasInput(Input.LEFT)) {
x -= 2;
}
if (gameSpace.hasInput(Input.RIGHT)) {
x += 2;
}
if (x < 0) {
x = 0;
} else if (x + getWidth() > gameSpace.getGameSpace().width) {
x = gameSpace.getGameSpace().width - getWidth();
}
setX(x);
return true;
}
}
public class InvaderEntity extends AbstractImageEntity {
private BufferedImage invader;
public InvaderEntity() throws IOException {
invader = ImageIO.read(getClass().getResource("/resources/Invader.png"));
}
#Override
protected BufferedImage getImage() {
return invader;
}
#Override
public void paint(GameSpace gameSpace, Graphics2D g2d) {
g2d.drawImage(invader, getX(), getY(), gameSpace);
}
#Override
public boolean update(GameSpace gameSpace) {
return true;
}
}
public class ProjectileEntity extends AbstractEntity {
private int delta;
public ProjectileEntity(int delta) {
this.delta = delta;
}
#Override
protected int getWidth() {
return 10;
}
#Override
protected int getHeight() {
return 10;
}
#Override
public void paint(GameSpace gameSpace, Graphics2D g2d) {
g2d.setColor(Color.RED);
int width = getWidth();
int height = getHeight();
g2d.fillOval(getX() - width / 2, getY() - height / 2, width, height);
}
#Override
public boolean update(GameSpace gameSpace) {
int y = getY() + delta;
setY(getY() + delta);
return y + getHeight() >= 0 && y + getHeight() <= gameSpace.getGameSpace().height;
}
}
Basically, they contain the logic required for getting their jobs done.
Finally, you need to setup the actual game UI
public class GamePane extends JPanel implements GameSpace {
private Set<Input> inputs;
private Entity playerEntity;
private List<Entity> projectileEntities;
private List<Entity> invaderEntities;
private long timeOfLastProjectile = -1;
public GamePane() throws IOException {
setBackground(Color.BLACK);
inputs = new HashSet<>(2);
playerEntity = new ShipEntity(this);
projectileEntities = new ArrayList<>(25);
invaderEntities = new ArrayList<>(25);
InvaderEntity invader = new InvaderEntity();
invader.setX((getGameSpace().width - invader.getBounds().width) / 2);
invader.setY((getGameSpace().height - invader.getBounds().height) / 2);
invaderEntities.add(invader);
addKeyBinding(Input.LEFT, "left", KeyEvent.VK_LEFT);
addKeyBinding(Input.RIGHT, "right", KeyEvent.VK_RIGHT);
addKeyBinding(Input.SPACE, "space", KeyEvent.VK_SPACE);
Timer timer = new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateState();
processCollisions();
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 800);
}
protected void updateState() {
playerEntity.update(this);
if (hasInput(Input.SPACE)) {
long time = System.currentTimeMillis() - timeOfLastProjectile;
if (time < 0 || time > 1000) {
timeOfLastProjectile = System.currentTimeMillis();
Rectangle bounds = playerEntity.getBounds();
ProjectileEntity projectile = new ProjectileEntity(-1);
int x = bounds.x + ((bounds.width - projectile.getWidth()) / 2);
int y = bounds.y - projectile.getHeight();
projectile.setX(x);
projectile.setY(y);
projectileEntities.add(projectile);
}
}
for (Entity entity : invaderEntities) {
entity.update(this);
}
List<Entity> outOfBounds = new ArrayList<>(25);
for (Entity entity : projectileEntities) {
if (!entity.update(this)) {
outOfBounds.add(entity);
}
}
projectileEntities.removeAll(outOfBounds);
}
protected void processCollisions() {
Set<Entity> hitInvaders = new HashSet<>(25);
Set<Entity> hitProjectiles = new HashSet<>(25);
for (Entity invader : invaderEntities) {
for (Entity projectile : projectileEntities) {
if (projectile.getBounds().intersects(invader.getBounds())) {
// Maybe lots of cool explosiions
hitInvaders.add(invader);
hitProjectiles.add(projectile);
}
}
}
invaderEntities.removeAll(hitInvaders);
projectileEntities.removeAll(hitProjectiles);
}
protected void addKeyBinding(Input input, String name, int virtualKey) {
ActionMap am = getActionMap();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(virtualKey, 0, false), name + ".pressed");
im.put(KeyStroke.getKeyStroke(virtualKey, 0, true), name + ".released");
am.put(name + ".pressed", new KeyAction(inputs, input, true));
am.put(name + ".released", new KeyAction(inputs, input, false));
}
#Override
public Dimension getGameSpace() {
return getPreferredSize();
}
#Override
public boolean hasInput(Input input) {
return inputs.contains(input);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
playerEntity.paint(this, g2d);
g2d.dispose();
for (Entity entity : invaderEntities) {
g2d = (Graphics2D) g.create();
entity.paint(this, g2d);
g2d.dispose();
}
for (Entity entity : projectileEntities) {
g2d = (Graphics2D) g.create();
entity.paint(this, g2d);
g2d.dispose();
}
}
}
public class KeyAction extends AbstractAction {
private Input input;
private Set<Input> inputs;
private boolean pressed;
public KeyAction(Set<Input> inputs, Input input, boolean pressed) {
this.input = input;
this.inputs = inputs;
this.pressed = pressed;
}
#Override
public void actionPerformed(ActionEvent e) {
if (pressed) {
inputs.add(input);
} else {
inputs.remove(input);
}
}
}
Now you could go a little further and generate an "engine" class which controls the entities and performs all the required updating, but I'm lazy ;)
That's a really rough idea of some the basic concepts you need to develop to be able to move forward, hope it helps
I'm new to Java graphics and threads, and I'm trying to make a game (specifically, Pong). The idea is that two people can play on the same keyboard (i.e. there are two paddles that are controlled through different keys). Currently, both players can't move their paddle at the same time.
Is there a solution to this? Are separate threads the answer?
If possible, I'd like the paddles to be able to move (at least seemingly) at the same time.
Update: It seems like using a Set<Integer> to store pressed keys is the best option. I've done that (and it works), but I'm wondering if any of this code is not on the Event Dispatching Thread (EDT) and if I need to use SwingUtilities.invokeLater();. Here's the necessary code:
private Set<Integer> keysDown = Collections.synchronizedSet(new HashSet<Integer>());
public void keyPressed(KeyEvent e)
{
keysDown.add(e.getKeyCode());
}
public void keyReleased(KeyEvent e)
{
keysDown.remove(e.getKeyCode());
}
public void updatePaddlePositions()
{
if (keysDown.contains(KeyEvent.VK_W))
paddleOne.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_S))
paddleOne.move(PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_UP))
paddleTwo.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_DOWN))
paddleTwo.move(PADDLE_MOVE_INCREMENT);
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
System.out.println("You Interrupted the game!");
}
canvas.repaint();
}
Here's the paintComponent method of the canvas object:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
paddleOne.paint(g);
paddleTwo.paint(g);
updatePaddlePositions(); // Does this need to be SwingUtilities.invokeLater(this)?
// And should updatePaddlePositions() be run() as a result?
}
And here's the paint method of the paddleOne and paddleTwo objects:
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
}
Feel free to comment on my design if anything pops out as "bad" to you. Lastly, what does Collections.synchronizedSet(new HashSet<Integer>()) mean/do?
Update #2: It seems like key bindings are the way to go (even though they take more code, in this case). What make key bindings better? Is it that they work separately from everything else (and don't need window focus like key listeners)?
Also, I understand that HashSet<Integer> is just a subclass of Set<Integer>, but what is the purpose of Collections.synchronizedSet(...)? I'm assuming it has to do with threads, but I don't know why it's needed in this program (if it is at all).
First off, use Swing KeyBindings Also I see no real need for multi-threadung unless you want your game multi-threaded.
To clarify the problem is you need to be able for 2 players to press different keys?
If so:
Solution:
Simply use booleans to flag whether or not a key is pressed down, you would than of course have to reset the flag when the key is released.
In your game logic you would check the states if the booleans and act appropriately.
See my below example (both paddles can move independently using W and S and UP and DOWN keys):
public class GameLogic {
public GameLogic() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Game Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create the gamepanel
final GamePanel gp = new GamePanel(600, 500);
//create panel to hold buttons to start pause and stop the game
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
final JButton startButton = new JButton("Start");
final JButton pauseButton = new JButton("Pause");
final JButton stopButton = new JButton("Stop");
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
//add listeners to buttons (most of the actions - excuse the pun - takes palce here :)
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//clear enitites currently in array
gp.clearEntities();
ArrayList<BufferedImage> ballEntityImages = new ArrayList<>();
ArrayList<Long> ballEntityTimings = new ArrayList<>();
ballEntityImages.add(createColouredImage("white", 50, 50, true));
ballEntityTimings.add(500l);
Entity ballEntity = new Entity(gp.getWidth() / 2, gp.getHeight() / 2, ballEntityImages, ballEntityTimings);
ballEntity.RIGHT = true;
//create images for entities
ArrayList<BufferedImage> advEntityImages = new ArrayList<>();
ArrayList<Long> advEntityTimings = new ArrayList<>();
advEntityImages.add(createColouredImage("orange", 10, 100, false));
advEntityTimings.add(500l);
advEntityImages.add(createColouredImage("blue", 10, 100, false));
advEntityTimings.add(500l);
//create entities
AdvancedSpritesEntity player1Entity = new AdvancedSpritesEntity(0, 100, advEntityImages, advEntityTimings);
ArrayList<BufferedImage> entityImages = new ArrayList<>();
ArrayList<Long> entityTimings = new ArrayList<>();
entityImages.add(createColouredImage("red", 10, 100, false));
entityTimings.add(500l);//as its the only image it doesnt really matter what time we put we could use 0l
//entityImages.add(createColouredImage("magenta", 100, 100));
//entityTimings.add(500l);
Entity player2Entity = new Entity(gp.getWidth() - 10, 200, entityImages, entityTimings);
gp.addEntity(player1Entity);
gp.addEntity(player2Entity);//just a standing still Entity for testing
gp.addEntity(ballEntity);//just a standing still Entity for testing
//create Keybingings for gamepanel
GameKeyBindings gameKeyBindings = new GameKeyBindings(gp, player1Entity, player2Entity);
GamePanel.running.set(true);
//start the game loop which will repaint the screen
runGameLoop(gp);
startButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
}
});
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
boolean b = GamePanel.paused.get();
GamePanel.paused.set(!b);//set it to the opposite of what it was i.e paused to unpaused and vice versa
if (pauseButton.getText().equals("Pause")) {
pauseButton.setText("Un-pause");
} else {
pauseButton.setText("Pause");
}
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
GamePanel.running.set(false);
GamePanel.paused.set(false);
/* if we want enitites to be cleared and a blank panel shown
gp.clearEntities();
gp.repaint();
*/
if (!pauseButton.getText().equals("Pause")) {
pauseButton.setText("Pause");
}
startButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
}
});
//add buttons to panel
buttonPanel.add(startButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
//add gamepanel to jframe and button panel
frame.add(gp);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//Simply used for testing (to simulate sprites) can create different colored images
public static BufferedImage createColouredImage(String color, int w, int h, boolean circular) {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
switch (color.toLowerCase()) {
case "green":
g2.setColor(Color.GREEN);
break;
case "magenta":
g2.setColor(Color.MAGENTA);
break;
case "red":
g2.setColor(Color.RED);
break;
case "yellow":
g2.setColor(Color.YELLOW);
break;
case "blue":
g2.setColor(Color.BLUE);
break;
case "orange":
g2.setColor(Color.ORANGE);
break;
case "cyan":
g2.setColor(Color.CYAN);
break;
case "gray":
g2.setColor(Color.GRAY);
break;
default:
g2.setColor(Color.WHITE);
break;
}
if (!circular) {
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
} else {
g2.fillOval(0, 0, img.getWidth(), img.getHeight());
}
g2.dispose();
return img;
}
//Starts a new thread and runs the game loop in it.
private void runGameLoop(final GamePanel gp) {
Thread loop = new Thread(new Runnable() {
#Override
public void run() {
gp.gameLoop();
}
});
loop.start();
}
//Code starts here
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {//attempt to set look and feel to nimbus Java 7 and up
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
GameLogic gameLogic = new GameLogic();
}
});
}
}
class GameKeyBindings {
public GameKeyBindings(JComponent gp, final Entity entity, final Entity entity2) {
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "W pressed");
gp.getActionMap().put("W pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "W released");
gp.getActionMap().put("W released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.UP = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "S pressed");
gp.getActionMap().put("S pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "S released");
gp.getActionMap().put("S released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down pressed");
gp.getActionMap().put("down pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down released");
gp.getActionMap().put("down released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.DOWN = false;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up pressed");
gp.getActionMap().put("up pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = true;
}
});
gp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up released");
gp.getActionMap().put("up released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
entity2.UP = false;
}
});
}
}
class AdvancedSpritesEntity extends Entity {
public AdvancedSpritesEntity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(x, y, images, timings);
}
void setAnimation(ArrayList<BufferedImage> images, ArrayList<Long> timings) {
reset();//reset variables of animator class
setFrames(images, timings);//set new frames for animation
}
}
class Entity extends Animator {
private int speed = 5;
public boolean UP = false, DOWN = false, LEFT = false, RIGHT = false, visible;
private Rectangle2D.Double rect;
public Entity(int x, int y, ArrayList<BufferedImage> images, ArrayList<Long> timings) {
super(images, timings);
UP = false;
DOWN = false;
LEFT = false;
RIGHT = false;
visible = true;
rect = new Rectangle2D.Double(x, y, getCurrentImage().getWidth(), getCurrentImage().getHeight());
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public HashSet<String> getMask(Entity e) {
HashSet<String> mask = new HashSet<>();
int pixel, a;
BufferedImage bi = e.getCurrentImage();//gets the current image being shown
for (int i = 0; i < bi.getWidth(); i++) { // for every (x,y) component in the given box,
for (int j = 0; j < bi.getHeight(); j++) {
pixel = bi.getRGB(i, j); // get the RGB value of the pixel
a = (pixel >> 24) & 0xff;
if (a != 0) { // if the alpha is not 0, it must be something other than transparent
mask.add((e.getX() + i) + "," + (e.getY() - j)); // add the absolute x and absolute y coordinates to our set
}
}
}
return mask; //return our set
}
// Returns true if there is a collision between object a and object b
public boolean checkPerPixelCollision(Entity b) {
// This method detects to see if the images overlap at all. If they do, collision is possible
int ax1 = (int) getX();
int ay1 = (int) getY();
int ax2 = ax1 + (int) getWidth();
int ay2 = ay1 + (int) getHeight();
int bx1 = (int) b.getX();
int by1 = (int) b.getY();
int bx2 = bx1 + (int) b.getWidth();
int by2 = by1 + (int) b.getHeight();
if (by2 < ay1 || ay2 < by1 || bx2 < ax1 || ax2 < bx1) {
return false; // Collision is impossible.
} else { // Collision is possible.
// get the masks for both images
HashSet<String> maskPlayer1 = getMask(this);
HashSet<String> maskPlayer2 = getMask(b);
maskPlayer1.retainAll(maskPlayer2); // Check to see if any pixels in maskPlayer2 are the same as those in maskPlayer1
if (maskPlayer1.size() > 0) { // if so, than there exists at least one pixel that is the same in both images, thus
return true;
}
}
return false;
}
public void move() {
if (UP) {
rect.y -= speed;
}
if (DOWN) {
rect.y += speed;
}
if (LEFT) {
rect.x -= speed;
}
if (RIGHT) {
rect.x += speed;
}
}
#Override
public void update(long elapsedTime) {
super.update(elapsedTime);
getWidth();//set the rectangles height accordingly after image update
getHeight();//set rectangles height accordingle after update
}
public boolean intersects(Entity e) {
return rect.intersects(e.rect);
}
public double getX() {
return rect.x;
}
public double getY() {
return rect.y;
}
public double getWidth() {
if (getCurrentImage() == null) {//there might be no image (which is unwanted ofcourse but we must not get NPE so we check for null and return 0
return rect.width = 0;
}
return rect.width = getCurrentImage().getWidth();
}
public double getHeight() {
if (getCurrentImage() == null) {
return rect.height = 0;
}
return rect.height = getCurrentImage().getHeight();
}
}
class Animator {
private ArrayList<BufferedImage> frames;
private ArrayList<Long> timings;
private int currIndex;
private long animationTime;
private long totalAnimationDuration;
private AtomicBoolean done;//used to keep track if a single set of frames/ an animtion has finished its loop
public Animator(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
currIndex = 0;
animationTime = 0;
totalAnimationDuration = 0;
done = new AtomicBoolean(false);
this.frames = new ArrayList<>();
this.timings = new ArrayList<>();
setFrames(frames, timings);
}
public boolean isDone() {
return done.get();
}
public void reset() {
totalAnimationDuration = 0;
done.getAndSet(false);
}
public void update(long elapsedTime) {
if (frames.size() > 1) {
animationTime += elapsedTime;
if (animationTime >= totalAnimationDuration) {
animationTime = animationTime % totalAnimationDuration;
currIndex = 0;
done.getAndSet(true);
}
while (animationTime > timings.get(currIndex)) {
currIndex++;
}
}
}
public BufferedImage getCurrentImage() {
if (frames.isEmpty()) {
return null;
} else {
try {
return frames.get(currIndex);
} catch (Exception ex) {//images might have been altered so we reset the index and return first image of the new frames/animation
currIndex = 0;
return frames.get(currIndex);
}
}
}
public void setFrames(ArrayList<BufferedImage> frames, ArrayList< Long> timings) {
if (frames == null || timings == null) {//so that constructor super(null,null) cause this to throw NullPointerException
return;
}
this.frames = frames;
this.timings.clear();
for (long animTime : timings) {
totalAnimationDuration += animTime;
this.timings.add(totalAnimationDuration);
}
}
}
class GamePanel extends JPanel {
private final static RenderingHints textRenderHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
private final static RenderingHints imageRenderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
private final static RenderingHints colorRenderHints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
private final static RenderingHints interpolationRenderHints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
private final static RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
public static AtomicBoolean running = new AtomicBoolean(false), paused = new AtomicBoolean(false);
private int width, height, frameCount = 0, fps = 0;
private ArrayList<Entity> entities = new ArrayList<>();
private final Random random = new Random();
public GamePanel(int w, int h) {
super(true);//make sure double buffering is enabled
setIgnoreRepaint(true);//mustnt repaint itself the gameloop will do that
width = w;
height = h;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
public void addEntity(Entity e) {
entities.add(e);
}
void clearEntities() {
entities.clear();
}
//Only run this in another Thread!
public void gameLoop() {
//This value would probably be stored elsewhere.
final double GAME_HERTZ = 30.0;
//Calculate how many ns each frame should take for our target game hertz.
final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
//At the very most we will update the game this many times before a new render.
//If you're worried about visual hitches more than perfect timing, set this to 1.
final int MAX_UPDATES_BEFORE_RENDER = 5;
//We will need the last update time.
double lastUpdateTime = System.nanoTime();
//Store the last time we rendered.
double lastRenderTime = System.nanoTime();
//If we are able to get as high as this FPS, don't render again.
final double TARGET_FPS = 60;
final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;
//Simple way of finding FPS.
int lastSecondTime = (int) (lastUpdateTime / 1000000000);
//store the time we started this will be used for updating map and charcter animations
long currTime = System.currentTimeMillis();
while (running.get()) {
if (!paused.get()) {
double now = System.nanoTime();
long elapsedTime = System.currentTimeMillis() - currTime;
currTime += elapsedTime;
int updateCount = 0;
//Do as many game updates as we need to, potentially playing catchup.
while (now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER) {
updateGame(elapsedTime);//Update the entity movements and collision checks etc (all has to do with updating the games status i.e call move() on Enitites)
lastUpdateTime += TIME_BETWEEN_UPDATES;
updateCount++;
}
//If for some reason an update takes forever, we don't want to do an insane number of catchups.
//If you were doing some sort of game that needed to keep EXACT time, you would get rid of this.
if (now - lastUpdateTime > TIME_BETWEEN_UPDATES) {
lastUpdateTime = now - TIME_BETWEEN_UPDATES;
}
drawGame();//draw the game by invokeing repaint (which will call paintComponent) on this JPanel
lastRenderTime = now;
//Update the frames we got.
int thisSecond = (int) (lastUpdateTime / 1000000000);
if (thisSecond > lastSecondTime) {
//System.out.println("NEW SECOND " + thisSecond + " " + frameCount);
fps = frameCount;
frameCount = 0;
lastSecondTime = thisSecond;
}
//Yield until it has been at least the target time between renders. This saves the CPU from hogging.
while (now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES) {
//allow the threading system to play threads that are waiting to run.
Thread.yield();
//This stops the app from consuming all your CPU. It makes this slightly less accurate, but is worth it.
//You can remove this line and it will still work (better), your CPU just climbs on certain OSes.
//FYI on some OS's this can cause pretty bad stuttering. Scroll down and have a look at different peoples' solutions to this.
//On my OS(Windows 7 x64 intel i3) it does not allow for time to make enityt etc move thus all stands still
try {
Thread.sleep(1);
} catch (Exception e) {
}
now = System.nanoTime();
}
}
}
fps = 0;//no more running set fps to 0
}
private void drawGame() {
//Both revalidate and repaint are thread-safe — you need not invoke them from the event-dispatching thread. http://docs.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html
repaint();
}
private void updateGame(long elapsedTime) {
updateEntityMovements(elapsedTime);
checkForCollisions();
}
private void checkForCollisions() {
if (entities.get(0).intersects(entities.get(2)) || entities.get(1).intersects(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
} /*
//This is best used when images have transparent and non-transparent pixels (only detects pixel collisions of non-transparent pixels)
if (entities.get(0).checkPerPixelCollision(entities.get(2)) | entities.get(1).checkPerPixelCollision(entities.get(2))) {
if (entities.get(2).LEFT) {
entities.get(2).RIGHT = true;
entities.get(2).LEFT = false;
} else {
entities.get(2).LEFT = true;
entities.get(2).RIGHT = false;
}
System.out.println("Intersecting");
}
*/
}
private void updateEntityMovements(long elapsedTime) {
for (Entity e : entities) {
e.update(elapsedTime);
e.move();
}
}
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
applyRenderHints(g2d);
drawBackground(g2d);
drawEntitiesToScreen(g2d);
drawFpsCounter(g2d);
frameCount++;
}
public static void applyRenderHints(Graphics2D g2d) {
g2d.setRenderingHints(textRenderHints);
g2d.setRenderingHints(imageRenderHints);
g2d.setRenderingHints(colorRenderHints);
g2d.setRenderingHints(interpolationRenderHints);
g2d.setRenderingHints(renderHints);
}
private void drawEntitiesToScreen(Graphics2D g2d) {
for (Entity e : entities) {
if (e.isVisible()) {
g2d.drawImage(e.getCurrentImage(), (int) e.getX(), (int) e.getY(), null);
}
}
}
private void drawFpsCounter(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.drawString("FPS: " + fps, 5, 10);
}
private void drawBackground(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
//thanks to trashgod for lovely testing background :) http://stackoverflow.com/questions/3256269/jtextfields-on-top-of-active-drawing-on-jpanel-threading-problems/3256941#3256941
g2d.setColor(Color.BLACK);
for (int i = 0; i < 128; i++) {
g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));//random color
g2d.drawLine(getWidth() / 2, getHeight() / 2, random.nextInt(getWidth()), random.nextInt(getHeight()));
}
}
}
This may be a legitimate use case for the low-level access afforded to a KeyListener. See How to Write a Key Listener and KeyEventDemo; don't forget to requestFocusInWindow(). Also consider offering keyboard control for one player and mouse control for the other.
Addendum: #David Kroukamp has adduced an appealing counter-example using key bindings. For reference, the example cited here illustrates one approach to managing key preferences.
I am making a JFrame holding several images that refresh using repaint(). The problem, however, was that the more images I added (or as the area that was being rendered increased) the framerate drastically decreased.
I was initially attempting to reduce the lag that Swing's unpredictable Timer experiences, but was unsuccessful. This time, I tried to call
repaint()
every 10 milliseconds based on system time. (To bypass the timer, desktop.screenPaint.drawWindow(); is called instead of repaint())
while(true)
{
long starttime = System.currentTimeMillis();
while(System.currentTimeMillis()-starttime < 10)
{
}
desktop.screenPaint.drawWindow();
desktop2.screenPaint.drawWindow();
}
Each "desktop" is just one of the draggable windows that you see if you run the code below. I noticed that when only "desktop" is added to "frame," there is no flickering. However, when "desktop2" is also added, flickering does not go away until the time until each refresh is set to 20 or more milliseconds. It is extremely strange, because when I was still using the timer, even thought the wait was set to 10 milliseconds, the framerate would lower to a frame every 20 milliseconds! I tested a little and noticed a trend: you will get flickering until the wait time to the amount of time that the 10 millisecond timer lagged behind. My question: Why is this happening? And is there any way to prevent the flickering, other than going back to the timer?
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.SwingUtilities.*;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
import java.io.File;
import java.io.IOException;
public class Display extends JPanel
{
public static int width, height;
public static JFrame frame = new JFrame("");
private static int rh = 10;
public static Display desktop = new Display();
public static Display desktop2 = new Display();
public static void main(String[] args)
{
Dimension screen = new Dimension();
screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
width = (int)screen.getWidth();
height = (int)screen.getHeight();
frame.setLayout(null);
frame.setLocation(0, 0);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
desktop.setBounds(0, 0, 620, 500+rh);
desktop2.setBounds(1000, 200, 620, 500+rh);
frame.add(desktop);
frame.add(desktop2);
frame.setUndecorated(true);
frame.setSize(width, height);
frame.setVisible(true);
while(true)
{
long starttime = System.currentTimeMillis();
while(System.currentTimeMillis()-starttime < 10)
{
}
desktop.screenPaint.drawWindow();
//desktop2.screenPaint.drawWindow();
}
}
private BufferedImage image;
private Graphics2D g;
public Listener screenPaint = new Listener();
private Display identify;
public Display()
{
identify = this;
image = new BufferedImage(620, 500+rh, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D)image.getGraphics();
Timer timer = new Timer(1, screenPaint);
timer.start();
addMouseListener(new mMouse());
addMouseWheelListener(new wWheel());
setFocusable(true);
}
private BufferedImage toCompatibleImage(BufferedImage image)
{
GraphicsConfiguration gfx_config = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
if (image.getColorModel().equals(gfx_config.getColorModel()))
return image;
BufferedImage new_image = gfx_config.createCompatibleImage(
image.getWidth(), image.getHeight(), image.getTransparency());
}
public void paint(Graphics view)
{
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
view.drawImage(toCompatibleImage(image), 0, 0, 620, 500+rh, null);
view.dispose();
}
private class Listener implements ActionListener
{
int y = 0;
int wy = 0;
int b = 500;
int c = 1500;
int iy = (int)(wy/(c/(double)b));
int a = -1;
int i = -1;
int j = -1;
boolean d = false;
boolean u = false;
int f = 0;
public void moveY(int sy)
{
f += sy;
}
public void actionPerformed(ActionEvent e)
{
//drawWindow();
}
public void drawWindow()
{
int lx = (int)(identify.getLocation().getX());
int ly = (int)(identify.getLocation().getY());
g.setColor(Color.white);
g.fillRect(0, 0, 620, 500+rh);
g.drawImage(new ImageIcon("image.png").getImage(), 0, wy+rh, 610, c, null);
if(c > b)
{
if(d || Mouse.withinRect(610+lx, (int)(-wy/(c/(double)b))+rh+ly, 10, (int)Math.ceil(Math.pow(b, 2)/(double)c)))
{
if(Mouse.pressLeft())
{
if(!d)d = true;
if(a == -1)a = Mouse.y()-(int)(-wy/(c/(double)b));
y = (int)((Mouse.y()-a)*(c/(double)b));
f = y;
g.setColor(Color.black);
}
else
{
if(d)d = false;
if(a != -1)a = -1;
g.setColor(new Color(60, 60, 60));
}
}
else
{
g.setColor(Color.gray);
if(a != -1)a = -1;
}
if(y == f){}
else if(y < f)
{
y += (int)((f-y)*0.1);
if(y < f)y++;
}
else
{
y -= (int)((y-f)*0.1);
if(y > f)y--;
}
if(y < 0)
{
y = 0;
f = 0;
}
else if(y > c-b)
{
y = c-b;
f = y;
}
wy = -y;
if(u || Mouse.withinRect(lx, ly, 620, 10))
{
if(Mouse.pressLeft())
{
if(!u)u = true;
if(i == -1)i = Mouse.x()-lx;
if(j == -1)j = Mouse.y()-ly;
identify.setLocation(Mouse.x()-i, Mouse.y()-j);
}
else
{
if(u)u = false;
if(i != -1)i = -1;
if(j != -1)j = -1;
}
}
else
{
if(u)u = false;
if(i != -1)i = -1;
if(j != -1)j = -1;
}
int scrollBarLength = (int)Math.ceil(Math.pow(b, 2)/(double)c);
g.fillRect(610, (int)(-wy/(c/(double)b))+rh, 10, scrollBarLength);
}
else
{
g.setColor(new Color(200, 200, 200));
g.fillRect(610, rh, 10, b);
}
g.setColor(new Color(50, 50, 50));
g.fillRect(0, 0, 620, rh);
if(identify == desktop)
repaint();
else if(false)
{}
}
}
}
public static boolean LMPress, LMRelease = false;
public static boolean LMRight, LMLeft = false;
private class mMouse extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
LMPress = true; LMRelease = false;
if(SwingUtilities.isRightMouseButton(e))
{
LMRight = true;
LMLeft = false;
}
else if(SwingUtilities.isLeftMouseButton(e))
{
LMLeft = true;
LMRight = false;
}
}
public void mouseReleased(MouseEvent e)
{
LMRelease = true; LMPress = false;
if(SwingUtilities.isRightMouseButton(e))
{
LMRight = true;
LMLeft = false;
}
else if(SwingUtilities.isLeftMouseButton(e))
{
LMLeft = true;
LMRight = false;
}
}
}
private class wWheel implements MouseWheelListener
{
public void mouseWheelMoved(MouseWheelEvent e)
{
int notches = e.getWheelRotation();
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {}
e.getScrollAmount();
screenPaint.moveY(e.getUnitsToScroll()*60); //desired pixel jump: 120
}
}
}
Mouse class:
import java.awt.*;
import java.awt.event.*;
public class Mouse {
public static int x() {
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
return (int) b.getX();
}
public static int y() {
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
return (int) b.getY();
}
public static boolean withinRect(int x, int y, int w, int h) {
if (x() >= x && x() < x + w && y() >= y && y() < y + h) return true;
else return false;
}
public static boolean press() {
return Display.LMPress;
}
public static boolean release() {
return Display.LMRelease;
}
public static boolean pressLeft() {
if (Display.LMPress && Display.LMLeft)
return true;
else return false;
}
public static boolean releaseLeft() {
if (Display.LMRelease && Display.LMLeft)
return true;
else return false;
}
public static boolean pressRight() {
if (Display.LMPress && Display.LMRight)
return true;
else return false;
}
public static boolean releaseRight() {
if (Display.LMRelease && Display.LMRight)
return true;
else return false;
}
}
Updating the view at 1 kHz is unrealistic; instead, consider the alternatives cited here. See this AnimationTest for an example of self-timing to determine your animation budget.
Addendum: The while(true) loop at the top is running at 100 Hz.
The available resolution of System.currentTimeMillis() may vary by platform.
Addendum: I am reopening this question because I was not able to fix it. Any more help?
Absent a Minimal, Complete, Tested and Readable Example, it's hard to say. You appear to be overriding paint(); was noted in Painting in AWT and Swing: The Paint Methods, "Swing programs should override paintComponent()." Moreover, you need to invoke super.paintComponent(), as shown here, to avoid visual artifacts.
I'm trying to create a custom extension of BasicSliderUI. I'm just trying to make the thumb a circle (note I'm in the Windows L&F). I've created a very simple implementation that just calls g.drawOval, but whenever I drag it, it leaves a "trail" behind. Any ideas why this is?
thanks,
Jeff
You need to call repaint on the whole thing, you cant just draw the oval on top of it. Swing will by default only repaint what needs to be repainted, which usually isn't the whole control. When are you drawing the circle?
If you want to get rid of "trail" when you drag you should write your custom TrackListener and control trumb position related to mouse move.
Look at my implementation:
public class LightSliderUI extends BasicSliderUI{
private final Color rangeColor = Color.BLUE;
private final BasicStroke stroke = new BasicStroke(2f);
private transient boolean upperDragging;
public LightSliderUI(JSlider b) {
super(b);
}
public static ComponentUI createUI(JComponent c) {
return new LightSliderUI((JSlider)c);
}
#Override
protected void calculateThumbSize() {
super.calculateThumbSize();
thumbRect.setSize(thumbRect.width, thumbRect.height);
}
/** Creates a listener to handle track events in the specified slider.*/
#Override
protected TrackListener createTrackListener(JSlider slider) {
return new RangeTrackListener();
}
#Override
protected void calculateThumbLocation() {
// Call superclass method for lower thumb location.
super.calculateThumbLocation();
// Adjust upper value to snap to ticks if necessary.
if (slider.getSnapToTicks()) {
int upperValue = slider.getValue() + slider.getExtent();
int snappedValue = upperValue;
int majorTickSpacing = slider.getMajorTickSpacing();
int minorTickSpacing = slider.getMinorTickSpacing();
int tickSpacing = 0;
if (minorTickSpacing > 0) {
tickSpacing = minorTickSpacing;
} else if (majorTickSpacing > 0) {
tickSpacing = majorTickSpacing;
}
if (tickSpacing != 0) {
// If it's not on a tick, change the value
if ((upperValue - slider.getMinimum()) % tickSpacing != 0) {
float temp = (float)(upperValue - slider.getMinimum()) / (float)tickSpacing;
int whichTick = Math.round(temp);
snappedValue = slider.getMinimum() + (whichTick * tickSpacing);
}
if (snappedValue != upperValue) {
slider.setExtent(snappedValue - slider.getValue());
}
}
}
// Calculate upper thumb location. The thumb is centered over its
// value on the track.
if (slider.getOrientation() == JSlider.HORIZONTAL) {
int upperPosition = xPositionForValue(slider.getValue() + slider.getExtent());
thumbRect.x = upperPosition - (thumbRect.width / 2);
thumbRect.y = trackRect.y;
} else {
int upperPosition = yPositionForValue(slider.getValue() + slider.getExtent());
thumbRect.x = trackRect.x;
thumbRect.y = upperPosition - (thumbRect.height / 2);
}
slider.repaint();
}
/** Returns the size of a thumb.
* Parent method not use size from LaF
* #return size of trumb */
#Override
protected Dimension getThumbSize() {
return Dimensions.getSliderThumbSize();
}
private Shape createThumbShape(int width, int height) {
Ellipse2D shape = new Ellipse2D.Double(0, 0, width, height);
return shape;
}
#Override
public void paintTrack(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Stroke old = g2d.getStroke();
g2d.setStroke(stroke);
g2d.setPaint(Colors.TEXT_STEEL);
Color oldColor = Colors.TEXT_STEEL;
Rectangle trackBounds = trackRect;
if (slider.getOrientation() == SwingConstants.HORIZONTAL) {
g2d.drawLine(trackRect.x, trackRect.y + trackRect.height / 2,
trackRect.x + trackRect.width, trackRect.y + trackRect.height / 2);
int lowerX = thumbRect.width / 2;
int upperX = thumbRect.x + (thumbRect.width / 2);
int cy = (trackBounds.height / 2) - 2;
g2d.translate(trackBounds.x, trackBounds.y + cy);
g2d.setColor(rangeColor);
g2d.drawLine(lowerX - trackBounds.x, 2, upperX - trackBounds.x, 2);
g2d.translate(-trackBounds.x, -(trackBounds.y + cy));
g2d.setColor(oldColor);
}
g2d.setStroke(old);
}
/** Overrides superclass method to do nothing. Thumb painting is handled
* within the <code>paint()</code> method.*/
#Override
public void paintThumb(Graphics g) {
Rectangle knobBounds = thumbRect;
int w = knobBounds.width;
int h = knobBounds.height;
Graphics2D g2d = (Graphics2D) g.create();
Shape thumbShape = createThumbShape(w - 1, h - 1);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(knobBounds.x, knobBounds.y);
g2d.setColor(Color.WHITE);
g2d.fill(thumbShape);
g2d.setColor(Colors.BIOLIN_BLUE_TINT);
g2d.draw(thumbShape);
g2d.dispose();
}
/** Listener to handle model change events. This calculates the thumb
* locations and repaints the slider if the value change is not caused by dragging a thumb.*/
public class ChangeHandler implements ChangeListener {
#Override
public void stateChanged(ChangeEvent arg0) {
calculateThumbLocation();
slider.repaint();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JSlider slider = new JSlider(0, 100);
slider.setPaintTicks(true);
slider.setUI(new LightSliderUI(slider));
frame.add(slider);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
/** Listener to handle mouse movements in the slider track.*/
public class RangeTrackListener extends TrackListener {
#Override
public void mouseClicked(MouseEvent e) {
if (!slider.isEnabled()) {
return;
}
currentMouseX -= thumbRect.width / 2; // Because we want the mouse location correspond to middle of the "thumb", not left side of it.
moveUpperThumb();
}
public void mousePressed(MouseEvent e) {
if (!slider.isEnabled()) {
return;
}
currentMouseX = e.getX();
currentMouseY = e.getY();
if (slider.isRequestFocusEnabled()) {
slider.requestFocus();
}
boolean upperPressed = false;
if (slider.getMinimum() == slider.getValue()) {
if (thumbRect.contains(currentMouseX, currentMouseY)) {
upperPressed = true;
}
} else {
if (thumbRect.contains(currentMouseX, currentMouseY)) {
upperPressed = true;
}
}
if (upperPressed) {
switch (slider.getOrientation()) {
case JSlider.VERTICAL:
offset = currentMouseY - thumbRect.y;
break;
case JSlider.HORIZONTAL:
offset = currentMouseX - thumbRect.x;
break;
}
//upperThumbSelected = true;
upperDragging = true;
return;
}
upperDragging = false;
}
#Override
public void mouseReleased(MouseEvent e) {
upperDragging = false;
slider.setValueIsAdjusting(false);
super.mouseReleased(e);
}
#Override
public void mouseDragged(MouseEvent e) {
if (!slider.isEnabled()) {
return;
}
currentMouseX = e.getX();
currentMouseY = e.getY();
if (upperDragging) {
slider.setValueIsAdjusting(true);
moveUpperThumb();
}
}
#Override
public boolean shouldScroll(int direction) {
return false;
}
/** Moves the location of the upper thumb, and sets its corresponding value in the slider.*/
public void moveUpperThumb() {
int thumbMiddle = 0;
switch (slider.getOrientation()) {
case JSlider.HORIZONTAL:
int halfThumbWidth = thumbRect.width / 2;
int thumbLeft = currentMouseX - offset;
int trackLeft = trackRect.x;
int trackRight = trackRect.x + (trackRect.width - 1);
int hMax = xPositionForValue(slider.getMaximum() -
slider.getExtent());
if (drawInverted()) {
trackLeft = hMax;
}
else {
trackRight = hMax;
}
thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth);
thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth);
setThumbLocation(thumbLeft, thumbRect.y);//setThumbLocation
thumbMiddle = thumbLeft + halfThumbWidth;
slider.setValue(valueForXPosition(thumbMiddle));
break;
default:
return;
}
}
}
}