2014-01-22 50 views
0

我一直在使用箭头键移动,当我终于找到一个简单的教程,图形不会画圆,请任何帮助都将不胜感激!Ellispe不会出现在jframe

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

对于自定义的绘画在Java中,你需要使用的JComponentpaintComponent(Graphics g)。在你的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)); 
} 

这会帮助您。

+0

谢谢sooooo很多人像魅力一样工作!再次感谢! –