我在将代码绘制到我的jpanel时遇到了一些困难。
除了图形绘图外,所有内容都正确运行。
还有其他答案,说我需要用设置设置面板的大小,但是我已经这样做了。
其他答案说我需要致电super.paintComponent(g);
,但我也这样做。
我缺少什么?
这是我的代码:
事先感谢您的任何帮助。
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import static java.awt.Color.*;
public class Main extends JPanel implements KeyListener {
//Declare all class vars.
private Snake snake = new Snake(50,50,50);
//Declare all Player global booleans
private boolean leftPressed, rightPressed, upPressed, downPressed;
//Declare all Gamestate gobal booleans
// private boolean running = true;
public static void main(String[] args){
Main main = new Main();
main.createFrame();
SwingUtilities.invokeLater(main::customUpdate);
}
private void createFrame() {
JFrame frame = new JFrame("Snaek");
JPanel panel = new JPanel();
frame.setResizable(false);
frame.setSize(800,800);
frame.setLocationRelativeTo(null);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
panel.requestFocus();
panel.addKeyListener(this);
panel.setSize(new Dimension(frame.getWidth(), frame.getHeight()));
Frame.getFrames();
}
private void customUpdate() {
if(leftPressed) {
snake.changeX(-1);
} else if(upPressed) {
snake.changeY(-1);
} else if(downPressed) {
snake.changeY(1);
} else if(rightPressed) {
snake.changeX(1);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(black);
g.drawRect(snake.getX(), snake.getY(), snake.getSize(), snake.getSize());
g.drawRect(100,100,200,200);
repaint();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case 37:
// System.out.println("Left?");
leftPressed = true;
break;
case 38:
// System.out.println("Up?");
upPressed = true;
break;
case 39:
// System.out.println("Right?");
rightPressed = true;
break;
case 40:
System.out.println("Down?");
downPressed = true;
break;
case 27: //Escape
System.out.println(snake.getX());
break;
case 50: //Space
// spacePressed = true;
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case 37:
// System.out.println("Left?");
leftPressed = false;
break;
case 38:
// System.out.println("Up?");
upPressed = false;
break;
case 39:
// System.out.println("Right?");
rightPressed = false;
break;
case 40:
// System.out.println("Down?");
downPressed = false;
break;
}
}
}
您在这里创建一个新的JPanel
:
JPanel panel = new JPanel();
然后将其添加到JFrame
frame.add(panel);
相反,您应该将面板(Main
)添加到其中
frame.add(this);
另外,如@vinceemigh在上面的评论中所述,避免在paintComponent()
方法中调用repaint()
,否则您可以陷入无尽的循环,在应用程序中滞后或冻结。绘画方法仅用于绘画。
另一个提示是使用KeyBindings
代替KeyListener
,或者您可以属于程序不响应关键事件...
,我还将将frame.setVisible(true);
线移至createFrame()
方法的末端...
您将默认面板添加到Jframe。您想添加自定义Jpanel。