我的任務是通過paintComponent方法創建一個10x10可調整大小的棋盤。
我的問題是我得到的第一個行權,但接下來的行不顯示,我根本不知道我的錯誤是10x10棋盤與paintComponent
GrafikPanel類:
import java.awt.*;
import javax.swing.*;
public class GrafikPanel extends JPanel {
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
int width = g.getClipBounds().width;
int height = g.getClipBounds().height;
int lines = 0;
while(lines < 10){
int posH = height;
int posW = width/10;
int squares = 0;
while(squares < 10){
if(squares%2 == 0){
if(lines%2 != 0){
g.setColor(Color.BLACK);
}
else {
g.setColor(Color.WHITE);
}
g.fillRect(width-posW, height-posH, width/10, height/10);
}
if(squares%2 != 0){
if(lines%2 != 0){
g.setColor(Color.WHITE);
}
else {
g.setColor(Color.BLACK);
}
g.fillRect(width-posW, height-posH, width/10, height/10);
}
posW += width/10;
squares++;
}
posH -= height/10;
lines++;
}
}
@Override
public Dimension getPreferredSize(){
return new Dimension(500, 500);
}
}
AUF1類:
import java.awt.*;
import javax.swing.*;
public class Auf1 extends JFrame {
GrafikPanel panel;
public Auf1(){
setTitle("Schachbrett");
panel = new GrafikPanel();
add(panel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new Auf1();
}
}
我的代碼格式不正確,因爲我無法習慣於在這裏輸入代碼的方式,因此, 如果有人能告訴我我在哪裏可以修復我的錯誤,那會很好。
另請參閱此[相關示例](http://stackoverflow.com/a/10097538/230513)。 – trashgod