我這樣做是爲了生成一個棋盤,並且每隔10秒翻轉10次瓦片(開關顏色)。但是,圖形要麼不加載,要麼不更新。圖形緩慢或沒有均勻加載
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class ShapeTest extends JPanel implements ActionListener {
private static int FRAME_HEIGHT = 500;
private static int FRAME_WIDTH = 500;
private static JFrame frame = new JFrame();
Color color1 = Color.BLACK;
Color color2 = Color.WHITE;
javax.swing.Timer timer = null;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setAttributes();
}
});
}
public static void setAttributes() {
frame.add(new ShapeTest());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("FrameTest");
frame.pack();
frame.setVisible(true);
}
/* Constructor */
public ShapeTest() {
timer = new Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (color1 == Color.BLACK) {
color1 = Color.WHITE;
color2 = Color.BLACK;
repaint();
} else {
color1 = Color.BLACK;
color2 = Color.WHITE;
repaint();
}
}
});
timer.start();
}
protected void painComponent(Graphics g) {
super.paintComponent(g);
for (int x = 0; x < FRAME_WIDTH; x = x + 10) {
for (int y = 0; y < FRAME_HEIGHT; y = y + 10) {
if (x % 20 == 0) {
g.setColor(color2);
g.fillRect(x, y, 10, 10);
y = y + 10;
g.setColor(color1);
g.fillRect(x, y, 10, 10);
} else {
g.setColor(color1);
g.fillRect(x, y, 10, 10);
y = y + 10;
g.setColor(color2);
g.fillRect(x, y, 10, 10);
}
}
}
}
public Dimension getPreferredSize() {
return new Dimension(FRAME_WIDTH, FRAME_HEIGHT);
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
這是根據下面的答案修改後的代碼,但是,它似乎仍然沒有運行。
對不起,我拼寫'paintComponent'錯誤。我有'painComponent'。做出修復,並且工作正常。我測試了它。 –