gpt4 book ai didi

java - 椭圆不会出现在 jframe 上

转载 作者:行者123 更新时间:2023-12-01 13:35:48 25 4
gpt4 key购买 nike

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

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);

}

}

最佳答案

对于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));
}

这对你有帮助。

关于java - 椭圆不会出现在 jframe 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21286659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com