How to send and resend back fxml object - java

I'd like to take Pane object from controller class to another class called Wykres in my case, then add to it children for example Circle's objects, but when I try to generate circles by clicking button there is no circles, can someone help me? Thanks.
public class Controller {
#FXML
public Label label_x_waga;
#FXML
Label label_y_waga;
#FXML
Pane root_pane;
#FXML
Button button_add;
private static Pane panee;
private SiecNeuronowa siecNeuronowa;
public void initialize(){
siecNeuronowa = new SiecNeuronowa();
panee=root_pane;
}
public static Pane getPane(){
return panee;
}
#FXML
public void button_add_action(){
root_pane = Wykres.getPane_root();
for(int i=0;i<300;i++)
siecNeuronowa.dodajPunkt();
}
}
And the Wykres class
public class Wykres {
private int xWartosc, yWartosc;
private String kolor;
private static Pane pane_root;
public void rysujPunkt(Pane root, int x, int y, String color){
x+=180;
y+=180;
xWartosc = x;
yWartosc = y;
this.kolor = color;
if(color.equals("NIEBIESKI")){
root.getChildren().add(new Circle(x, y, 5, Color.BLUE));
}
else if(color.equals("CZERWONY")){
root.getChildren().add(new Circle(x, y, 5, Color.RED));
}
pane_root = root;
}
public static Pane getPane_root(){return pane_root;}
}
rysujPunkt() method is invoked here:
public class SiecNeuronowa {
private Perceptron perceptron1;
private Wykres wykres1;
public SiecNeuronowa(){
wykres1 = new Wykres();
perceptron1 = new Perceptron(){
#Override
public double finalizuj_dane(double potencjalMembranowy){
if(potencjalMembranowy>0)
return 1;
else
if(potencjalMembranowy<0)
return -1;
else
return 0;
}
};
perceptron1.dodajWejscia(2);
Random random = new Random();
double rand_x = random.nextDouble();
double rand_y = random.nextDouble();
perceptron1.setWagaWejsciowa(0, rand_x);
perceptron1.setWagaWejsciowa(1, rand_y);
}
public void dodajPunkt(){
Random random = new Random();
int x = random.nextInt()*150;
int y = random.nextInt()*150;
perceptron1.setDaneWejsciowe(0, x);
perceptron1.setDaneWejsciowe(1, y);
int wynik = (int)perceptron1.getWyjscie();
if(wynik == 1)
wykres1.rysujPunkt(Controller.getPane(), x, y, "Niebieski");
else
if(wynik == -1)
wykres1.rysujPunkt(Controller.getPane(), x, y, "Czerwony");
}
}

Related

How to return Instance Variables for objects in an array

I am new to graphics in java and I am currently working on a game. Essentially, there are rising bubbles, and the user has to pop them by moving the mouse over them.
I have already made the bubbles but now for the collision detection, I need to be able to find the x and coordinates as well as the diameter of the circle. How can I return the instance variables for each bubble (from the Bubbles object array). You can see my code below. If you find coding errors, please let me know.
Game Class:
public class Game extends JPanel{
public static final int WINDOW_WIDTH = 600;
public static final int WINDOW_HEIGHT = 400;
private boolean insideCircle = false;
private static boolean ifPaused = false;
private static JPanel mainPanel;
private static JLabel statusbar;
private static int clicks = 0;
//Creates a Bubbles object Array
Bubbles[] BubblesArray = new Bubbles[5];
public Game() {
//initializes bubble objects
for (int i = 0; i < BubblesArray.length; i++)
BubblesArray[i] = new Bubbles();
}
public void paint(Graphics graphics) {
//makes background white
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
//paints square objects to the screen
for (Bubbles aBubblesArray : BubblesArray) {
aBubblesArray.paint(graphics);
}
}
public void update() {
//calls the Square class update method on the square objects
for (Bubbles aBubblesArray : BubblesArray) aBubblesArray.update();
}
public static void main(String[] args) throws InterruptedException {
statusbar = new JLabel("Default");
Game game = new Game();
game.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
statusbar.setText(String.format("Your mouse is at %d, %d", e.getX(), e.getY()));
}
public void mouseExited(MouseEvent e){
ifPaused = true;
}
public void mouseEntered(MouseEvent e){
ifPaused = false;
}
});
JFrame frame = new JFrame();
frame.add(game);
frame.add(statusbar, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Bubble Burst");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
while (true) {
if (!ifPaused){
game.update();
game.repaint();
Thread.sleep(5);
}
}
}
}
Bubbles Class:
public class Bubbles{
private int circleXLocation;
private int circleSize;
private int circleYLocation = Game.WINDOW_WIDTH + circleSize;
private int fallSpeed = 1;
private int color = (int) (4 * Math.random() + 1);
Random rand = new Random();
private int whereMouseX;
private int whereMouseY;
public int generateRandomXLocation(){
return circleXLocation = (int) (Game.WINDOW_WIDTH * Math.random() - circleSize);
}
public int generateRandomCircleSize(){
return circleSize = (int) (50 * Math.random() + 30);
}
public int generateRandomFallSpeed(){
return fallSpeed = (int) (5 * Math.random() + 1);
}
public void paint(Graphics g){
if (color == 1) g.setColor(new Color(0x87CEEB));
if (color == 2) g.setColor(new Color(0x87CEFF));
if (color == 3) g.setColor(new Color(0x7EC0EE));
if (color == 4) g.setColor(new Color(0x6CA6CD));
g.fillOval (circleXLocation, circleYLocation, circleSize, circleSize);
}
public Bubbles(){
generateRandomXLocation();
generateRandomCircleSize();
generateRandomFallSpeed();
}
public void update(){
if (circleYLocation <= - circleSize){
generateRandomXLocation();
generateRandomFallSpeed();
generateRandomCircleSize();
circleYLocation = Game.WINDOW_HEIGHT + circleSize;
}
if (circleYLocation > - circleSize){
circleYLocation -= fallSpeed;
}
}
public int getX(){
return circleXLocation;
}
public int getY(){
return circleYLocation;
}
public int getCircleSize(){
return circleSize;
}
}
Set your bubbles to include x and y values in it's constructor.
Public Bubble(float x, float y, int circleSize){
// initialize variables here
}
Then check to see if they are colliding with your current mouse location, something like...
if(e.getX() == this.getX() && e.getY() == this.getY()){
// do something
}
Loop through each Bubble in the array and access the public get methods you have created in the Bubble class:
Example:
for (Bubble b : BubblesArray)
{
int x = b.getX();
int y = b.getY();
}

Random Level Generation with LibGDX

I have made a class for the level generation and have got so far with it:
public class LevelGenerator {
private Sprite environment;
private float leftEdge, rightEdge, minGap, maxGap, y;
public Enemy enemy;
public LevelGenerator(Sprite environment, float leftEdge, float rightEdge,
float minGap, float maxGap) {
this.environment = environment;
this.leftEdge = leftEdge;
this.rightEdge = rightEdge;
this.minGap = minGap;
this.maxGap = maxGap;
}
public void generate(float topEdge){
if(y + MathUtils.random(minGap, maxGap) < topEdge)
return;
y = topEdge;
float x = MathUtils.random(leftEdge, rightEdge);
}
Basically, what I want to happen is for the enemy block to randomly generate on the sides of the screen. Here is the enemy block class (very simple):
public class Enemy extends Sprite{
public Enemy(Sprite sprite) {
super(sprite);
}
#Override
public void draw(Batch spriteBatch){
super.draw(spriteBatch);
}
}
This is what the game looks like at the moment when the block is just simply drawn on the game screen in a static position: http://i.imgur.com/SIt18Qn.png. What I am trying to achieve is for these "enemy" blocks to spawn randomly on either side of the screen but I can't seem to figure out a way to do it with the code I have so far.
Thank you!
I could not test but I think it will be fine, you have a rectangle if you want to see if it collides with another actor, if so updates its position in the update and draw method, and ramdon method start customizing to see if the coordinates, which colicionan be assigned to another actor rectagulo enemy or bye.
public class overFlowEnemy extends Sprite {
private final float maxH = Gdx.graphics.getHeight();
private final float maxW = Gdx.graphics.getWidth();
private Rectangle rectangle;
private Random random = new Random();
private float inttt = 0;
private float randomN = 0;
private boolean hasCollided = false;
public overFlowEnemy(Sprite sprite) {
super(sprite);
crearEnemigo();
rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());
}
#Override
public void draw(Batch spriteBatch) {
super.draw(spriteBatch);
}
private void crearEnemigo(){
setX(RandomNumber((int)maxW));
setY(RandomNumber((int)maxH));
}
private int RandomNumber(int pos) {
random.setSeed(System.nanoTime() * (long) inttt);
this.randomN = random.nextInt(pos);
inttt += randomN;
return (int)randomN;
}
public Rectangle getColliderActor(){
return this.rectangle;
}
}
the class as this should create a random enemy.
Edit: rereading your question, is that my English is not very good, and I think you wanted to be drawn only on the sides of the screen if so, tell me or adapts the class because when you create thought, which was across the screen.
I just added another class, if you can and want to work as you tell me which is correct, and delete the other.
public class overFlow extends Sprite {
private final float maxH = Gdx.graphics.getHeight();
private final float maxW = Gdx.graphics.getWidth();
private Rectangle rectangle;
private Random random = new Random();
private float inttt = 0;
private float randomN = 0;
private boolean hasCollided = false;
public overFlow(Sprite sprite) {
super(sprite);
crearEnemigo();
rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());
}
#Override
public void draw(Batch spriteBatch) {
super.draw(spriteBatch);
}
private void crearEnemigo(){
setX(RandomNumber((int)maxW, true));
setY(RandomNumber((int)maxH, false));
}
private int RandomNumber(int pos, boolean w) {
random.setSeed(System.nanoTime() * (long) inttt);
if (w = true){
this.randomN = random.nextInt((pos));
if(randomN % 2 == 0){
randomN = (pos - getWidth());
}else{
randomN = 0; //left screen
}
}else{
this.randomN = random.nextInt(pos - (int)getHeight());
}
inttt += randomN;
return (int)randomN;
}
public Rectangle getColliderActor(){
return this.rectangle;
}
}

Use Timer class to call move()

ok so I created a method that randomly moves an enemy icon, and I used a Swing timer to make it constantly repeat and update every second or so, but the problem is the icon isn't moving it's just staying at the position, I added a print method to display my random numbers, and they are being created and displayed properly, but my enemy is not moving, any help is greatly appreciated :) and the ImageIcon for the bluespell class is a method that jus returns a regular ImageIcon there's nothing wrong with that method ha
public class BlueSpell extends WizardBattleGrid{
private int BlueSpellx;
private static int BlueSpelly;
private ImageIcon Blue;
WizardBattleRunner wbr = new WizardBattleRunner();
Timer timer;
public BlueSpell(int x, int y, ImageIcon BlueSpell){
BlueSpellx = x;
BlueSpelly = y;
Blue = BlueSpell;
}
public int getx(){
return BlueSpellx;
}
public int gety(){
return BlueSpelly;
}
public ImageIcon getIcon(){
return Blue;
}
public int changex(int x){
BlueSpellx = x;
return x;
}
public int changey(int y){
BlueSpelly = y;
return y;
}
public void shootSpell(){
final BlueSpell b = new BlueSpell(GoodGuy.getx(), GoodGuy.gety() +1, BlueSpellWizard());
int delay = 60;
timer = new Timer(delay,new ActionListener(){
public void actionPerformed(ActionEvent e){
if(b.gety() != 19){
WizardCells[b.getx()][b.gety()].setIcon(null);
WizardCells[b.getx()][b.changey(b.gety()+1)].setIcon(b.getIcon());
}
else{
WizardCells[b.getx()][b.gety()].setIcon(null);
b.changex(GoodGuy.getx());
b.changey(GoodGuy.gety() +1);
timer.stop();
}
}
});
timer.start();
}
}
WizardCells are in my Grid class here they are:
public class WizardBattleGrid extends GameWindowWizard {
public static JLabel[][] WizardCells = new JLabel [20][20];
public static JPanel WizardPanel = new JPanel(new GridLayout(20, 20, 0, 0));
static BufferedImage cursorimage = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
static Cursor blankcursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorimage, new Point(0, 0), "blank cursor");
public static void CreateGrid(){
for(int i=0; i<WizardCells.length; i++ ){
for(int j=0; j<WizardCells[i].length; j++){
JLabel label = new JLabel();
WizardCells[i][j] = label;
}
}
for(int i=0; i<WizardCells.length; i++){
for(int j=0; j<WizardCells[i].length;j++){
WizardPanel.add(WizardCells[i][j]);
}
}
WizardCells[10][0].setIcon(GoodGuyWizardIcon());
WizardPanel.setOpaque(true);
WizardPanel.setBackground(Color.DARK_GRAY);
WizardPanel.setCursor(blankcursor);
gameWindow.add(WizardPanel);
}
}

How to refer ChangeListener of one class to another class?

I DISCARD ALL THESE CODE AND WORK ON TOTALLY DIFFERENT ONE>>>
NO NEED TO ANSWER ANYMORE
I got a homework from my professor. He told us to make applet paint program using 4 classes.
Main; LightSourcePanel;DrawingPanel;PalettePanel;
(The basic code are not giving; only the class)
The program will take Mouse input and draw circle when I make a circular line. And the circle will have a 'glowing effect' depend on the lightSource (Use JSlider as light). When the JSlider is slided, the circle glowing effect change real time.
I am having problem referring the LightSource event Listener to the Drawing so It change the 'int light' inside the DrawingPanel. I don't know why the refering in the JColorChooser work while this one don't.
(It gave me java "non-static method cannot be referenced from a static" and I can't change it to static since I need to call repaint() method )
This is my Third class assignment and professor just taught us basic action listener in a single class. So I have no idea what Am I doing. If possible please explain my mistake in detail.
Main code:
public class HW3_to_4 extends Applet {
public void init (){
Dimension d = this.getSize();
setLayout(new BorderLayout());
JPanel Pale = new PalettePanel();
Pale.setBorder(BorderFactory.createLineBorder(Color.black, 5));
JPanel Light = new LightSourcePanel();
Light.setBorder(BorderFactory.createLineBorder(Color.black, 5));
JPanel Draw = new DrawingPanel();
Cursor c = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
Draw.setCursor(c);
Draw.setBorder(BorderFactory.createLineBorder(Color.green, 3));
add(Pale, BorderLayout.SOUTH );
add(Light,BorderLayout.NORTH);
add(Draw,BorderLayout.CENTER);
}
}
PalettePanel Code:
class PalettePanel extends JPanel implements ChangeListener {
JColorChooser j;
public PalettePanel () {
j = new JColorChooser ();
j.setPreviewPanel(new JPanel());
j.getSelectionModel().addChangeListener(this);
this.add(j);
}
public void stateChanged (ChangeEvent e){
Color a = j.getColor();
DrawingPanel.changecolor (a);
}
}
DrawingPanel Code & sub class inside (DrawingCanvas and Polyline)
I rip this off from a example page in YAIP.
:
public class DrawingPanel extends JPanel {
private List<PolyLine> lines = new ArrayList<PolyLine>();
private static PolyLine currentline;
private int maxX,maxY,difX, difY,minX,minY;
private static int lightSource = 0;
public static final int CANVAS_WIDTH = 2000;
public static final int CANVAS_HEIGHT = 800;
public static int[][] circle = new int[1000][4];
public static int check = 0;
public static Color c = Color.RED;
public DrawingPanel(){
DrawingCanvas canvas = new DrawingCanvas();
Dimension d = new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT);
canvas.setPreferredSize(d);
canvas.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
currentline = new PolyLine();
currentline.line_color = c;
lines.add(currentline);
currentline.add(e.getX(), e.getY());
}
});
canvas.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentline.add(e.getX(), e.getY());
repaint();
}
});
canvas.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
for(int i = 0; i<currentline.xList.size()-1; i++){
if(maxX<currentline.xList.get(i)){
maxX = currentline.xList.get(i);
}
}
for(int i = 0; i<currentline.yList.size()-1; i++){
if(maxY<currentline.yList.get(i)){
maxY = currentline.yList.get(i);
}
}
minX = maxX;
for(int i = 0; i<currentline.xList.size()-1; i++){
if(minX>currentline.xList.get(i)){
minX = currentline.xList.get(i);
}
}
minY = maxY;
for(int i = 0; i<currentline.yList.size()-1; i++){
if(minY>currentline.yList.get(i)){
minY = currentline.yList.get(i);
}
}
difX = maxX - minX;
difY = maxY - minY;
currentline.addcircle(minX,minY, difX, difY);
circle[check][0] = minX;
circle[check][1] = minY;
circle[check][2] = difX;
circle[check][3] = difY;
check++;
repaint();
maxX = 0; difX = 0;
maxY = 0; difY = 0;
}
});
this.add(canvas);
}
public static void changecolor(Color b){
c = b;
}
public void lightChange (int light){
lightSource = light;
RE();
}
public void RE (){
for (int x = 0; x< check ; x++) currentline.addcircle(circle[x][0],circle[x][1], circle[x][2],circle[x][3],lightSource);
repaint();
}
private class DrawingCanvas extends JPanel{
public void paint(Graphics g){
for(PolyLine line : lines){
g.setColor(line.line_color);
line.draw(g);
}
}
}
static class PolyLine{
public Color line_color = Color.RED;
private List <Integer> xList;
private List <Integer> yList;
boolean drawcircle = false;
int minx, miny, difx, dify, light;
public PolyLine() {
xList = new ArrayList<Integer>();
yList = new ArrayList<Integer>();
}
public void add(int x, int y){
xList.add(x);
yList.add(y);
}
public void addcircle(int x, int y, int difx, int dify){
this.minx = x; this.miny = y; this.difx = difx; this.dify = dify;
drawcircle = true;
}
public void addcircle(int x, int y, int difx, int dify, int light){
this.minx = x; this.miny = y; this.difx = difx; this.dify = dify; this.light = light;
drawcircle = true;
}
public void draw(Graphics g){
if(drawcircle){
g.fillOval(minx, miny, difx, dify);
g.setColor(Color.WHITE);
g.fillOval((minx+difx/4)+light, miny+dify/4, difx/4, dify/4);
g.setColor(line_color);
}else{
for(int i = 0; i<xList.size()-1; i++){
g.drawLine((int)xList.get(i), (int)yList.get(i), (int)xList.get(i + 1),
(int)yList.get(i + 1));
}
}
}}}
>
Here is the problem.
LightSourcePanel Code:
class LightSourcePanel extends JPanel implements ChangeListener {
static JSlider j;
public LightSourcePanel (){
j = new JSlider(0,180,90);
j.setMajorTickSpacing(45);
j.setMinorTickSpacing(5);
j.setPaintLabels(true);
j.setPaintTicks (true);
j.setPreferredSize(new Dimension (1500,50));
j.addChangeListener(this);
this.add(j);
}
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
lightChange(j.getValue()); // problem <<<<<< FAIL
}}
First off, change the changecolor(Color) method in DrawingPanel to remove the static keyword. Then you need an instance of DrawingColor to use the class. I would store the instance of it in a field just like JColorChooser is stored.

Timers and KeyEvents in Java

I'm having trouble with creating an animation of a square that will move at a certain speed when one of the arrow keys are pressed. I have implemented both of the keyPressed, and the actionPerformed methods and also started the tick of the timer at end of the constructor.. But the square still wont' move.. What am i doing wrong?
Below is the JPanel.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class A3JPanel extends JPanel implements KeyListener, ActionListener{
public static final int JFRAME_AREA_WIDTH = A3Constants.JFRAME_AREA_WIDTH;
public static final int JFRAME_AREA_HEIGHT = A3Constants.JFRAME_AREA_HEIGHT;;
public static final Rectangle HOME_AREA = A3Constants.HOME_AREA;
public static final Rectangle LEO_LEFT_AREA = A3Constants.LEO_LEFT_AREA;
public static final Rectangle ALL_WALLS_AREA = A3Constants.ALL_WALLS_AREA;
public static final Rectangle EXITING_SLIDES_AREA = A3Constants.EXITING_SLIDES_AREA;
public static final Color NICE_GRAY_COLOUR = A3Constants.NICE_GRAY_COLOUR;
public static final Color GAME_SCREEN_COLOUR = A3Constants.GAME_SCREEN_COLOUR;
public static final Color SLIDES_AREA_COLOUR = A3Constants.SLIDES_AREA_COLOUR;
public static final Color LEO_AREA_COLOUR = A3Constants.LEO_AREA_COLOUR;
public static final Color HOME_AREA_COLOUR = A3Constants.HOME_AREA_COLOUR;
public static final Color WALL_COLOUR = A3Constants.WALL_COLOUR;
public static final int MAX_WALLS = A3Constants.MAX_WALLS;
public static final Font TINY_FONT = A3Constants.TINY_FONT;
public static final Font LARGE_FONT = A3Constants.LARGE_FONT;
public static final Font HUGE_FONT = A3Constants.HUGE_FONT;
public static final int LARGE_FONT_SIZE = A3Constants.LARGE_FONT_SIZE;
public static final int HUGE_FONT_SIZE = A3Constants.HUGE_FONT_SIZE;
public static final Point TICKS_POSITION = A3Constants.TICKS_POSITION;
public static final Point WINNER_LOSER_INFO_POSITION = A3Constants.WINNER_LOSER_INFO_POSITION;
public static final Point INFORMATION_POSITION1 = A3Constants.INFORMATION_POSITION1;
public static final Point INFORMATION_POSITION2 = A3Constants.INFORMATION_POSITION2;
public static final Point INFORMATION_POSITION3 = A3Constants.INFORMATION_POSITION3;
public static final int TICKS_ALLOWED = A3Constants.TICKS_ALLOWED;
public static final int UP = A3Constants.UP;
public static final int DOWN = A3Constants.DOWN;
public static final int LEFT = A3Constants.LEFT;
public static final int RIGHT = A3Constants.RIGHT;
private CoolCat coolCat;
private Timer t;
public A3JPanel() {
setBackground(Color.GREEN);
coolCat = new CoolCat(A3Constants.LEO_START_AREA.x, A3Constants.LEO_START_AREA.y);
addKeyListener(this);
t = new Timer(30,this);
t.start();
//t.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
drawGameArea(g);
coolCat.draw(g);
}
private void drawGameArea(Graphics g){
g.setColor(A3Constants.LEO_AREA_COLOUR);
g.fillRect(A3Constants.LEO_LEFT_AREA.x, A3Constants.LEO_LEFT_AREA.y, A3Constants.LEO_LEFT_AREA.width, A3Constants.LEO_LEFT_AREA.height);
g.setColor(A3Constants.WALL_COLOUR);
g.fillRect(A3Constants.ALL_WALLS_AREA.x, A3Constants.ALL_WALLS_AREA.y, A3Constants.ALL_WALLS_AREA.width, A3Constants.ALL_WALLS_AREA.height);
g.setColor(A3Constants.HOME_AREA_COLOUR);
g.fillRect(A3Constants.HOME_AREA.x, A3Constants.HOME_AREA.y, A3Constants.HOME_AREA.width, A3Constants.HOME_AREA.height);
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP){
coolCat.setDirection(A3Constants.UP);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
coolCat.setDirection(A3Constants.DOWN);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
coolCat.setDirection(A3Constants.LEFT);
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
coolCat.setDirection(A3Constants.RIGHT);
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public void actionPerformed(ActionEvent e){
coolCat.move();
repaint();
}
}
And below is the other Class.
import java.awt.*;
public class CoolCat {
public static final Rectangle LEO_START_AREA = A3Constants.LEO_START_AREA;
public static final int GAME_SCREEN_AREA_TOP = A3Constants.GAME_SCREEN_AREA_TOP;
public static final int GAME_SCREEN_AREA_BOTTOM = A3Constants.GAME_SCREEN_AREA_BOTTOM;
public static final int GAME_SCREEN_AREA_LEFT = A3Constants.GAME_SCREEN_AREA_LEFT;
public static final int GAME_SCREEN_AREA_RIGHT = A3Constants.GAME_SCREEN_AREA_RIGHT;
public static final int UP = A3Constants.UP;
public static final int DOWN = A3Constants.DOWN;
public static final int LEFT = A3Constants.LEFT;
public static final int RIGHT = A3Constants.RIGHT;
private Rectangle area;
private int speed;
private int direction;
public CoolCat(int x, int y){
this.speed = speed;
speed = (int)(Math.random() * (8 - 4 + 1)) + 4;
area = new Rectangle(A3Constants.LEO_START_AREA.x, A3Constants.LEO_START_AREA.y);
direction = RIGHT;
}
public Rectangle getArea(){
area = new Rectangle(LEO_START_AREA.x, LEO_START_AREA.y, LEO_START_AREA.width, LEO_START_AREA.height);
return area;
}
public void setDirection(int direction){
this.direction = direction;
}
//public boolean hasReachedHome(Rectangle zhomeArea){}
public void move(){
if(direction == A3Constants.UP){
area.y -= speed;
} else if(direction == A3Constants.DOWN){
area.y += speed;
} else if(direction == A3Constants.LEFT){
area.x -= speed;
} else if(direction == A3Constants.RIGHT){
area.x += speed;
}
}
public void draw(Graphics g){
g.setColor(Color.RED);
g.fillOval(A3Constants.LEO_START_AREA.x, A3Constants.LEO_START_AREA.y, A3Constants.LEO_START_AREA.width, A3Constants.LEO_START_AREA.height);
}
}
You are adding a KeyListener to a JPanel, a component that by default cannot accept the focus, and the focus is required for key listeners to work.
A simple solution would be to allow your JPanel to accept focus and then request focus be given to it.
A better solution is to avoid use of KeyListeners for Swing applications and instead use Key Bindings (as has been discussed in similar questions many times previously). For example, please check out: How to make an image move while listening to a keypress in Java.
Try something like this. I just made this quickly, so please excuse any errors.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class g{
public static void main(String args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
create();
}
});
}
public static MyPanel my;
public static void create(){
JFrame f = new JFrame("test");
my = new MyPanel();
f.add(my);
f.setSize(1000,1000);
f.setVisible(true);
f.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode == 37){ //left
my.move(4); //1 = up, 2 = right, 3 = down, 4 = left
}
if(e.getKeyCode == 39){ //left
my.move(2); //1 = up, 2 = right, 3 = down, 4 = left
}
if(e.getKeyCode == 38){ //left
my.move(1); //1 = up, 2 = right, 3 = down, 4 = left
}
if(e.getKeyCode == 40){ //left
my.move(3); //1 = up, 2 = right, 3 = down, 4 = left
}
}
#Override
public void keyReleased(KeyEvent e){
//do nothings
}
#Override
public void keyTyed(KeyEvent e){
//do nothing
}
});
}
}
public class MyPanel extends JPanel implements ActionListener{
public static Timer time1;
public Square s;
public MyPanel(){
time1 = new Timer(50, this);
time1.start();
}
public void actionPerformed(ActionEvent e){
repaint();
}
public void move(int d){
if(d == 1){
s.setY(s.getY()-1);
}
if(d == 2){
s.setX(s.getX() + 1);
}
if(d == 3){
s.setY(s.getY() + 1);
}
if(d == 4){
s.setX(set.getX() - 1);
}
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
s.paintSquare(g);
}
}
public class Square{
public int x;
public int y;
public void setX(int xPos){
this.x = xPos;
}
public int getX(){
return x;
}
public void setY(int yPos){
this.y = yPos;
}
public int getY(){
return y;
}
public void paintSquare(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0,0,1000,1000);
g.setColor(Color.RED);
g.fillRect(x,y,30,30);
}
}

Categories