椭圆不会出现在jframe上

时间:2014-01-22 15:10:50

标签: java swing jframe paintcomponent

我一直在使用箭头键移动,当我终于找到一个简单的教程时,图形将不会绘制圆圈,请任何帮助都将非常感谢!

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.event.KeyListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
import javax.swing.Timer;


public class Plant extends JPanel implements ActionListener, KeyListener{
double x = 0, y = 0, velx = 0, vely = 0;
Timer t = new Timer(5, this);//calls action listener every 5 seconds
public Plant(){
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);//sets odd keys to act normal

}
public void drawGraphics(Graphics g){

super.paintComponent(g);
Graphics2D g2= (Graphics2D) g;
g2.fill(new Ellipse2D.Double(x, y, 70, 70));

}
public void actionPerformed(ActionEvent e){
repaint();//adds to x and y coordinates, then redraws them to the new coordinates
x += velx;
y += vely;


}
public void up(){
vely = -1.5;//casll when up key is pressed
velx = 0;
}
public void down(){
vely = 1.5;
velx = 0;

}
public void left(){
velx = -1.5;
vely = 0;

}
public void right(){
velx = 1.5;
vely = 0;

}
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_LEFT){
    left();
}
if(code == KeyEvent.VK_RIGHT){
    right();
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}

}

这是我的第二个类的代码,用于绘制框架。

import javax.swing.JFrame;

public class BasicCharacterMovement{
public static void main(String args[]){
    JFrame j = new JFrame();
    Plant s = new Plant();
    j.add(s);
    j.setVisible(true);
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(800, 600);

}

}

1 个答案:

答案 0 :(得分:1)

对于java中的自定义绘图,您需要使用paintComponent(Graphics g) JComponent。在Plant中,您在drawGraphics中绘制椭圆是错误的。将drawGraphics替换为:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.fill(new Ellipse2D.Double(x, y, 70, 70));
}

这有助于你。