最近我一直在研究一個程序,用空的彩色正方形畫一個區域。它們在屏幕上的位置基於文本文件中的值1和2。 1s應該製造紅色盒子,2s應該製造綠色盒子。但是,當我運行該程序時,只有紅色框被繪製。我做了一些測試,發現重繪方法只被調用了兩次(有時出於某種原因),即使文件中有近300個值,並且應該爲每個值調用一次repaint()
。這裏是我的代碼:重繪()不叫
public class MAP extends JFrame {
public static void main(String[] args) throws IOException {
MAP map = new MAP();
}
Shape shape;
int x = -32;
int y = 0;
ArrayList<Shape> shapes = new ArrayList<Shape>();
Graphics2D g2;
Color coulor = null;
private class PaintSurface extends JComponent {
public PaintSurface() {
}
public void paint(Graphics g) {
g2 = (Graphics2D) g;
g2.setColor(coulor);
for (Shape s : shapes) {
g2.draw(s);
}
}
}
public MAP() throws FileNotFoundException, IOException {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
frame.setTitle("Grid Maker");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(new PaintSurface(), BorderLayout.CENTER);
frame.setVisible(true);
readNextLine();
}
private void readNextLine() throws IOException {
File file = new File("map.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '1') {
coulor = Color.RED;
x += 32;
int smallX = x/32;
int smallY = y/32;
shape = new Rectangle2D.Float(x, y, 32, 32);
shapes.add(shape);
repaint();
} else if (c == '2') {
coulor = Color.GREEN;
x += 32;
int smallX = x/32;
int smallY = y/32;
shape = new Rectangle2D.Float(x, y, 32, 32);
shapes.add(shape);
repaint();
}
}
line = in.readLine();
x = -32;
y += 32;
}
}
}
爲什麼這段代碼不能正常工作?
請永遠不要在ALLCAPS中命名課程。 「地圖」更容易閱讀 – supersam654 2013-02-10 23:01:52
@ supersam654。對於那個很抱歉。我想我在一本我正在閱讀的書中找到了課程名稱。 – KrisC 2013-02-10 23:05:21
你的輸入文件是什麼? – Raufio 2013-02-10 23:18:36