这个问题在这里已有答案:
我知道如何用Java创建形状但由于某种原因我无法看到框架上的形状。我尝试了多个版本的创建形状,但它不适合我的特定类。最后,我想要一个创建圆圈的课程(我可以将它放在任何我想要的地方)。
我知道其他人已经在这里问了这个问题,我尝试了解决方案。但它不起作用......我尝试过:类扩展了Component,JPanel,与Graphics2D等不同的解决方案
我希望它在哪里(代码注释):
public class GameBoard extends JFrame implements KeyListener {
private CreateCircle circle;
public GameBoard() {
this.setSize(500, 500);
this.getContentPane().setBackground(Color.BLACK);
this.setTitle("Game");
this.setLayout(null);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//CREATE CIRCLE
circle = new CreateCircle();
this.add(circle);
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 38) {
//UP
}
if(e.getKeyCode() == 40) {
//DOWN
}
if(e.getKeyCode() == 39) {
//RIGHT
}
if(e.getKeyCode() == 37) {
//LEFT
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
让我们假设你的`CreateCircle是一个JPanel。
class CreateCircle extends JPanel{
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.drawOval(20, 20, 80, 80);
}
}
这应该与您拥有的代码一起使用。