我的任务是通过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