如何在每次按下JButton时使分形树生长?我想让它看起来每次点击按钮时分支更多。
我目前有这个绘制分形树的代码。
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.geom.*;
public class Tree {
public float posX = 0;
public float posY = 0;
public void Tree(){
}
public void branch(Graphics2D g2, float len) {
g2.setStroke(new BasicStroke(2));
g2.draw(new Line2D.Float(posX, posY, 0, -len)); // Draw the branch itself
g2.translate(0, -len); // Move to the end of that line
len *= 0.66; // Shrink the length of the branch
if (len > 2) { // Base case: exit when the length of the branch is 2
// pixels or less
AffineTransform at = g2.getTransform();
g2.rotate(Math.PI / 5); // Rotate to the right
branch(g2, len); // Call itself to draw two shorter branches
g2.setTransform(at);
// Repeat the same thing
at = g2.getTransform();
g2.rotate(-Math.PI / 5);
branch(g2, len);
g2.setTransform(at);
}
}
}
我还有一个Panel类,它显示了花园环境中的树(不包括花园类)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Panel extends JPanel implements ActionListener {
public static final int WINDOW_W = 1280;
public static final int WINDOW_H = 720;
private JButton simpleGarden;
private Text txt;
Tree tree;
Garden garden;
public Panel(){
this.setBackground(Color.GRAY);
setPreferredSize(new Dimension(WINDOW_W, WINDOW_H));
setLayout(new FlowLayout());
simpleGarden = new JButton("START YOUR GARDEN");
add(simpleGarden);
simpleGarden.addActionListener(this);
txt = new Text();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (garden != null){
garden.showGarden(g2);
g2.setColor(new Color(139,69,19));
g2.translate(WINDOW_W/2, WINDOW_H - 75);
tree.branch(g2, 120); // display fractal
txt.removeText(g2);
}
else{
txt.startGarden(g2);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "START YOUR GARDEN") {
garden = new SimpleGarden();
tree = new Tree();
remove(simpleGarden);
}
repaint();
}
}