This is the class Ive used to create the JFrame:
import javax.swing.JFrame;
import javax.swing.*;
public class macheads{
public static void main(String[] args){
{
JFrame f = new JFrame();
second object = new second();
f.add(object);
f.setVisible(true);
mazeclass component = new mazeclass();
f.add(component);
f.setVisible(true);
f.setSize(500,400);
f.setLocationRelativeTo(null);
f.setTitle("Maze Game");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
This is the class that I am using to create the player piece (with key listeners to move it)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class second extends JPanel implements ActionListener, KeyListener
{
Timer t = new Timer(5, this);
double x = 0, y = 0, velx = 0, vely = 0;
public second(){
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
//Draws/Paints
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.fill(new Rectangle.Double(x, y, 40, 40));
}
public void actionPerformed(ActionEvent e){
if(x > 500)
{
velx = 0;
x = 500;
}
if(y<0)
{
vely = 0;
y = 0;
}
if(x > 460)
{
velx = 0;
x = 460;
}
x = x + velx;
y = y + vely;
repaint();
}
//the keys (up is negative down is positive)
public void up(){
vely = -1;
velx = 0;
}
public void down(){
vely = 1;
velx = 0;
}
public void left(){
velx = -1;
vely = 0;
}
public void right(){
velx = 1;
vely = 0;
}
//this sets up how you know which key is used
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
up();
}
if (code == KeyEvent.VK_DOWN){
down();
}
if (code == KeyEvent.VK_RIGHT){
right();
}
if (code == KeyEvent.VK_LEFT){
left();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
velx = 0;
vely = 0;
}
}
This is the class ive used to create the maze(the painted rectangles)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
public class mazeclass extends JComponent{
public void paintComponent(Graphics g)
{
//Level One Graphics
//Right wall
Graphics2D g2 = (Graphics2D) g;
Rectangle rim2 = new Rectangle (650,0,5,900);
g2.fill(rim2);
g2.setColor(Color.BLACK);
g2.draw(rim2);
g2.fill(rim2);
}
}
Ive talked to my teacher about the problem ive been having but he has not worked with graphics much and had no idea. Ive tried everything that I can think of. Also is this possible because he did mention he wasnt sure if I could do it like that, but this is the only way I could think of...Thanks for you help!!!!

New Topic/Question
Reply



MultiQuote








|