Java KeyPress is not being detected - java

When the code runs I get no errors. It runs all parts except for my keypress. Where something is going wrong.
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
// Inheriting the JFrame class
public class Main extends JFrame {
Scanner d = new Scanner(System.in);
//Defining the Frame
JFrame f;
char input;
int x = 250;
int y = 100;
//Constructor
Main()
{
ImageIcon p = new ImageIcon("Player.png");
JLabel b = new JLabel(p);
b.setBounds(x, y, 50, 50);
add(b);
System.out.println("started");
b.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("*Event Listener Run*");
input = e.getKeyChar();
if (input == 'w')
{
y-=50;
}
else if (input == 'a')
{
x-=50;
}
else if (input == 's')
{
y+=50;
}
else if (input == 'd')
{
x+=50;
}
System.out.println("Cords: "+x+","+y);
b.setBounds(x, y, 50, 50);
}
public void keyTyped(KeyEvent e){
}
public void keyReleased(KeyEvent e){
System.out.println("keyReleased");
}
});
//Set up Window
System.out.println("*setup window*");
setSize(800, 600);
setLayout(null);
setVisible(true);
System.out.println("*setup window done*");
}
public static void main(String[] args){
// Create the window
new Main();
}
}
I added error println's to see if some of the code isn't running, however it all is.

As #this_is_cat explained earlier, the listener needs to be on the JFrame and not on the JLabel.
Also, the use of setLayout(null) is not good practice, but was used here because we only have one component with which to work.
package keylistener1;
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
// Inheriting the JFrame class
public class KeyListener1 extends JFrame {
private static final String ICON_FILE_PATH = "btn_home.gif";
// Scanner d = new Scanner(System.in);
private JLabel label = new JLabel("image not found");
private JFrame jframe = new JFrame();
private int xpos = 250;
private int ypos = 250;
public KeyListener1() throws HeadlessException {
initFrame();
}
private JFrame initFrame() {
jframe.setLayout(null);
jframe.setPreferredSize(new Dimension(525, 525));
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
jframe.setTitle("Key Listener");
// set up image icon
Class cls = this.getClass();
try (InputStream imageSource = cls.getResourceAsStream(ICON_FILE_PATH)) {
BufferedImage bi = ImageIO.read(imageSource);
ImageIcon p = new ImageIcon(bi);
setLabel(new JLabel(p));
getLabel().setBounds(getXpos(), getYpos(), 50, 50);
} catch (IOException ex) {
Logger.getLogger(KeyListener1.class.getName()).log(Level.SEVERE, null, ex);
}
initKeyListener();
jframe.add(getLabel());
jframe.pack();
System.out.println("Starting coordinates: " + getXpos() + "," + getYpos());
return jframe;
}
private void initKeyListener() {
getJframe().addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("jf: " + e.getKeyChar());
char input = e.getKeyChar();
if (input == 'w') {
// ypos -= 50;
setYpos(getYpos() - 50);
} else if (input == 'a') {
// xpos -= 50;
setXpos(getXpos() - 50);
} else if (input == 's') {
// ypos += 50;
setYpos(getYpos() + 50);
} else if (input == 'd') {
// xpos += 50;
setXpos(getXpos() + 50);
}
System.out.println("New Coordinates: " + getXpos() + "," + getYpos());
getLabel().setBounds(getXpos(), getYpos(), 50, 50);
}
});
}
public JLabel getLabel() {
return label;
}
public void setLabel(JLabel label) {
this.label = label;
}
public int getXpos() {
return xpos;
}
public void setXpos(int xpos) {
this.xpos = xpos;
}
public int getYpos() {
return ypos;
}
public void setYpos(int ypos) {
this.ypos = ypos;
}
public JFrame getJframe() {
return jframe;
}
public void setJframe(JFrame jframe) {
this.jframe = jframe;
}
public static void main(String[] args) {
new KeyListener1();
}
}

Related

Can't implement draw(rectangle) within paintComponent

So I'm trying to implement implement a game where overtime the player is hit by an asteroid, they loose a life. all i want to do is create an array of square that removes one square overtime the player is hit. for some reason i keep getting a "cannot find symbol error" when i try to x.draw the rectangle in the paintComponent method, and I don't understand why. Can anyone explain this?
package lightrunner;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.Random;
import java.awt.geom.Area;
import java.util.ArrayList;
import javax.swing.JMenuBar;
import javax.swing.Timer;
import java.util.Iterator;
import java.awt.geom.Rectangle2D;
class LightRunner
{
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,520);
frame.setTitle("Light Runner");
frame.add(new GamePanel());
frame.setVisible(true);
}
public static class GamePanel extends JPanel
{
public java.util.List<Rectangle> lives;
Ship ship;
Asteroid asteroid;
Asteroid asteroid2;
Timer timer;
Graphics g;
// private final int MILLESECONDS_BETWEEN_FRAMES = 10;
Asteroid[] ast_array;
boolean isStar;
public GamePanel()
{
super();
setBackground(Color.black);
// menu();
initializeGameObjects();
addKeyListener(new ShipMover());
setFocusable(true);
}
public void initializeGameObjects()
{
ast_array = new Asteroid[8];
//asteroid = new Asteroid(250,250, "/Users/nicholascerillo/Desktop/asteroid.png");
// asteroid2 = new Asteroid(300,300, "/Users/nicholascerillo/Desktop/asteroid.png");
ship = new Ship(10, 164, "/Users/nicholascerillo/Desktop/ship.png");
timer = new Timer(10, new GameMotion());
//
for (int i = 0; i <= 7; i++)
{
Random rand = new Random();
int Astx = WIDTH + (i*200) + 200;
int Asty = rand.nextInt((600-0)) + 0;
// int star = rand.nextInt((10-0)) + 0;
ast_array[i] = new Asteroid(Astx,Asty);
}
lives = new ArrayList<Rectangle>();
lives.add(new Rectangle( 10, 10, 10, 10));
lives.add(new Rectangle( 10, 25, 10, 10));
lives.add(new Rectangle( 10, 30, 10, 10));
// GameMotion();
timer.start();
}
#Override
public void paintComponent(Graphics x)
{
//super();//paintComponent(x);
Graphics2D g2 = (Graphics2D)x;
ship.paint(g2);
g2.drawImage(ship.getShip(),ship.getX1(), ship.getY1(),this);
for(int r = 0; r < 7; r++)
{
g2.drawImage(ast_array[r].getImage(), ast_array[r].getX(), ast_array[r].getY(),null);
}
x.setColor(Color.RED);
for (Rectangle life : lives)
{
x.draw(life);
}
//asteroid.paint(g2);
}
private class GameMotion implements ActionListener
{
public GameMotion()
{
// light = new Timer(20,this);
}
public void actionPerformed(ActionEvent evt)
{
// light.start();
//checkBounds();
Iterator<Rectangle> it = lives.iterator();
// ship.BoundedY();
ship.move();
ast_array[0].moveAsteroid();
ast_array[1].moveAsteroid();
ast_array[2].moveAsteroid();
ast_array[3].moveAsteroid();
ast_array[4].moveAsteroid();
ast_array[5].moveAsteroid();
ast_array[6].moveAsteroid();
ast_array[7].moveAsteroid();
while(it.hasNext())
{
Rectangle life = it.next();
for(int p = 0; p < 7; p++)
{
ship.isHit(ast_array[p]);
if(ship.getHit())
{
it.remove();
}
}
}
repaint();
}
}
private class ShipMover implements KeyListener
{
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_RIGHT )
{
ship.setSpeedX(5);
}
else if (key == KeyEvent.VK_LEFT)
{
ship.setSpeedX(-5);
}
else if(key == KeyEvent.VK_UP /*&& (ship.BoundedY())*/){
ship.setSpeedY(-5);
}
else if(key == KeyEvent.VK_DOWN /*&& (ship.BoundedY())*/){
ship.setSpeedY(5);
}
}
public void keyReleased(KeyEvent evt) {
int key = evt.getKeyCode();
if ((key == KeyEvent.VK_LEFT) || (key == KeyEvent.VK_RIGHT) ) {
ship.setSpeedX(0);
}
else if((key == KeyEvent.VK_UP) || (key == KeyEvent.VK_DOWN))
{
ship.setSpeedY(0);
}
}
public void keyTyped(KeyEvent evt) {
}
}
}
}

How to change an image after a keyboard input in java?

I have the following code to show you:
public class Test extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this);
int x = 0, y = 0, velX = 0, velY = 0;
public Test()
{
tm.start(); //starts the timer
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paint(Graphics g)
{
super.paint(g);
ImageIcon s = new ImageIcon("C:\\Users\\Owner\\Pictures\\Stick.jpg");
s.paintIcon(this,g,x,y);
}
public void actionPerformed(ActionEvent e)
{
if (x < 0)
{
velX = 0;
x = 0;
}
if (x > 630)
{
velX = 0;
x = 630;
}
if(y < 0)
{
velY = 0;
y = 0;
}
if(y > 430)
{
velY = 0;
y = 430;
}
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode();
if (c == KeyEvent.VK_LEFT)
{
velX = -1;
velY = 0;
}
if(c == KeyEvent.VK_UP)
{
velX = 0;
velY = -1;
}
if(c == KeyEvent.VK_RIGHT)
{
velX = 1;
velY = 0;
}
if(c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 1;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
velX = 0;
velY = 0;
}
public static void main(String[] args)
{
Test t = new Test();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(700, 600);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
jf.setVisible(true);
}
My problem is I whenever the user holds the right arrow on the keyboard it changes an image, when the user lets go it goes back the the default image. Please tell me how to do that. I think it is a series of if statements in the Graphics class then calling them to the key input but I'm not quite sure. I am also using Eclipse. Thank You.
Override paintComponent instead of paint. See Performing Custom Painting and Painting in AWT and Swing for more details
Use the key bindings API instead of KeyListener, it will cause you less issues. See How to Use Key Bindings for more details
Essentially, you could just have a Image as a class instance field, which was painted by the paintComponent method. When the key was pressed, you would change the image to the "move image" and when it was released, change it back to the "default image"
Updated with example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface Mover {
public enum Direction {
LEFT, RIGHT, NONE;
}
public void setDirection(Direction direction);
public Direction getDirection();
}
public class TestPane extends JPanel implements Mover {
private BufferedImage left;
private BufferedImage right;
private BufferedImage stand;
private BufferedImage current;
private Direction direction = Direction.NONE;
private int xPos;
private int yPos;
public TestPane() {
try {
left = ImageIO.read(getClass().getResource("/Left.png"));
right = ImageIO.read(getClass().getResource("/Right.png"));
stand = ImageIO.read(getClass().getResource("/Stand.png"));
current = stand;
xPos = 100 - (current.getWidth() / 2);
yPos = 100 - (current.getHeight() / 2);
} catch (IOException exp) {
exp.printStackTrace();
}
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "move.left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), new MoveAction(this, Direction.LEFT));
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "stop.left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), new MoveAction(this, Direction.NONE));
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "move.right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), new MoveAction(this, Direction.RIGHT));
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "stop.right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), new MoveAction(this, Direction.NONE));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updatePosition();
repaint();
}
});
timer.start();
}
protected void bindKeyStrokeTo(int condition, String name, KeyStroke keyStroke, Action action) {
InputMap im = getInputMap(condition);
ActionMap am = getActionMap();
im.put(keyStroke, name);
am.put(name, action);
}
#Override
public Direction getDirection() {
return direction;
}
#Override
public void setDirection(Direction direction) {
this.direction = direction;
}
protected void updatePosition() {
switch (getDirection()) {
case LEFT:
current = left;
xPos -= 1;
break;
case RIGHT:
current = right;
xPos += 1;
break;
case NONE:
current = stand;
break;
}
if (xPos < 0) {
xPos = 0;
current = stand;
} else if (xPos + current.getWidth() > getWidth()) {
current = stand;
xPos = getWidth() - current.getWidth();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(current, xPos, yPos, this);
g2d.dispose();
}
}
public class MoveAction extends AbstractAction {
private Mover mover;
private Mover.Direction direction;
public MoveAction(Mover mover, Mover.Direction direction) {
this.mover = mover;
this.direction = direction;
}
#Override
public void actionPerformed(ActionEvent e) {
mover.setDirection(direction);
}
}
}

Java Massive Multiple Frame Instances Issue

sigh OK guys... There is going to be a painstaking amount of code here, but i'm going to do it anyway.
So basically, I have a custom made (well it's actually just a HEAVILY customized version of a JFrame) and am having major issues.
I have a background. (Fair enough, that's fine) THEN I have a Terminal frame that pops up and spits stuff out. This Terminal frame is based off another class named CustomFrame. I also have ANOTHER class called Notification, which is ALSO a frame class like Terminal ALSO based off Custom Frame.
In the beginning, background loads fine. Terminal loads fine. Calls method to show Notification window. And thats where the problem rises. The notification window won't show.
I have tried frame.setVisible(); frame.setSize(); frame.setLocation(); I have tried, EVERYTHING.
And if I don't show Terminal at all, it seems to spit it's code onto Notification instead, almost like there can only be ONE instance of the CustomFrame open AT ALL TIMES.
I hope you understand my problems... So here is the code!
Game.java
public class Game implements KeyListener {
int BACK_WIDTH = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
int BACK_HEIGHT = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
JFrame back_frame = new JFrame();
JPanel window = new JPanel();
JLabel title = new JLabel(Variables.TITLE);
Terminal login = new Terminal();
public static void main(String[] args) {
new Game();
}
public Game() {
try {
back_frame.setSize(BACK_WIDTH, BACK_HEIGHT);
back_frame.setLocation(0, 0);
back_frame.getContentPane().setBackground(Color.BLACK);
back_frame.setUndecorated(true);
back_frame.setVisible(true);
back_frame.add(window);
window.setBackground(Color.BLACK);
window.setLayout(null);
window.add(title);
title.setBounds((BACK_WIDTH / 2) - (550 / 2), (BACK_HEIGHT / 2) - (50 / 2), 550, 50);
title.setForeground(Color.WHITE);
back_frame.addKeyListener(this);
login.addKeyListener(this);
login.setLocationRelativeTo(null);
login.setVariables(Types.LOGINTERMINAL);
waitForStart();
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
int index;
public void waitForStart() {
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (index < 1 && index >= 0) {
index++;
} else {
((Timer)e.getSource()).stop();
login.setVisible(true);
login.slowPrint("Please login to continue...\n"
+ "Type 'help' for more information.\n");
}
}
});
timer.start();
}
public void keyPressed(KeyEvent e) {
int i = e.getKeyCode();
if(i == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
CustomFrame.java
public class CustomFrame implements MouseListener {
static JFrame frame = new JFrame();
public static Paint window = new Paint();
public void addKeyListener(KeyListener listener) {
frame.addKeyListener(listener);
}
private Point initialClick;
private boolean inBounds = false;
public int getWidth() {
return frame.getWidth();
}
public int getHeight() {
return frame.getHeight();
}
public void add(JComponent component) {
window.add(component);
}
public void setLocation(int x, int y) {
frame.setLocation(x, y);
}
public void setLocationRelativeTo(Component c) {
frame.setLocationRelativeTo(c);
}
private void setFrameType(Types type) {
switch(type) {
case TERMINAL:
frame.setSize(600, 400);
break;
case LOGINTERMINAL:
frame.setSize(600, 400);
break;
case NOTIFICATION:
frame.setSize(300, 150);
break;
default:
frame.setSize(600, 400);
break;
}
}
int index = 0;
public void slowPrint(final String text, final JTextArea field) {
Timer timer = new Timer(40, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (index < text.length() && index >= 0) {
String newChar = Character.toString(text.charAt(index));
field.append(newChar);
index++;
} else {
field.append("\n");
index = 0;
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
public void slowPrintAndClear(final String text, final JTextArea field, final boolean andQuit) {
Timer timer = new Timer(40, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (index < text.length() && index >= 0) {
String newChar = Character.toString(text.charAt(index));
field.append(newChar);
index++;
} else {
field.append("\n");
if(andQuit == false) {
field.setText(null);
} else {
System.exit(0);
}
index = 0;
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
public CustomFrame(Types type) {
frame.setAlwaysOnTop(true);
frame.addMouseListener(this);
frame.setResizable(false);
frame.setUndecorated(true);
setFrameType(type);
frame.add(window);
window.setLayout(null);
frame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
frame.getComponentAt(initialClick);
}
});
frame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if(e.getX() >= 0 && e.getX()<= frame.getWidth() &&
e.getY() >= 0 && e.getY() <= 20) {
inBounds = true;
}
if(inBounds == true) {
int thisX = frame.getLocation().x;
int thisY = frame.getLocation().y;
int xMoved = (thisX + e.getX()) - (thisX + initialClick.x);
int yMoved = (thisY + e.getY()) - (thisY + initialClick.y);
int x = thisX + xMoved;
int y = thisY + yMoved;
frame.setLocation(x, y);
}
}
});
}
public JFrame setVisible(boolean bool) {
frame.setVisible(bool);
return null;
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if(x >= CustomFrame.frame.getWidth() - 20 && x <= CustomFrame.frame.getWidth() - 6 &&
y >= 3 && y <= 14) {
frame.dispose();
}
}
public void mouseReleased(MouseEvent e) {
inBounds = false;
}
}
class Paint extends JPanel {
private static final long serialVersionUID = 1L;
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, CustomFrame.frame.getWidth(), CustomFrame.frame.getHeight());
Color LIGHT_BLUE = new Color(36, 171, 255);
//g2d.setColor(Color.BLUE);
GradientPaint topFill = new GradientPaint(0, 0, LIGHT_BLUE, CustomFrame.frame.getWidth(), 20, Color.BLUE);
g2d.setPaint(topFill);
g2d.fillRect(0, 0, CustomFrame.frame.getWidth(), 20);
g2d.setColor(Color.WHITE);
g2d.drawRect(0, 0, CustomFrame.frame.getWidth() - 1, CustomFrame.frame.getHeight() - 1);
g2d.drawLine(0, 20, CustomFrame.frame.getWidth(), 20);
g2d.fillRect(CustomFrame.frame.getWidth() - 20, 3, 14, 14);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
Terminal.java
public class Terminal implements KeyListener {
static CustomFrame frame = new CustomFrame(Types.TERMINAL);
JTextArea log = new JTextArea();
JTextField field = new JTextField();
public void setVisible(boolean bool) {
frame.setVisible(bool);
}
public void addKeyListener(KeyListener listener) {
frame.addKeyListener(listener);
}
public void setLogText(String str) {
log.setText(log.getText() + str + "\n");
}
public void setLocation(int x, int y) {
frame.setLocation(x, y);
}
public void setLocationRelativeTo(Component c) {
frame.setLocationRelativeTo(c);
}
int index = 0;
public void slowPrint(final String text) {
frame.slowPrint(text, log);
}
public void slowPrintAndClear(final String text, boolean andQuit) {
frame.slowPrintAndClear(text, log, andQuit);
}
public Terminal() {
try {
JScrollPane pane = new JScrollPane();
JScrollBar scrollBar = pane.getVerticalScrollBar();
scrollBar.setUI(new ScrollBarUI());
pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.setViewportView(log);
frame.add(field);
frame.add(pane);
log.setBackground(Color.BLACK);
log.setForeground(Color.WHITE);
log.setWrapStyleWord(true);
log.setLineWrap(true);
pane.setBounds(4, 20 + 4, frame.getWidth() - 8, frame.getHeight() - 50);
pane.setBorder(null);
log.setEditable(false);
log.setCaretColor(Color.BLACK);
field.setBackground(Color.BLACK);
field.setForeground(Color.WHITE);
field.setBounds(2, frame.getHeight() - 23, frame.getWidth() - 5, 20);
field.setHighlighter(null);
field.setCaretColor(Color.BLACK);
field.addKeyListener(this);
field.setText(" > ");
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void dumpToLog() {
log.setText(log.getText() + field.getText() + "\n");
field.setText(" > ");
}
public void setVariables(Types type) {
switch(type) {
case TERMINAL:
this.type = Types.TERMINAL;
break;
case LOGINTERMINAL:
this.type = Types.LOGINTERMINAL;
break;
default:
this.type = Types.TERMINAL;
break;
}
}
Types type;
public void keyPressed(KeyEvent e) {
int i = e.getKeyCode();
String text1 = " > ";
String text2 = field.getText().replaceFirst(text1, "");
String text2_1 = text2.trim();
String text = text1 + text2_1;
if (type == Types.TERMINAL) {
} else if (type == Types.LOGINTERMINAL) {
if(i == KeyEvent.VK_ENTER && field.isFocusOwner()) {
if(text.startsWith(" > register") || text.startsWith(" > REGISTER")) {
if(!(text.length() == 13)) {
dumpToLog();
slowPrint("Registry not available at this current given time.\n");
//TODO: Create registry system.
new Notification("test");
} else {
dumpToLog();
slowPrint("\nInformation:\n"
+ "Registers a new account.\n\n"
+ "Usage:\n"
+ "register <username>\n");
}
} else {
System.out.println("start |" + text + "| end");
dumpToLog();
slowPrint("Unknown command.\n");
}
}
} else {
// SETUP CODE FOR NOTIFICATION ERROR AGAIN
}
if(field.isFocusOwner() && i == KeyEvent.VK_LEFT || i == KeyEvent.VK_RIGHT) {
e.consume();
}
if(!field.getText().startsWith(" > ")) {
field.setText(" > ");
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
Notification.java
public class Notification {
static CustomFrame frame = new CustomFrame(Types.NOTIFICATION);
JTextArea display = new JTextArea();
public Notification(String notification) {
try {
frame.setLocationRelativeTo(null);
frame.add(display);
display.setBackground(Color.BLACK);
display.setForeground(Color.WHITE);
display.setWrapStyleWord(true);
display.setLineWrap(true);
display.setBounds(4, 20 + 4, frame.getWidth() - 8, frame.getHeight() - 50);
display.setBorder(null);
display.setEditable(false);
display.setCaretColor(Color.BLACK);
frame.slowPrint(notification, display);
frame.setVisible(true);
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Types.java
public enum Types {
TERMINAL, LOGINTERMINAL,
NOTIFICATION;
}
ScrollBarUI.java
public class ScrollBarUI extends MetalScrollBarUI {
private Image thumb, track;
private JButton blankButton() {
JButton b = new JButton();
b.setPreferredSize(new Dimension(0, 0));
b.setMaximumSize(new Dimension(0, 0));
b.setMinimumSize(new Dimension(0, 0));
return b;
}
public ScrollBarUI() {
thumb = FauxImage.create(32, 32, true);
track = FauxImage.create(32, 32, false);
}
protected void paintThumb(Graphics g, JComponent component, Rectangle rectangle) {
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.BLUE);
g2d.drawImage(thumb, rectangle.x, rectangle.y, rectangle.width, rectangle.height, null);
g2d.setPaint(Color.WHITE);
g2d.drawRect(rectangle.x, rectangle.y, rectangle.width - 1, rectangle.height-1);
}
protected void paintTrack(Graphics g, JComponent component, Rectangle rectangle) {
((Graphics2D) g).drawImage(track, rectangle.x, rectangle.y, rectangle.width, rectangle.height, null);
}
protected JButton createIncreaseButton(int orientation) {
return blankButton();
}
protected JButton createDecreaseButton(int orientation) {
return blankButton();
}
private static class FauxImage {
static public Image create(int width, int height, boolean thumb) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
if (thumb == true) {
Color LIGHT_BLUE = new Color(0, 140, 255);
//g2d.setPaint(Color.BLUE);
GradientPaint topFill = new GradientPaint(5, 25, Color.BLUE, 2, 2, LIGHT_BLUE);
g2d.setPaint(topFill);
g2d.fillRect(0, 0, width, height);
g2d.dispose();
} else {
g2d.setPaint(Color.BLACK);
g2d.fillRect(0, 0, width, height);
g2d.dispose();
}
return bi;
}
}
}
On a serious note though, if anyone is able to help me with such a sizeable post, I will SERIOUSLY be eternally grateful.
Cheers and thankyou... ALOT.
Edit:
Did have the time to fix up fonts. Extremely sorry, now it has been done.
Edit:
Here is where the Notification frame is called and doesn't end up showing:
if(!(text.length() == 13)) {
dumpToLog();
slowPrint("Registry not available at this current given time.\n");
//TODO: Create registry system.
new Notification("test");
}
As #Andrew Thompson, #trashgod pointed, it is a bad practice to use multiple frames.
If you still need to fix your problem, here goes:
The issue is with your static instance of the CustomFrame for your Game application and then modifying that frame instance using methods like setUndecorated(...).
In your Terminal class, you have
static CustomFrame frame = new CustomFrame(Types.TERMINAL);
and in your Notification class, you have
static CustomFrame frame = new CustomFrame(Types.NOTIFICATION);
but you are getting the same instance of the frame
static JFrame frame = new JFrame(); (in your CustomFrame class)
So what this means :
When the Game application loads, the Terminal is visible. And when you register a user, you are displying a Notification, with modified frame size and then by calling the setVisible() method of the CustomFrame.
Which is causing the issue. The setUndecorated() and setVisible() is invoked for the same static instance. YOU CANNOT MODIFY A FRAME WHICH IS VISIBLE. Meaning, YOU CAN ONLY MODIFY A FRAME BEFORE IT IS VISIBLE. Here your frame is already visible (for Terminal) and when displaying the Notification you are trying to change the size and display. WHICH IS WRONG.
As you said I want DIFFERENT JFrames, as in my code, I use Types.java as an enum to pick my different TYPES of frames. The frame is completely different each time due to the use of different components and sizing, to achieve this, you need multiple instances for each type of frame.
Changes/Fixes to your code :
Game1.java
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game1 implements KeyListener
{
int BACK_WIDTH = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
int BACK_HEIGHT = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
JFrame back_frame = new JFrame();
JPanel window = new JPanel();
JLabel title = new JLabel("Title");
Terminal1 login = new Terminal1();
public static void main(String[] args)
{
new Game1();
}
public Game1()
{
try
{
back_frame.setSize(BACK_WIDTH, BACK_HEIGHT);
back_frame.setLocation(0, 0);
back_frame.getContentPane().setBackground(Color.BLACK);
back_frame.setUndecorated(true);
back_frame.setVisible(true);
back_frame.add(window);
window.setBackground(Color.BLACK);
window.setLayout(null);
window.add(title);
title.setBounds((BACK_WIDTH / 2) - (550 / 2), (BACK_HEIGHT / 2) - (50 / 2), 550, 50);
title.setForeground(Color.WHITE);
back_frame.addKeyListener(this);
login.addKeyListener(this);
login.setLocationRelativeTo(null);
login.setVariables(Types.LOGINTERMINAL);
waitForStart();
}
catch (Exception e)
{
e.printStackTrace();
}
}
int index;
public void waitForStart()
{
Timer timer = new Timer(2000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (index < 1 && index >= 0)
{
index++;
}
else
{
((Timer) e.getSource()).stop();
login.setVisible(true);
login.slowPrint("Please login to continue...\n" + "Type 'help' for more information.\n");
}
}
});
timer.start();
}
public void keyPressed(KeyEvent e)
{
int i = e.getKeyCode();
if (i == KeyEvent.VK_ESCAPE)
{
System.exit(0);
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
CustomFrame1.java
import java.awt.Color;
import java.awt.Component;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class CustomFrame1 implements MouseListener
{
JFrame frame = new JFrame();
public static Paint window = null;
public void addKeyListener(KeyListener listener)
{
frame.addKeyListener(listener);
}
private Point initialClick;
private boolean inBounds = false;
public int getWidth()
{
return frame.getWidth();
}
public int getHeight()
{
return frame.getHeight();
}
public void add(JComponent component)
{
window.add(component);
}
public void setLocation(int x, int y)
{
frame.setLocation(x, y);
}
public void setLocationRelativeTo(Component c)
{
frame.setLocationRelativeTo(c);
}
private void setFrameType(Types type)
{
switch (type)
{
case TERMINAL:
frame.setSize(600, 400);
break;
case LOGINTERMINAL:
frame.setSize(600, 400);
break;
case NOTIFICATION:
frame.setSize(300, 150);
break;
default:
frame.setSize(600, 400);
break;
}
}
int index = 0;
public void slowPrint(final String text, final JTextArea field)
{
Timer timer = new Timer(40, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (index < text.length() && index >= 0)
{
String newChar = Character.toString(text.charAt(index));
field.append(newChar);
index++;
}
else
{
field.append("\n");
index = 0;
((Timer) e.getSource()).stop();
}
}
});
timer.start();
}
public void slowPrintAndClear(final String text, final JTextArea field, final boolean andQuit)
{
Timer timer = new Timer(40, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (index < text.length() && index >= 0)
{
String newChar = Character.toString(text.charAt(index));
field.append(newChar);
index++;
}
else
{
field.append("\n");
if (andQuit == false)
{
field.setText(null);
}
else
{
System.exit(0);
}
index = 0;
((Timer) e.getSource()).stop();
}
}
});
timer.start();
}
public CustomFrame1(Types type)
{
window = new Paint(frame);
frame.setAlwaysOnTop(true);
frame.addMouseListener(this);
frame.setResizable(false);
frame.setUndecorated(true);
setFrameType(type);
frame.add(window);
window.setLayout(null);
frame.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
initialClick = e.getPoint();
frame.getComponentAt(initialClick);
}
});
frame.addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
if (e.getX() >= 0 && e.getX() <= frame.getWidth() && e.getY() >= 0 && e.getY() <= 20)
{
inBounds = true;
}
if (inBounds == true)
{
int thisX = frame.getLocation().x;
int thisY = frame.getLocation().y;
int xMoved = (thisX + e.getX()) - (thisX + initialClick.x);
int yMoved = (thisY + e.getY()) - (thisY + initialClick.y);
int x = thisX + xMoved;
int y = thisY + yMoved;
frame.setLocation(x, y);
}
}
});
}
public void dispose()
{
frame.dispose();
}
public JFrame setVisible(boolean bool)
{
frame.setVisible(bool);
return null;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
if (x >= frame.getWidth() - 20 && x <= frame.getWidth() - 6 && y >= 3 && y <= 14)
{
frame.dispose();
}
}
public void mouseReleased(MouseEvent e)
{
inBounds = false;
}
}
class Paint extends JPanel
{
private static final long serialVersionUID = 1L;
private JFrame frame;
public Paint(JFrame frame)
{
this.frame = frame;
}
private void doDrawing(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, frame.getWidth(), frame.getHeight());
Color LIGHT_BLUE = new Color(36, 171, 255);
// g2d.setColor(Color.BLUE);
GradientPaint topFill = new GradientPaint(0, 0, LIGHT_BLUE, frame.getWidth(), 20, Color.BLUE);
g2d.setPaint(topFill);
g2d.fillRect(0, 0, frame.getWidth(), 20);
g2d.setColor(Color.WHITE);
g2d.drawRect(0, 0, frame.getWidth() - 1, frame.getHeight() - 1);
g2d.drawLine(0, 20, frame.getWidth(), 20);
g2d.fillRect(frame.getWidth() - 20, 3, 14, 14);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
doDrawing(g);
}
}
Terminal1.java
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class Terminal1 implements KeyListener
{
static CustomFrame1 frame = new CustomFrame1(Types.TERMINAL);
JTextArea log = new JTextArea();
JTextField field = new JTextField();
public void setVisible(boolean bool)
{
frame.setVisible(bool);
}
public void addKeyListener(KeyListener listener)
{
frame.addKeyListener(listener);
}
public void setLogText(String str)
{
log.setText(log.getText() + str + "\n");
}
public void setLocation(int x, int y)
{
frame.setLocation(x, y);
}
public void setLocationRelativeTo(Component c)
{
frame.setLocationRelativeTo(c);
}
int index = 0;
public void slowPrint(final String text)
{
frame.slowPrint(text, log);
}
public void slowPrintAndClear(final String text, boolean andQuit)
{
frame.slowPrintAndClear(text, log, andQuit);
}
public Terminal1()
{
try
{
JScrollPane pane = new JScrollPane();
JScrollBar scrollBar = pane.getVerticalScrollBar();
scrollBar.setUI(new ScrollBarUI());
pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.setViewportView(log);
frame.add(field);
frame.add(pane);
log.setBackground(Color.BLACK);
log.setForeground(Color.WHITE);
log.setWrapStyleWord(true);
log.setLineWrap(true);
pane.setBounds(4, 20 + 4, frame.getWidth() - 8, frame.getHeight() - 50);
pane.setBorder(null);
log.setEditable(false);
log.setCaretColor(Color.BLACK);
field.setBackground(Color.BLACK);
field.setForeground(Color.WHITE);
field.setBounds(2, frame.getHeight() - 23, frame.getWidth() - 5, 20);
field.setHighlighter(null);
field.setCaretColor(Color.BLACK);
field.addKeyListener(this);
field.setText(" > ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void dumpToLog()
{
log.setText(log.getText() + field.getText() + "\n");
field.setText(" > ");
}
public void setVariables(Types type)
{
switch (type)
{
case TERMINAL:
this.type = Types.TERMINAL;
break;
case LOGINTERMINAL:
this.type = Types.LOGINTERMINAL;
break;
default:
this.type = Types.TERMINAL;
break;
}
}
Types type;
public void keyPressed(KeyEvent e)
{
int i = e.getKeyCode();
String text1 = " > ";
String text2 = field.getText().replaceFirst(text1, "");
String text2_1 = text2.trim();
String text = text1 + text2_1;
if (type == Types.TERMINAL)
{
}
else if (type == Types.LOGINTERMINAL)
{
if (i == KeyEvent.VK_ENTER && field.isFocusOwner())
{
if (text.startsWith(" > register") || text.startsWith(" > REGISTER"))
{
if (!(text.length() == 13))
{
dumpToLog();
slowPrint("Registry not available at this current given time.\n");
// TODO: Create registry system.
new Notification1("test");
}
else
{
dumpToLog();
slowPrint("\nInformation:\n" + "Registers a new account.\n\n" + "Usage:\n" + "register <username>\n");
}
}
else
{
System.out.println("start |" + text + "| end");
dumpToLog();
slowPrint("Unknown command.\n");
}
}
}
else
{
// SETUP CODE FOR NOTIFICATION ERROR AGAIN
}
if (field.isFocusOwner() && i == KeyEvent.VK_LEFT || i == KeyEvent.VK_RIGHT)
{
e.consume();
}
if (!field.getText().startsWith(" > "))
{
field.setText(" > ");
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
Notification1.java
import java.awt.Color;
import javax.swing.JTextArea;
public class Notification1
{
static CustomFrame1 frame = new CustomFrame1(Types.NOTIFICATION);
JTextArea display = new JTextArea();
public Notification1(String notification)
{
try
{
frame.setLocationRelativeTo(null);
frame.add(display);
display.setBackground(Color.BLACK);
display.setForeground(Color.WHITE);
display.setWrapStyleWord(true);
display.setLineWrap(true);
display.setBounds(4, 20 + 4, frame.getWidth() - 8, frame.getHeight() - 50);
display.setBorder(null);
display.setEditable(false);
display.setCaretColor(Color.BLACK);
frame.slowPrint(notification, display);
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Infinite background for game

I am working on a Java project to simulate the flight of a helicopter in a frame. The helicopter moves on the screen using the arrow keys. I want the helicopter to be able to move infinitely, that is, when the helicopter reaches the edge of the frame, the background should move in the opposite direction to have the effect of endless terrain.
Here is the code I have so far:
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainFrame extends JFrame
{
private static int FRAME_WIDTH = 800;
private static int FRAME_HEIGHT = 500;
public MainFrame()
{
add(new AnotherBackground(FRAME_WIDTH, FRAME_HEIGHT));
setTitle("Helicopter Background Test");
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new MainFrame();
}
}
class AnotherBackground extends JPanel
{
private BufferedImage heliImage = null;
private BufferedImage backImage = null;
private int heliX = 0;
private int heliY = 0;
private int backX = 0;
private int backY = 0;
private int frameWidth = 0;
private int frameHeight = 0;
private int backWidth = 0;
private int backHeight = 0;
public AnotherBackground(int fWidth, int fHeight)
{
frameWidth = fWidth;
frameHeight = fHeight;
this.setFocusable(true);
this.addKeyListener(new HeliListener());
try
{
heliImage = ImageIO.read(new URL("http://imageshack.us/a/img7/2133/helicopter2f.png"));
// 2.7 Meg Crap that is a humungous image! Substitute dummy.
backImage = new BufferedImage(1918,1200,BufferedImage.TYPE_INT_RGB);
}
catch(IOException ex)
{
System.out.println("Problem durinng loading heli image");
}
backWidth = backImage.getWidth();
backHeight = backImage.getHeight();
HeliPainter l = new HeliPainter();
new Thread(l).start();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(backImage, backX, backY, null);
g.drawImage(heliImage, heliX, heliY, null);
}
class HeliListener extends KeyAdapter
{
#Override
public void keyPressed(KeyEvent e)
{
System.out.println(heliX + " " + heliY + " " + backX + " " + backY);
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(heliX > 0)
{
heliX -= 5;
}
else
{
backX += 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(heliX < frameWidth)
{
heliX += 5;
}
else
{
backX -= 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
if(heliY > 0)
{
heliY -= 5;
}
else
{
backY += 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(heliY < frameHeight)
{
heliY += 5;
}
else
{
backY -= 5;
}
}
}
}
class HeliPainter implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
repaint();
}
});
Thread.sleep(1);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem putting thread to sleep");
}
}
}
}
Now there's two images in the code. One is that of a small helicopter, and the other is a large (2.7 meg) background. They are here:
background
helicopter http://imageshack.us/a/img7/2133/helicopter2f.png
How to show the BG continuously?
Have a look through this source which behaves in a more predictable manner, and also includes a nice tweak to the chopper image (animated). ;)
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainFrame
{
public MainFrame()
{
JFrame f = new JFrame("Helicopter Background Test");
f.add(new AnotherBackground());
//setTitle("Helicopter Background Test"); Redundant..
// Set a preferred size for the content area and pack() the frame instead!
// setSize(FRAME_WIDTH,FRAME_HEIGHT);
// setLocationRelativeTo(null); Better to..
f.setLocationByPlatform(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack(); // Size the GUI - VERY MPORTANT!
f.setVisible(true);
}
public static void main(String[] args)
{
new MainFrame();
}
}
class AnotherBackground extends JPanel
{
private static int PREFERRED_WIDTH = 400;
private static int PREFERRED_HEIGHT = 200;
private BufferedImage heliImage = null;
private BufferedImage heliLeftImage = null;
private BufferedImage heliRightImage = null;
private BufferedImage backImage = null; //getFlippedImage(
private int heliX = 0;
private int heliY = 0;
private int backX = 0;
private int backY = 0;
private int frameWidth = 0;
private int frameHeight = 0;
private int backWidth = 0;
private int backHeight = 0;
public AnotherBackground()
{
frameWidth = PREFERRED_WIDTH;
frameHeight = PREFERRED_HEIGHT;
this.setFocusable(true);
this.addKeyListener(new HeliListener());
try
{
heliLeftImage = ImageIO.read(
new URL("http://imageshack.us/a/img7/2133/helicopter2f.png"));
heliRightImage = getFlippedImage(heliLeftImage);
heliImage = heliLeftImage;
// 2.7 Meg Crap that is an humungous image! Substitute dummy.
backImage = getTileImage(250);
//ImageIO.read(
// new URL("http://i.stack.imgur.com/T5uTa.png"));
backWidth = backImage.getWidth();
backHeight = backImage.getHeight();
//HeliPainter l = new HeliPainter(); // see mention of repaint()
//new Thread(l).start();
} catch(IOException ex) {
// THERE IS NO POINT CONTINUING AFTER THIS POINT!
// unless it is to pop an option pane error message..
System.err.println("Problem during loading heli image");
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
int normalizeX = (heliRealX-heliX)%backImage.getWidth();
int normalizeY = (heliRealY-heliY)%backImage.getHeight();
int timesRepeatX = (getWidth()/backImage.getWidth())+2;
int timesRepeatY = (getHeight()/backImage.getHeight())+2;
for (int xx=-1; xx<timesRepeatX; xx++) {
for (int yy=-1; yy<timesRepeatY; yy++) {
g.drawImage(
backImage,
(xx*backImage.getWidth())-normalizeX,
(yy*backImage.getHeight())-normalizeY,
this); // A JPanel IS AN ImageObserver!
g.drawImage(heliImage, heliX, heliY, this);
}
}
g.setColor(Color.BLACK);
}
private int heliRealX = 0;
private int heliRealY = 0;
class HeliListener extends KeyAdapter
{
#Override
public void keyPressed(KeyEvent e)
{
int pad = 5;
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(heliX > 0)
{
heliX -= 5;
}
else
{
backX += 5;
}
heliRealX-=5;
heliImage = heliLeftImage;
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
// correct for image size + padding
if(heliX+heliImage.getWidth()+pad < getWidth())
{
heliX += 5;
}
else
{
backX -= 5;
}
heliRealX+=5;
heliImage = heliRightImage;
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
if(heliY > 0)
{
heliY -= 5;
}
else
{
backY += 5;
}
heliRealY-=5;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
// correct for image size + padding
if(heliY+heliImage.getHeight()+pad < getHeight())
{
heliY += 5;
}
else
{
backY -= 5;
}
heliRealY+=5;
}
repaint(); // Replaces need for threads for this simple demo!
}
}
public BufferedImage getFlippedImage(BufferedImage original) {
BufferedImage bi = new BufferedImage(
original.getWidth(),
original.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
AffineTransform at = AffineTransform.getTranslateInstance(bi.getWidth(),1d);
at.concatenate(AffineTransform.getScaleInstance(-1d,1d));
g.setTransform(at);
g.drawImage(original,0,0,this);
g.dispose();
return bi;
}
public BufferedImage getTileImage(int s) {
BufferedImage bi = new BufferedImage(s,s,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
GradientPaint gp1 = new GradientPaint(
(float)0,(float)s/4, Color.YELLOW,
(float)s/4,0f, Color.GREEN,
true);
g.setPaint(gp1);
g.fillRect(0,0,s,s);
int trans = 165;
GradientPaint gp2 = new GradientPaint(
(float)s/2,(float)s/2, new Color(255,0,0,trans),
0f,(float)s/2, new Color(255,255,255,trans),
true);
g.setPaint(gp2);
g.fillRect(0,0,s,s);
g.dispose();
return bi;
}
}
This is a really simple example (you can only move in a single direction). The basic idea is that there is a prepareView method that is responsible for generating a view of the world based on the available viewable area. If the view is trying to view an area off the map, the map is titled to make up for it.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class InfiniteBackground {
public static void main(String[] args) {
new InfiniteBackground();
}
public InfiniteBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
protected static final int DELTA = 5;
private BufferedImage terrian;
private BufferedImage heli;
private Point pov;
private Point heliPoint;
private BufferedImage view;
public TestPane() {
pov = new Point();
heliPoint = new Point();
try {
terrian = ImageIO.read(getClass().getResource("/terrain_map.jpg"));
heli = ImageIO.read(getClass().getResource("/helicopter2f.png"));
pov.x = terrian.getWidth() - getPreferredSize().width;
pov.y = ((terrian.getHeight() - getPreferredSize().height) / 2);
heliPoint.x = getPreferredSize().width / 2;
heliPoint.y = getPreferredSize().height / 2;
prepareView();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "goLeft");
am.put("goLeft", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
heliPoint.x -= DELTA;
if (heliPoint.x - (heli.getWidth() / 2) < 0) {
heliPoint.x = (heli.getWidth() / 2);
prepareView();
pov.x -= DELTA;
}
repaint();
}
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
protected void prepareView() {
if (getWidth() > 0 && getHeight() > 0) {
view = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = view.createGraphics();
if (pov.x < 0) {
pov.x = terrian.getWidth();
}
g2d.drawImage(terrian, -pov.x, -pov.y, this);
if (pov.x + getWidth() > terrian.getWidth()) {
g2d.drawImage(terrian, -pov.x + terrian.getWidth(), -pov.y, this);
}
g2d.dispose();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (terrian != null) {
Graphics2D g2d = (Graphics2D) g.create();
if (view == null) {
prepareView();
}
g2d.drawImage(view, 0, 0, this);
g2d.drawImage(heli, heliPoint.x - (heli.getWidth() / 2), heliPoint.y - (heli.getHeight() / 2), this);
g2d.dispose();
}
}
}
}

How can I move a jlabel image around the screen?

I want to click on the screen and have the character move to that destination. Not instantly, but rather "walk" to the given coordinate. Currently I'm using JLabels and they're fine if I only use static images, but everytime I click somewhere on the screen the image shows up at that exact point. Could someone give me some tips?
edit: Should I override the paint class and draw some items that way?
Here's some code:
package mod;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.awt.KeyboardFocusManager;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Board2 extends JPanel {
private Thread animator;
int x, y;
double ix, iy;
double dx, dy;
final int frameCount = 8;
BufferedImage flower;
private int[][] fPos = {{232, 15},{400, 200},{335, 335}}; // flower coordinates
private static int bWIDTH = 800; // width of window
private static int bHEIGHT = 600;// height of window
private Font font;
private FontMetrics metrics;
ImageIcon grassI = new ImageIcon(this.getClass().getResource("grass.png"));
ImageIcon riverI = new ImageIcon(this.getClass().getResource("river.png"));
private Image grass = grassI.getImage();
private Image river = riverI.getImage();
private House house = new House();
private River river1 = new River();
//private Flower flower = new Flower();
private TitleScreenLayer ts = new TitleScreenLayer();
private Player girlP = new Player();
private static int px = 250;
private static int py = 250;
private boolean visTl = false;
private boolean plant = false;
ArrayList<Flower> flowers= new ArrayList<Flower>();
private long period;
private volatile boolean running = false;
private volatile boolean gameOver = false;
private volatile boolean isPaused = false;
// New stuff for Board2 below
private JLayeredPane lpane;
private JLabel grassLabel;
private JLabel riverLabel;
private JLabel houseLabel;
private JLabel pear1Label;
private JLabel pear2Label;
private JLabel pear3Label;
private JLabel drivewayLabel;
private JLabel girlLabel;
private JProgressBar progressBar;
private JLabel toolLabel;
private JTextArea textBubble;
ImageIcon girlImage = new ImageIcon(girlP.getImage());
int mouseClicks = 0;
CountdownTimer cTimer;
private static String message;
public static String setMessage(String newMessage){
return message = newMessage;
}
private static ImageIcon playerTool = new ImageIcon("BradfordPear.png");
public ImageIcon getPlayerTool(){
return playerTool;
}
public static void setPlayerTool(String image){
playerTool = new ImageIcon(image);
}
public JTextArea getTextBubble(){
return textBubble;
}
public Player getPlayer(){
return girlP;
}
public static int getPlayerX(){
return px;
}
public static int getPlayerY(){
return py;
}
public JLayeredPane getLayeredPane(){
return lpane;
}
public Board2(){
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
//create the layered pane
lpane = new JLayeredPane();
lpane.setPreferredSize(new Dimension(800, 600));
//create the "background" image
ImageIcon image = new ImageIcon("grass.png");
grassLabel = new JLabel(image);
grassLabel.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
//create the house image
ImageIcon houseImage = new ImageIcon("house.png");
houseLabel = new JLabel(houseImage);
houseLabel.setBounds(-330, -150, image.getIconWidth(), image.getIconHeight());
//create the driveway image
ImageIcon drivewayImage = new ImageIcon("driveway.png");
drivewayLabel = new JLabel(drivewayImage);
drivewayLabel.setBounds(-335, 105, image.getIconWidth(), image.getIconHeight());
//create the river image
ImageIcon riverImage = new ImageIcon("river.png");
riverLabel = new JLabel(riverImage);
riverLabel.setBounds(360, 0, image.getIconWidth(), image.getIconHeight());
//create pear1 image
ImageIcon pear1Image = new ImageIcon("BradfordPear.png");
pear1Label = new JLabel(pear1Image);
pear1Label.setBounds(100, 100, image.getIconWidth(), image.getIconHeight());
//create pear2 image
ImageIcon pear2Image = new ImageIcon("BradfordPear.png");
pear2Label = new JLabel(pear2Image);
pear2Label.setBounds(50, -100, image.getIconWidth(), image.getIconHeight());
//create pear3 image
ImageIcon pear3Image = new ImageIcon("BradfordPear.png");
pear3Label = new JLabel(pear3Image);
pear3Label.setBounds(-100, -50, image.getIconWidth(), image.getIconHeight());
//create initial Player(girl) image
//ImageIcon girlImage = new ImageIcon(girlP.getImage());
girlLabel = new JLabel(girlImage);
girlLabel.setBounds((int)girlP.getPositionX(), (int)girlP.getPositionY(), image.getIconWidth(), image.getIconHeight());
//create progress bar
progressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 10);
progressBar.setValue(0);
progressBar.setBounds(720, 50, 100, 500);
//create timer
JTextField timerField = new JTextField();
cTimer = new CountdownTimer(timerField);
timerField.setBounds(400, 0, 50, 50);
//create toolbox
Toolbox toolbox = new Toolbox();
toolbox.setBounds(550, 0, 250, 50);
//create the text bubble
textBubble = new JTextArea("IDPC is the best coding group ever");
textBubble.setLineWrap(true);
//textBubble.setBounds(200, 200, 100, 100);
//add the background & various images
lpane.add(grassLabel, new Integer(1));
lpane.add(houseLabel, new Integer(2));
lpane.add(riverLabel, new Integer(2));
lpane.add(drivewayLabel, new Integer(2));
lpane.add(pear1Label, new Integer(2));
lpane.add(pear2Label, new Integer(2));
lpane.add(pear3Label, new Integer(2));
lpane.add(progressBar, new Integer(3));
lpane.add(girlLabel, new Integer(3));
lpane.add(timerField, new Integer(2));
lpane.add(toolbox, new Integer(3));
add(lpane);
cTimer.start();
// listen for action events
new ActionListener() {
public void actionPerformed(ActionEvent e) {
girlP.move();
//girlLabel.setLocation(px, py);
}
};
// listen for mouse presses
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
//lpane.remove(textBubble);
mouseClicks+= 1;
testPress(e.getX(), e.getY());
//textBubble.setBounds(e.getX(), e.getY(), 40, 40);
updateProgressBar();
}
});
//listen for player action
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2){
ImageIcon flowerImage = playerTool;
JLabel flowerPanel = new JLabel(flowerImage);
flowerPanel.setBounds((px -((int)girlP.getPositionX() / 2)),
(py - ((int)girlP.getPositionY() / 2)),
flowerImage.getIconWidth(),
flowerImage.getIconHeight());
lpane.add(flowerPanel, new Integer(3));
textBubble.setBounds(e.getX(), e.getY(), 200, 40);
textBubble.replaceSelection(message);
lpane.add(textBubble, new Integer(3));
//lpane.remove(textBubble);
}
}
});
x = 15;
y = 150;
ix = 0;
iy = 0;
dx = .05;
dy = .05;
girlP.setDestination(px, py);
}
public void testPress(int x, int y){
px = x;
py = y;
if (px < (ix + house.getImage().getWidth(this))
&& (py < (iy + house.getImage().getHeight(this)))) {
px = px + (house.getImage().getWidth(this)/3);
py = py + (house.getImage().getHeight(this)/3);
}
if (px > (bWIDTH - river1.getImage().getWidth(this))) {
px = px - 80 - (river1.getImage().getWidth(this)/2);
}
girlLabel.setBounds((px -((int)(girlP.getPositionX()*2.5))),
(py - ((int)(girlP.getPositionY()*2.5))),
girlImage.getIconWidth(), girlImage.getIconHeight());
girlP.setDestination((px-(girlP.getImage().getWidth(this)/2)),
(py-(girlP.getImage().getHeight(this)/2)));
girlP.pinned(x, y);
}
public void updateProgressBar(){
if(progressBar.getValue() == 3){
//progressBar.setBackground(Color.red);
//UIManager.put("progressBar.foreground", Color.RED);
UIDefaults defaults = new UIDefaults();
defaults.put("progressBar[Enabled].foregroundPainter", Color.RED);
progressBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
progressBar.putClientProperty("Nimbus.Overrides", defaults);
}
progressBar.setValue(mouseClicks);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new TitleScreenLayer();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Here's the player class:
package mod;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.ImageObserver;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class Player {
int tile;
double positionX;
double positionY;
int destinationX;//Used when moving from place to place
int destinationY;
Tool currentTool;
int direction; //Position the image is facing
double dx;
double dy;
int [] pin = new int[10];
private String girl = "girl.png";
ImageIcon ii = new ImageIcon(this.getClass().getResource(girl)); // load girl image
private Image image = ii.getImage();
private boolean visible = true;
public boolean plant = false;
Image playerImage;
public double getPositionX() {
return positionX;
}
public void setPositionX(double positionX) {
this.positionX = positionX;
}
public double getPositionY() {
return positionY;
}
public void setPositionY(double positionY) {
this.positionY = positionY;
}
public Player(){
positionX=30;
positionY=20;
dx = 0.2;
dy = 0.2;
destinationX=(int)positionX;
destinationY=(int)positionY;
//this.playerImage=playerImage;
}
public void doAction() {
//currentTool.getNum();
plant = true;
}
public void pinned(int x, int y) {
if (plant == true) {
pin[0] = x;
pin[1] = y;
}
//plant = false;
}
public void plant(Graphics g, ImageObserver io) {
int x = pin[0];
int y = pin[1];
if (plant == true) {
// g.drawImage(flower.getImage(), x, y, io);
}
}
public void ActionPerformed(ActionEvent e) {
positionX += dx;
positionY += dy;
}
public boolean isVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public Image getImage() {
return image;
}
public void move(){
//MOVE LEFT AND RIGHT
if(destinationX<positionX){
positionX-=dx;
}
if(destinationX>positionX){
positionX+=dx;
}
//MOVE UP AND DOWN
if(destinationY<positionY){
positionY-=dy;
}
if(destinationY>positionY){
positionY+=dy;
}
}
public double setDx(double speed) {
dx = speed;
return dx;
}
public double setDy(double speed) {
dy = speed;
return dy;
}
public void TileIn(int px, int py)
{
px=destinationX;
py=destinationY;
int tileX=1;
int tileY = 1;
int bWIDTH=800;
int bHEIGHT=600;
if(px >= 0 && px <= 800*.1)
{
tileX=2;
}
else if(px> bWIDTH*.1 && px <= bWIDTH*.2)
{
tileX=3;
}
else if(px > bWIDTH*.2 && px <= bWIDTH*.3)
{
tileX=4;
}
else if(px > bWIDTH*.3 && px <= bWIDTH*.4)
{
tileX=5;
}
else if(px > bWIDTH*.4 && px <= bWIDTH*.5)
{
tileX=6;
}
else if(px > bWIDTH*.5 && px <= bWIDTH*.6)
{
tileX=7;
}
else if(px > bWIDTH*.6 && px <= bWIDTH*.7)
{
tileX=8;
}
else if(px > bWIDTH*.7 && px <= bWIDTH*.8)
{
tileX=9;
}
else if(px > bWIDTH*.8 && px <= bWIDTH*.9)
{
tileX=10;
}
else if(px > bWIDTH*.9 && px <= bWIDTH)
{
tileX=11;
}
if(py >= 0 && py <= bHEIGHT*.1)
{
tileY=2;
}
else if(py> bHEIGHT*.1 && py <= bHEIGHT*.2)
{
tileY=3;
}
else if(py > bHEIGHT*.2 && py <= bHEIGHT*.3)
{
tileY=4;
}
else if(py > bHEIGHT*.3 && py <= bHEIGHT*.4)
{
tileY=5;
}
else if(py > bHEIGHT*.4 && py <= bHEIGHT*.5)
{
tileY=6;
}
else if(py > bHEIGHT*.5 && py <= bHEIGHT*.6)
{
tileY=7;
}
else if(py > bHEIGHT*.6 && py <= bHEIGHT*.7)
{
tileY=8;
}
else if(py > bHEIGHT*.7 && py <= bHEIGHT*.8)
{
tileY=9;
}
else if(py > bHEIGHT*.8 && py <= bHEIGHT*.9)
{
tileY=10;
}
else if(py > bHEIGHT*.9 && py <= bHEIGHT)
{
tileY=11;
}
System.out.println("Grid X: " + tileX + " Grid Y: " + tileY);
}
public void setDestination(int x, int y){
destinationX=x;
destinationY=y;
System.out.println(x + "," + y);
TileIn(x,y);
}
// public void tileIn(int a)
// {
//
// b=destinationY;
// return TileIn(x,y)
// }
public void draw(Graphics g,ImageObserver io){
g.drawImage(image, (int)positionX,(int) positionY,io);
}
}
Here is the main class:
package mod;
import java.awt.Container;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class Skeleton2 extends JFrame /*implements WindowListener*/{
private static int DEFAULT_FPS = 80;
private Board2 bd;
public Skeleton2(long period) {
super("Skeleton");
makeGUI(period);
//addWindowListener(this);
pack();
setResizable(false);
setVisible(true);
}
public void makeGUI(long period) {
Container c = getContentPane();
bd = new Board2();
c.add(bd, "Center");
} // end of makeGUI()
//==================================================================================
// Window Events
//==================================================================================
/*
public void windowActivated(WindowEvent e) {
bd.resumeGame();
}
public void windowDeactivated(WindowEvent e) {
bd.pauseGame();
}
public void windowDeiconified(WindowEvent e) {
bd.resumeGame();
}
public void windowIconified(WindowEvent e) {
bd.pauseGame();
}
public void windowClosing(WindowEvent e) {
bd.stopGame();
}
*/
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
//==================================================================================
public static void main(String[] args) {
int fps = DEFAULT_FPS;
long period = (long) 1000.0/fps;
new Skeleton2(period);
System.out.println("Period: " + period);
}
}
Not instantly, but rather "walk" to the given coordinate.
Then you need to use a Swing Timer. The Timer is used to schedule the animation. So you would need to calculate a path between the two points. Every time the Timer fires you would move the label a few pixels until it reaches it's destination.
There is no need to do custom painting for this. A JLabel will work fine. The hard part is calculating the path you want the character to take. Also make sure you use a null layout on the panel you add the JLabel to, which means you will also need to set the size of the label equal to the preferred size of the label.
You should rather use g.drawImage in your component paintComponent method.

Categories