简体   繁体   中英

Eclipse vs BlueJ issue

I tried this code in BlueJ which should create a rectangle and move it around but it does not function. Then I put the same exact code into Eclipse and it functions as I thought it would. Any ideas to why this works in Eclipse but not in BlueJ?

import javax.swing.*;
import java.awt.*;
public class Shapes
{
    public static void main(String[] args)
    {

         JFrame frame = new JFrame("Test");
         Draw object = new Draw(); 
         frame.add(object); 
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(400,400);
         frame.setVisible(true);
    }
}



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Draw extends JPanel implements ActionListener, KeyListener
{
    Timer tm = new Timer(5,this);
    int x = 0, y = 0, velX = 0, velY = 0;

    public Draw()
    {
        tm.start();
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false); 

    }


    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.fillRect(x,y,100,20);
    }

    public void actionPerformed(ActionEvent e)
    {
        x += velX;
        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;
    }
}

I can see what you mean I believe it attaches it to that corner of the screen because when I resize the screen it moves with that corner. I think its not that BlueJ can't Run it properly i believe it can but it does it differently than what eclipse does. I believe this question asks the same thing and it gets pretty good answers you should look at it first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM