我正试图在窗口中间以规则的距离间隔打印出一条小圆圈的水平线。我需要使用递归来完成此操作。当我调用递归方法来增加屏幕上圆圈的位置以创建线条但是我的屏幕上没有打印出图形时,我使用构造函数?
package weekFour;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.*;
@SuppressWarnings("serial")
public class Circle extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private Color circleColor = Color.RED; //starting colour
private Color circleColor2 = Color.BLUE;
private Color squareColor = Color.GREEN;
private Color squareColor2 = Color.YELLOW;
private int circX = -15;
private int circY = circX;
private int circW = PREF_W - 2 * circX;
private int circH = PREF_H - 2 * circY;
private static int windowW = 2000;
private static int windowH = 1000;
public Circle() {
}
protected void paintComponent(Graphics g, int xval, int yval, int diameter) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //smoothes out edges
g2.setColor(circleColor);
g2.fillOval(xval, yval, diameter, diameter);
g2.setColor(Color.BLACK);
g2.drawOval(xval, yval, diameter, diameter);
paintComponent(g, circX + 25, 450, 12);
}
private static void createAndShowGui() { //code for GUI visuals
JFrame frame = new JFrame("MyTaskToo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Circle());
frame.setSize(windowW, windowH);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
感谢您的时间
答案 0 :(得分:2)
首先查看Painting in AWT and Swing和Performing Custom Painting,了解有关绘画如何运作的详细信息。
您应该覆盖paintComponent(Graphics g)
方法(注意,没有额外的参数),但在此之前,您将需要更改方法,因为递归方法调用将不起作用。
相反,您需要某种后台线程,可以定期触发新的绘画更新
请参阅Concurrency in Swing了解执行此操作所涉及的危险,并How to use Swing Timers了解可能的解决方案
答案 1 :(得分:-2)
//你需要在最后添加一行来重新绘制。
圈()
{
重绘();
}