Adding graphics on same Panel from different classes - java

I am working on a project that simulates a traffic intersection. So far I did the map, traffic lights. Now I want to add some movement, some cars in my project. The problem that I am facing is that i can't add graphics on the same Panel from different classes. And can someone give me a good tutorial where I can learn how to move multiple graphics (cars in my case) .
Main class:
import java.awt.Color;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
MyMap map = new MyMap();
MyCar car = new MyCar();
Thread x = new Thread(map);
x.start();
JFrame f = new JFrame("Broadway Intersection");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
map.setBackground(Color.white);
f.add(map);
f.add(car);
f.setSize(1366, 738);
f.setVisible(true);
}
}
Map class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyMap extends JPanel implements Runnable {
Color color = Color.RED;
Color color2 = Color.RED;
Color color3 = Color.RED;
Color color4 = Color.RED;
int[] faza = new int[4];
int k;
int faza_curenta = 0;
public MyMap() {
faza[0] = 20;
faza[1] = 20;
faza[2] = 20;
faza[3] = 20;
}
public void run() {
color = Color.GREEN;
while (true) {
System.out.println("Faza = " + faza_curenta + " k= " + k);
k++;
if (k == faza[0]) {
faza_curenta = 1;
color = Color.RED;
color2 = Color.GREEN;
} else if (k == (faza[0] + faza[1])) {
faza_curenta = 2;
color = Color.RED;
color2 = Color.RED;
color3 = Color.GREEN;
} else if (k == (faza[0] + faza[1] + faza[2])) {
faza_curenta = 3;
color = Color.RED;
color3 = Color.RED;
color4 = Color.GREEN;
} else if (k == (faza[0] + faza[1] + faza[2] + faza[3])) {
faza_curenta = 0;
color = Color.GREEN;
color4 = Color.RED;
k = 0;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 250); // stanga sus
g.fillRect(900, 0, 500, 250); // dreapta sus
g.fillRect(0, 500, 500, 250);// stanga jos
g.fillRect(900, 500, 500, 250); // dreapta jos
g.setColor(Color.GRAY);
g.fillRect(500, 0, 400, 900);
g.fillRect(0, 250, 500, 250);
g.fillRect(900, 250, 500, 250);
g.setColor(Color.WHITE);
g.fillRect(695, 0, 5, 100);// linii verticale
g.fillRect(695, 150, 5, 100);
g.fillRect(695, 500, 5, 100);
g.fillRect(695, 650, 5, 50);
g.fillRect(0, 370, 50, 5);
g.fillRect(100, 370, 100, 5); // linii orizontale
g.fillRect(250, 370, 100, 5);
g.fillRect(400, 370, 100, 5);
g.fillRect(900, 370, 100, 5);
g.fillRect(1050, 370, 100, 5);
g.fillRect(1200, 370, 100, 5);
g.setColor(Color.BLACK);
g.fillRect(470, 220, 30, 30); // semafor Nord
g.setColor(color);
g.fillOval(475, 225, 20, 20); // semafor Nord
g.setColor(Color.BLACK);
g.fillRect(900, 220, 30, 30); // semafor Est
g.setColor(color2);
g.fillOval(905, 225, 20, 20); // semafor Nord
g.setColor(Color.BLACK);
g.fillRect(470, 500, 30, 30); // semafor Vest
g.setColor(color4);
g.fillOval(475, 505, 20, 20); // semafor Nord
g.setColor(Color.BLACK);
g.fillRect(900, 500, 30, 30); // semafor Sud
g.setColor(color3);
g.fillOval(905, 505, 20, 20); // semafor Nord
repaint();
}
}
And finally MyCar class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyCar extends JPanel {
int x; // X position
int y; // Y position
int xSpeed; // Speed in the X direction
int ySpeed; // Speed in the Y direction
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(420, 200, 30, 30);
repaint();
}
}

You can set Panel.setLayout(null); and add JButton by setting image icon on it now you can control Button (CAR) location by button.setLocation(x,y);

Related

Attempting to create a moving sprite in java but there is an afterimage

I'm trying to create a moving sprite in java, which I have managed to do, except every time I move it there is an afterimage that follows the sprite. Are there any ways I could easily fix this problem without radically changing my code?
I'm completely stumped as to any kind of ways I could fix this problem.
To get the full context I have to post all three files.
Here's the first file:
package gameproject;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class CarMovement {
private int dx;
private int dy;
private int x = 635;
private int y = 550;
private int w;
private int h;
private Image moveimage;
public CarMovement() {
loadImage();
}
private void loadImage() {
ImageIcon q = new ImageIcon("racecar.png");
moveimage = q.getImage();
w = moveimage.getWidth(null);
h = moveimage.getHeight(null);
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public Image getImage() {
return moveimage;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = -10;
}
if (key == KeyEvent.VK_D) {
dx = 10;
}
if (key == KeyEvent.VK_W) {
dy = -10;
}
if (key == KeyEvent.VK_S) {
dy = 10;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = 0;
}
if (key == KeyEvent.VK_D) {
dx = 0;
}
if (key == KeyEvent.VK_W) {
dy = 0;
}
if (key == KeyEvent.VK_S) {
dy = 0;
}
}
}
The second:
package gameproject;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CarMovement2 extends JPanel implements ActionListener {
private Timer timer;
private CarMovement racecar;
private final int DELAY = 10;
public CarMovement2() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
racecar = new CarMovement();
timer = new Timer(DELAY, this);
timer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0, 204, 0));
g.fillRect(0, 0, 400, 1100);
g.fillRect(1525, 0, 400, 1100);
g.setColor(new Color(102, 102, 102));
g.fillRect(400, 0, 1125, 1100);
g.setColor(new Color(255, 255, 255));
g.fillRect(940, 25, 25, 100);
g.fillRect(940, 325, 25, 100);
g.fillRect(940, 475, 25, 100);
g.fillRect(940, 625, 25, 100);
g.fillRect(940, 775, 25, 100);
g.fillRect(940, 925, 25, 100);
g.setColor(new Color(255, 255, 255));
g.fillRect(400, 175, 1125, 100);
g.setColor(new Color(0, 0, 0));
g.fillRect(400, 225, 50, 50);
g.fillRect(450, 175, 50, 50);
g.fillRect(500, 225, 50, 50);
g.fillRect(550, 175, 50, 50);
g.fillRect(600, 225, 50, 50);
g.fillRect(650, 175, 50, 50);
g.fillRect(700, 225, 50, 50);
g.fillRect(750, 175, 50, 50);
g.fillRect(800, 225, 50, 50);
g.fillRect(850, 175, 50, 50);
g.fillRect(900, 225, 50, 50);
g.fillRect(950, 175, 50, 50);
g.fillRect(1000, 225, 50, 50);
g.fillRect(1050, 175, 50, 50);
g.fillRect(1100, 225, 50, 50);
g.fillRect(1150, 175, 50, 50);
g.fillRect(1200, 225, 50, 50);
g.fillRect(1250, 175, 50, 50);
g.fillRect(1300, 225, 50, 50);
g.fillRect(1350, 175, 50, 50);
g.fillRect(1400, 225, 50, 50);
g.fillRect(1450, 175, 50, 50);
g.fillRect(1500, 225, 25, 50);
g.setColor(new Color(255, 255, 255));
g.fillRect(380, 0, 20, 1100);
g.fillRect(1525, 0, 20, 1100);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(racecar.getImage(), racecar.getX(),
racecar.getY(), this);
}
#Override
public void actionPerformed(ActionEvent e) {
step();
}
private void step() {
racecar.move();
repaint(racecar.getX()-1, racecar.getY()-1,
racecar.getWidth()+2, racecar.getHeight()+2);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
racecar.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
racecar.keyPressed(e);
}
}
}
The third:
package gameproject;
import java.awt.EventQueue;
import javax.swing.JFrame;
public final class CarMovement3 extends JFrame {
public CarMovement3() {
InitUI();
}
private void InitUI() {
add(new CarMovement2());
setTitle("Top Speed Triumph");
setSize(1900, 1100);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
CarMovement3 ex = new CarMovement3();
ex.setVisible(true);
});
}
}
And the link to the sprite :
http://www.clker.com/clipart-red-sports-car-top-view.html
So, your problem stems from using...
repaint(racecar.getX() - 1, racecar.getY() - 1,
racecar.getWidth() + 2, racecar.getHeight() + 2);
Basically, you're not covering enough of the "existing" area that use to occupy to completely "remove" it.
You can simply use repaint() instead and it will solve your basic problem. I'd avoid worrying about this level of optimisation until it actually becomes a problem.
If you want to use it, then I would take a snap shot of the location of the care before it was moved (ie grab it's current x/y position) and merge that with it's new location so you cover both areas. That, or call repaint(x, y, width, height) twice, once with the old position and once with the new
private void step() {
Rectangle old = new Rectangle(racecar.getX(), racecar.getY(), racecar.getWidth(), racecar.getHeight());
racecar.move();
Rectangle now = new Rectangle(racecar.getX(), racecar.getY(), racecar.getWidth(), racecar.getHeight());
repaint(old);
repaint(now);
}
Also, you'll find that KeyListener is unreliable, I would suggest making use of the key bindings API which will solve the issues which KeyListener suffers from
I would also recommend using ImageIO over ImageIcon as more reliable way of loading your images, see Reading/Loading an Image for more details

ActionListener only responding once

I have created a basic Roulette wheel in Java, and I have a JButton with an ActionListener that spins the wheel. Once I have pressed the button once, it works as intended.
The problem is: Once I press the JButton a second time, it no longer works. I will post my entire code, for anyone who wants to see exactly what I mean.
Bonus Points: Bonus points to whoever can help me with the following things:
Buttons don't appear until after you have either clicked them, or put the window in the background and brought it back up.
For some reason, the spin ALWAYS lands on red. I have a method called randomSpin() which produces an int that is either 21 or 22, and that method DOES work, but for some reason when it's used in the spin method , it always spins 21 times.
WheelBuilder
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.lang.*;
public class WheelBuilder extends JApplet{
public int total = 1000, score, Tbet = 100, last;
public JLabel winning;
public JButton spin, Abet, Sbet;
RouletteWheel wheel = new RouletteWheel();
Graphics page;
public Color color;
public void init()
{
resize(540,600);
spin = new JButton("SPIN!");
spin.addActionListener(new spinListener());
Container cp = getContentPane();
cp.setVisible(true);
cp.setBackground((Color.GREEN).darker().darker());
Abet = new JButton("+BET+");
Abet.addActionListener(new aListener());
Sbet = new JButton("-BET-");
Sbet.addActionListener(new sListener());
cp.add(Sbet);
cp.add(spin);
cp.add(Abet);
cp.setLayout(new FlowLayout(270, 5, 525));
}
public void paint(Graphics page)
{
page.setColor((Color.GREEN).darker().darker());
page.fillRect(0, 0, 1000, 1000);
setBackground((Color.GREEN).darker().darker());
wheel.paintWheel(page, wheel.getStatus());
page.setColor(Color.BLACK);
page.drawString("TOTAL: "+total, 400, 50);
page.drawString("Current Bet: "+Tbet, 400, 25);
page.drawString("Last Spin:", 50, 25);
page.setColor(Color.WHITE);
page.fillOval(260, 75, 20, 20);
page.fillRect(50, 35, 60, 25);
page.setColor(color);
page.drawString(""+last, 70, 52);
}
public class spinListener implements ActionListener
{
Timer tm = new Timer(100, this);
int count = 0;
int countEnd = randomSpin();
public void actionPerformed(ActionEvent e)
{
tm.start();
changeWheel();
if (wheel.getStatus())
{
color = Color.RED;
last = (int)(Math.random()*7)*2+1;
}
else
{
color = Color.BLACK;
last = (int)(Math.random()*7)*2+2;
}
}
public void changeWheel()
{
int countEnd = randomSpin();
if (count <= countEnd)
{
wheel.setStatus(!(wheel.getStatus()));
repaint();
count++;
}
}
public int randomSpin()
{
return ((int)(Math.random()*2)+21);
}
}
public class aListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet <= total-50)
{
Tbet+=50;
}
last = 0;
repaint();
}
}
public class sListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet > 50)
{
Tbet-=50;
}
last = 0;
repaint();
}
}
}
RouletteWheel
import javax.swing.JApplet;
import java.awt.*;
public class RouletteWheel extends JApplet {
public boolean status;
public void paintWheel(Graphics page, boolean status)
{
if (status){
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.BLACK);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.setColor(Color.RED);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
if (!status)
{
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.RED);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
}
public boolean getStatus()
{
return status;
}
public void setStatus(boolean s)
{
status = s;
}
}

Java Painting problems

I'm trying to make a simulation on our school's enrollment system. But I'm stuck on a problem that i can't figure out why, the box that i rendered are blinking. I need it not to. can you help me? thanks.
import java.awt.Color;
import java.awt.*;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates and open the template
* in the editor.
*/
/**
*
* #author paolo
*/
public class simulator extends JPanel {
Thread tr;
Image i;
Graphics gbfr;
Dimension size;
int num = 0, check, wid, hyt, oq;
Random rand = new Random();
Dimension locs[];
list waiting, queue;
boolean allowMove = false;
simulator(int w, int h) {
oq = 0;
wid = w;
hyt = h;
tr = new tr1();
locs = new Dimension[30];
waiting = new list(50);
queue = new list(30);
int tw, u;
for (u = 0, tw = 64; u < 10; u++, tw += 55) {
locs[u] = new Dimension(tw, 275);
locs[19 - u] = new Dimension(tw, 325);
locs[u + 20] = new Dimension(tw, 375);
}
}
public void paint(Graphics g) {
i = createImage(getWidth(), getHeight());
gbfr = i.getGraphics();
gbfr.setColor(getBackground());
gbfr.fillRect(0, 0, getWidth(), getHeight());
gbfr.setColor(getForeground());
paintComponent(gbfr);
g.drawImage(i, 0, 0, this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
drawSettings(g);
drawStudents(g);
}
protected void drawSettings(Graphics g) {
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
}
protected void drawStudents(Graphics g) {
waiting.drawStudents(g);
}
public class tr1 extends Thread implements Runnable {
public void run() {
for (check = 0;; check++) {
num++;
try {
if (num % 100 == 0 && waiting.max != waiting.countL) {
waiting.add();
}
repaint();
Thread.sleep(1);
} catch (InterruptedException e) {
}
//repaint();
}
}
}
public class list {
int max, countL;
students temp, head;
list() {
head = new students();
countL = 0;
head.setNext(null);
max = 0;
}
list(int m) {
countL = 0;
head = new students(1);
list();
max = m;
head.setNext(null);
}
void add() {
students t;
t = head;
if (countL == 0) {
countL++;
t.setNext(new students());
} else {
temp = head.getNext();
while (temp != null) {
temp = temp.getNext();
}
countL++;
head.setNext(new students());
//updateCount();
}
}
void delete(int c) {
students t = head, t1;
int aa = 1;
if (countL == 1) {
if (c == 1) {
t.setNext(null);
}
} else {
if (c == 1) {
t.setNext(t.getNext());
} else {
for (t = t.getNext(); aa < c; aa++, t = t.getNext()) {
}
t.setNext(t.getNext().getNext());
}
}
}
void updateCount() {
students t = new students();
t = head;
t = t.getNext();
System.out.println(countL + "__");
for (int q = 1; q < countL; q++) {
System.out.println(t);
t.setCount(q);
t = t.getNext();
}
}
void drawStudents(Graphics g) {
students t = head;
if (countL != 0) {
t = t.getNext();
while (t != null) {
g.setColor(t.getClr());
g.fillRect(t.xpos, t.ypos, 10, 10);
t = t.getNext();
}
}
}
}
public class students {
int xpos, ypos, year, level, servtime, waittime, pos, destx, desty, count;
Color clr;
boolean active, onq;
students next;
students() {
//System.out.print("Recieved");
xpos = rand.nextInt((wid - 580) + 1) + 580;
onq = false;
ypos = rand.nextInt((hyt - 280) + 1) + 280;
waittime = rand.nextInt((100 - 50) + 1) + 50;
servtime = rand.nextInt((200 - 100) + 1) + 100;
count = 0;
level = 0;
next = null;
year = rand.nextInt((4 - 1) + 1) + 1;
clr = new Color(12, 12, 12);
if (year == 1) {
clr = Color.GREEN;
} else if (year == 2) {
clr = Color.YELLOW;
} else if (year == 3) {
clr = Color.RED;
} else {
clr = Color.BLUE;
}
pos = 0;
active = false;
}
students(int i) {
count = 0;
}
void setxpos(int x) {
xpos = x;
}
void setypos(int y) {
ypos = y;
}
void setpos(int p) {
pos = p;
}
void setCount(int q) {
count = q;
}
students getNext() {
return next;
}
Color getClr() {
return clr;
}
void setNext(students n) {
next = n;
}
int getpos() {
return pos;
}
boolean isActive() {
return active;
}
void activate() {
active = true;
}
}
}
Don't override the simulator JPanel's paint(Graphics g) method
Don't call paintComponent directly. You mess with all of Swing's graphics by doing these two things.
Draw your stable background image to a BufferedImage, and then draw the image in your JPanel's paintComponent(Graphics g) method.
Note that your code does not reproduce your problem for me. I don't see any blinking. Should there be some animation going on that we're not seeing?
e.g.,
// class names should begin with an upper-case letter
public class Simulator extends JPanel {
// ....
private BufferedImage settings = null;
Simulator(int w, int h) {
// ....
settings = createSettings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(wid, hyt);
}
// public void paint(Graphics g) {
// i = createImage(getWidth(), getHeight());
// gbfr = i.getGraphics();
// gbfr.setColor(getBackground());
// gbfr.fillRect(0, 0, getWidth(), getHeight());
//
// gbfr.setColor(getForeground());
// paintComponent(gbfr);
//
// g.drawImage(i, 0, 0, this);
// }
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
if (settings != null) {
g.drawImage(settings, 0, 0, this);
}
// !! drawSettings(g);
drawStudents(g);
}
private BufferedImage createSettings() {
int width = 700;
int height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
g.dispose();
return img;
}
// ...
}

my keyPressed function isn't being called

I'm working on a school assignment in which I need to make a JComponent that makes some objects (defined in my Player Class) move around. In order to do this I need to use the keyPressed function of the KeyListener Interface but I can't get my program to call it. This I know because the println at the beginning of keyPressed doesn't print when I press keys.
Following is the relevant code.
BackgroundMain.java
package edu.hiram.cs.cpsc172;
import java.awt.Color;
import javax.swing.JFrame;
/**
*
* #author tricksimon
* Class that creates the JFrame, and gives instructions for the frame.
*/
public class BackgroundMain {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Learned in Stackoverflow
frame.setTitle("Game Background");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BackgroundComponent background = new BackgroundComponent();
frame.add(background);
frame.setVisible(true);
}
}
BackgroundComponent.java
package edu.hiram.cs.cpsc172;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.Polygon;
import javax.swing.JComponent;
/**
*
* #author Simonpj
* Class that makes the many parts of the background.
*/
public class BackgroundComponent extends JComponent implements KeyListener {
private long lastTime;
private int upArrow;
private int downArrow;
private int enterKey;
private int leftArrow;
private int rightArrow;
private int spaceKey;
private Player player;
public BackgroundComponent(){
player = new Player(200, 200, Color.BLUE);
setFocusable(true);
requestFocus();
}
public void paintComponent(Graphics g) {
upArrow=38;
downArrow = 40;
enterKey = 10;
leftArrow = 37;
rightArrow = 39;
spaceKey = 32;
Graphics2D g2 = (Graphics2D) g;
g2.setBackground(Color.yellow);
//Grass for the scene
Rectangle box = new Rectangle(0, 528, 2000, 1000);
g2.draw(box);
Color green = new Color(0, 255, 0);
g2.setColor(Color.green);
g2.fill(box);
//Rectangle representing the sky
Rectangle box1 = new Rectangle(0, 0, 2000, 530);
Color cyan = new Color(0, 255, 255);
g2.setColor(Color.cyan);
g2.draw(box1);
g2.fill(box1);
//Rectangle representing the house
Rectangle box2 = new Rectangle(0, 530, 600, 500);
g2.draw(box2);
g2.setColor(Color.black);
g2.fill(box2);
//Rectangle representing the door of the house
Rectangle box3 = new Rectangle(265, 650, 80, 150);
g2.draw(box3);
Color brown = new Color(139, 69, 19);
g2.setColor(brown);
g2.fill(box3);
//Ellipse representing the door knob
Ellipse2D.Double ellipse1 = new Ellipse2D.Double(330, 710, 10, 10);
g2.draw(ellipse1);
g2.setColor(Color.black);
g2.fill(ellipse1);
//Ellipse representing the sun
Ellipse2D.Double ellipse = new Ellipse2D.Double(1320, -20, 150, 150);
g2.setColor(Color.yellow);
g2.draw(ellipse);
g2.fill(ellipse);
//Create a polygon for the roof of the house
int[] xCoords = new int[]{0, 300, 600};
int[] yCoords = new int[]{530, 5, 530};
Polygon poly = new Polygon(xCoords, yCoords, 3);
g2.setColor(brown);
g2.fillPolygon(poly);
//Windows
Rectangle box4 = new Rectangle(100, 600, 70, 70);
g2.draw(box4);
g2.setColor(Color.blue);
g2.fill(box4);
Rectangle box5 = new Rectangle(126, 600, 15, 71);
g2.setColor(Color.black);
g2.draw(box5);
g2.fill(box5);
Rectangle box6 = new Rectangle(100, 628, 70, 15);
g2.setColor(Color.black);
g2.draw(box6);
g2.fill(box6);
Rectangle box7 = new Rectangle(450, 600, 70, 70);
g2.draw(box7);
g2.setColor(Color.blue);
g2.fill(box7);
Rectangle box8 = new Rectangle(476, 600, 15, 71);
g2.setColor(Color.black);
g2.draw(box8);
g2.fill(box8);
Rectangle box9 = new Rectangle(450, 628, 70, 15);
g2.setColor(Color.black);
g2.draw(box9);
g2.fill(box9);
// Drawing a car
//Main Car
Rectangle box10 = new Rectangle(750, 655, 300, 100);
g2.setColor(Color.blue);
g2.draw(box10);
g2.fill(box10);
Rectangle box11 = new Rectangle(830, 620, 150, 50);
g2.draw(box11);
g2.fill(box11);
//Wheels
Ellipse2D.Double ellipse2 = new Ellipse2D.Double(795, 725, 50, 50);
g2.setColor(Color.black);
g2.draw(ellipse2);
g2.fill(ellipse2);
Ellipse2D.Double ellipse3 = new Ellipse2D.Double(950, 725, 50, 50);
g2.setColor(Color.black);
g2.draw(ellipse3);
g2.fill(ellipse3);
Ellipse2D.Double ellipse4 = new Ellipse2D.Double(963, 738, 25, 25);
g2.setColor(Color.white);
g2.draw(ellipse4);
g2.fill(ellipse4);
Ellipse2D.Double ellipse5 = new Ellipse2D.Double(807.5, 738, 25, 25);
g2.setColor(Color.white);
g2.draw(ellipse5);
g2.fill(ellipse5);
//Text for the background
Font courierBold20 = new Font("Courier", Font.BOLD, 20);
g2.setColor(Color.black);
g2.setFont(courierBold20);
g2.drawString("My Game Background", 650, 270);
UFO u = new UFO(320,240, Color.BLUE);
u.draw(g2);
UFO u1 = new UFO(60,30, Color.RED);
u1.draw(g2);
UFO u2 = new UFO(900,180, Color.magenta);
u2.draw(g2);
Player p = new Player(700, 644, Color.DARK_GRAY);
p.draw(g2);
Player p1 = new Player(390, 644, Color.DARK_GRAY);
p1.draw(g2);
player.draw(g2);
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("check");
if (e.getKeyCode() == upArrow){
player.increaseSize();
}
if (e.getKeyCode() == downArrow){
player.decreaseSize();
}
if (e.getKeyCode() == enterKey){
player.resetSize();
}
if (e.getKeyCode() == leftArrow){
player.moveLeft();
}
if (e.getKeyCode() == rightArrow){
player.moveRight();
}
if (e.getKeyCode() == spaceKey){
player.newColor();
}
player.move(e.getKeyCode());
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Player.java
package edu.hiram.cs.cpsc172;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.util.Random;
/**
*
* #author Simonpj
* Class that creates a player.
*/
public class Player {
private int x;
private int y;
private Color userColor;
private double size;
private Random rand;
/**
* Constructor for the Player class
* #param x X Coordinate for Player
* #param y Y Coordinate for Player
* #param userColor Color of the Player
*/
public Player(int x, int y, Color userColor) {
this.x=x;
this.y=y;
this.userColor=userColor;
this.size=1.0;
this.rand = new Random();
}
/**
* Draws the Player
* #param g Graphics object
*/
public void draw(Graphics2D g) {
Graphics2D g2 = (Graphics2D)g;
g2.scale(size, size);
//Body
Rectangle rect = new Rectangle(x, y, 45, 75);
g2.setColor(userColor);
g2.fill(rect);
g2.draw(rect);
//Head
Ellipse2D.Double ellipse = new Ellipse2D.Double(x + 4, y - 35, 35, 35);
g2.setColor(Color.WHITE);
g2.fill(ellipse);
//Leg
Rectangle rect1 = new Rectangle(x + 12, y + 76, 20, 45);
g2.setColor(Color.WHITE);
g2.fill(rect1);
g2.draw(rect1);
//Arms
Rectangle rect3 = new Rectangle(x + 16, y + 15, 13, 45);
g2.setColor(Color.WHITE);
g2.fill(rect3);
g2.draw(rect3);
//reset scale
g2.scale(1.0/size, 1.0/size);
}
public void changeColor(Color color) {
userColor=color;
}
public void move(int keyPressed) {
System.out.println(keyPressed); //comment out this line once you know the ints for the keys you need
}
public void increaseSize() {
size*=1.1;
}
public void decreaseSize() {
size*=0.9;
}
public void resetSize() {
size = 1.0;
}
public void moveLeft() {
//poly.translate(-2,0);
this.x -= 2;
}
public void moveRight() {
//poly.translate(2,0);
this.x += 2;
}
public void newColor() {
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
userColor = randomColor;
}
}
I don't see that you're ever calling addKeyListener inside BackgroundComponent. You need to do that in order for the keyPressed method to get called.
You must add your object as a keyListener, likely in the constructor:
addKeyListener(this);

Why isn't this keyListener Working? How can i get it to work?

So I have my keyListener called TAdapter. For some reason i can't get this to work right. I have set the focus to the panel and it still doesnt work. I have searched and searched the web and found absolutely nothing on why this isn't working correctly. I'm new to java and completely stumped
import java.awt.*;
import javax.swing.JPanel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.TimerTask;
import java.util.Timer;
import java.awt.Toolkit;
public class Game extends JPanel implements Shared{
private static Brick bricks[];
private static Ball ball;
private static Paddle paddle;
Timer timer;
public Game(){
super();
this.addKeyListener(new TAdapter());
this.setFocusable(true);
this.requestFocusInWindow();
setSize(Shared.WIDTH, Shared.HEIGHT);
bricks = new Brick[100];
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), 1000, 10);
}
public void addNotify(){
super.addNotify();
gameInit();
}
public static void gameInit(){
ball = new Ball();
paddle = new Paddle();
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.GREEN, true);
int k = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
switch(i){
case 0:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 255), true);
break;
case 1:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 20, 127), true);
break;
case 2:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 0), true);
break;
case 3:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 127, 0), true);
break;
case 4:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 255, 0), true);
break;
case 5:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 0), true);
break;
case 6:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 127), true);
break;
case 7:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 127, 255), true);
break;
case 8:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 0, 255), true);
break;
case 9:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(127, 0, 255), true);
break;
}
bricks[k] = new Brick((j*BRICK_WIDTH) + (j*BRICK_SEP), (i*BRICK_HEIGHT) + BRICK_Y_OFFSET+(i*BRICK_SEP), gp);
k++;
}
}
}
public void paint(Graphics g){
super.paint(g);
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.RED, true);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gp);
g2.fillOval(ball.getX(), ball.getY(), BALL_RADIUS, BALL_RADIUS);
g2.fillRoundRect((Shared.WIDTH/2) - PADDLE_WIDTH/2, Shared.HEIGHT - PADDLE_Y_OFFSET*2, PADDLE_WIDTH, PADDLE_HEIGHT, 3, 3);
for(int i = 0; i< 100; i++){
if(!bricks[i].isDestroyed()){
g2.setPaint(bricks[i].getPaint());
g2.fillRoundRect(bricks[i].getX(), bricks[i].getY(), bricks[i].getWidth(), bricks[i].getHeight(), 5, 5);
}
}
Toolkit.getDefaultToolkit().sync();
g2.dispose();
}
private class TAdapter extends KeyAdapter{
public void keyReleased(KeyEvent e){
paddle.keyReleased(e);
}
public void keyPressed(KeyEvent e){
paddle.keyPressed(e);
}
}
class ScheduleTask extends TimerTask{
public void run(){
ball.move();
paddle.move();
checkCollision();
repaint();
}
}
public void stopGame(){
timer.cancel();
}
public void checkCollision() {
if (ball.getRect().getMaxY() > Shared.HEIGHT) {
stopGame();
}
for (int i = 0, j = 0; i < 100; i++) {
if (bricks[i].isDestroyed()) {
j++;
}
if (j == 100) {
stopGame();
}
}
if ((ball.getRect()).intersects(paddle.getRect())) {
int paddleLPos = (int)paddle.getRect().getMinX();
int ballLPos = (int)ball.getRect().getMinX();
int first = paddleLPos + 8;
int second = paddleLPos + 16;
int third = paddleLPos + 24;
int fourth = paddleLPos + 32;
if (ballLPos < first) {
ball.setXDir(-1);
ball.setYDir(-1);
}
if (ballLPos >= first && ballLPos < second) {
ball.setXDir(-1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos >= second && ballLPos < third) {
ball.setXDir(0);
ball.setYDir(-1);
}
if (ballLPos >= third && ballLPos < fourth) {
ball.setXDir(1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos > fourth) {
ball.setXDir(1);
ball.setYDir(-1);
}
}
for (int i = 0; i < 100; i++) {
if ((ball.getRect()).intersects(bricks[i].getRect())) {
int ballLeft = (int)ball.getRect().getMinX();
int ballHeight = (int)ball.getRect().getHeight();
int ballWidth = (int)ball.getRect().getWidth();
int ballTop = (int)ball.getRect().getMinY();
Point pointRight =
new Point(ballLeft + ballWidth + 1, ballTop);
Point pointLeft = new Point(ballLeft - 1, ballTop);
Point pointTop = new Point(ballLeft, ballTop - 1);
Point pointBottom =
new Point(ballLeft, ballTop + ballHeight + 1);
if (!bricks[i].isDestroyed()) {
if (bricks[i].getRect().contains(pointRight)) {
ball.setXDir(-1);
}
else if (bricks[i].getRect().contains(pointLeft)) {
ball.setXDir(1);
}
if (bricks[i].getRect().contains(pointTop)) {
ball.setYDir(1);
}
else if (bricks[i].getRect().contains(pointBottom)) {
ball.setYDir(-1);
}
bricks[i].setDestroyed(true);
}
}
}
}
}`
then here is the main
import javax.swing.*;
public class BreakOut extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
static Game game =new Game();
public BreakOut()
{
add(game);
setTitle("Breakout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(Shared.WIDTH, Shared.HEIGHT);
setResizable(false);
setVisible(true);
setIgnoreRepaint(true);
}
public static void main(String arg[]){
new BreakOut();a
}
}
Your key listener just sends the events to paddle.
You might want to include the code (or at least look in the code) for paddle.keyPressed(e) and paddle.keyReleased(e); but really, you probably shouldn't have your paddle object handling the keys directly. It is nice to translate your key presses to in-game meaningful calls, like paddle.moveUp() or something.
Im not sure where the shared interface comes from/does, but try implementing KeyListener. "Public class Game extends JPanel implements Shared, KeyListner" if you keep using the shared but like i said idk what its purpose is or what it does right off the top of my head.

Categories

Resources