我正在尝试更改我的网格系统中位置(0,1)的文本,但由于某种原因,它在停留之前的数字,所以如果我将它从0更改为1,它是一个0与1重叠。我的代码造成了什么问题?
主要课程:
package Tetris;
import java.awt.Color;
import javax.swing.JFrame;
class Tetris {
JFrame frame;
public Tetris() {
frame = new JFrame("Tetris");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setResizable(false);
//frame.setLocationRelativeTo(null);
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Board(frame));
}
public static void main(String[] args) {
new Tetris();
}
}
游戏课程:
package Tetris;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel {
private static final long serialVersionUID = -5635526290001171288L;
private int[][] boardLayout;
private int[] piecePos;
private float timerCount = 0.0f;
private String boardLayoutString;
private Timer timer;
public Board(JFrame frame) {
timer = new Timer(10, new ActionListener() {
public void actionPerformed(ActionEvent e) {
update();
}
});
timer.start();
boardLayout = new int[8][16];
piecePos = new int[] { 1, 0 };
boardLayoutString = "";
for(int y = 0; y < 16; y++) { // grid system
for(int x = 0; x < 8; x++) {
boardLayout[x][y] = 0;
if(x == 7) {
boardLayoutString += boardLayout[x][y] + "\n";
} else {
boardLayoutString += boardLayout[x][y] + " ";
}
}
}
frame.addKeyListener(new KeyListener() { // maybe put this somewhere else
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
if(e.getKeyCode() == KeyEvent.VK_Q) {
boardLayout[1][0] = 2;
}
}
public void keyReleased(KeyEvent e) {
//
}
public void keyTyped(KeyEvent e) {
//
}
});
}
private String boardLayoutToString(int[][] boardLayout) {
boardLayoutString = "";
for(int y = 0; y < 16; y++) { // grid system
for(int x = 0; x < 8; x++) {
if(x == 7) {
boardLayoutString += boardLayout[x][y] + "\n";
} else {
boardLayoutString += boardLayout[x][y] + " ";
}
}
}
return boardLayoutString;
}
private void update() {
timerCount += 0.01f; // every 10ms, add 0.01 - this means 1.0f = 1s
if(timerCount >= 1.0f) { // do something every 1s
// if(piecePos[1] < 8) {
// boardLayout[piecePos[0]][piecePos[1]] = 1;
// piecePos[1]++;
// if(piecePos[1] > 0) {
// boardLayout[piecePos[0]][piecePos[1] - 1] = 0;
// }
// } else {
// piecePos = new int[] { 1, 0 };
// }
timerCount = 0.0f;
}
}
public void paint(Graphics g) {
//Graphics2D g2 = (Graphics2D) g;
for(int i = 0; i < boardLayoutToString(boardLayout).split("\n").length; i++) {
g.drawString(boardLayoutToString(boardLayout).split("\n")[i], 50, 50 + (i * 15));
}
repaint();
}
}
答案 0 :(得分:4)
该来源有一些可疑的功能。
JComponent
中的自定义绘画,请使用paintComponent(Graphics)
代替paint(Graphics)
。 super.paintComponent(Graphics)
以清除上一张图。 @Override
表示法以确保编译时检查。 repaint()
,而应使用Swing ActionListener
Timer
调用它