java如何重复画图
使用循环结构重复绘制图形
在Java中,可以通过循环结构(如for或while循环)结合绘图方法实现重复画图。以下示例使用Graphics类的fillRect方法在JPanel上重复绘制矩形:
import javax.swing.*;
import java.awt.*;
public class RepeatDrawing extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 10; i++) {
g.fillRect(i * 30, i * 30, 20, 20);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new RepeatDrawing());
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
利用定时器实现动画效果
通过javax.swing.Timer可以实现周期性重绘,形成动态重复绘图效果:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class AnimatedDrawing extends JPanel {
private int x = 0;
public AnimatedDrawing() {
Timer timer = new Timer(100, (ActionEvent e) -> {
x = (x + 5) % getWidth();
repaint();
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x, 50, 30, 30);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new AnimatedDrawing());
frame.setSize(400, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
使用BufferedImage实现离屏绘制
对于复杂重复图形,可先绘制到BufferedImage再重复渲染:
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class BufferedImageDrawing extends JPanel {
private BufferedImage buffer;
public BufferedImageDrawing() {
buffer = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = buffer.createGraphics();
g2d.setColor(Color.BLUE);
g2d.fillOval(0, 0, 50, 50);
g2d.dispose();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 5; i++) {
g.drawImage(buffer, i * 60, i * 60, null);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new BufferedImageDrawing());
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
参数化绘图方法实现灵活重复
创建可配置的绘图方法,通过不同参数实现多样化重复:

import javax.swing.*;
import java.awt.*;
public class ParametricDrawing extends JPanel {
private void drawPattern(Graphics g, int x, int y, int size, Color color) {
g.setColor(color);
g.fillOval(x, y, size, size);
g.setColor(Color.BLACK);
g.drawOval(x, y, size, size);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 8; i++) {
drawPattern(g, i * 40, i * 20, 30 + i * 5,
new Color(100 + i * 20, 50 + i * 10, 150));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new ParametricDrawing());
frame.setSize(400, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}






