Trouble Drawing Line on JFrame - java

I'm trying to write a program that displays a bunch of lines on a screen, the coordinates of which will be determined from another program.
In doing so, I'm trying to modify jasssuncao's code from here, so that I don't have to click on any buttons in order to get lines: How to draw lines in Java
Here is what I have now:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LineDrawing extends JComponent{
private static class Line{
final int x1;
final int y1;
final int x2;
final int y2;
final Color color;
public Line(int x1, int y1, int x2, int y2, Color color) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
}
}
private final LinkedList<Line> lines = new LinkedList<Line>();
public void addLine(int x1, int x2, int x3, int x4) {
addLine(x1, x2, x3, x4, Color.black);
}
public void addLine(int x1, int x2, int x3, int x4, Color color) {
lines.add(new Line(x1,x2,x3,x4, color));
repaint();
}
public void clearLines() {
lines.clear();
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
g.setColor(line.color);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
}
public static void main(String[] args) {
JFrame testFrame = new JFrame();
testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final LineDrawing comp = new LineDrawing();
comp.setPreferredSize(new Dimension(1000, 400));
testFrame.getContentPane().add(comp, BorderLayout.CENTER);
comp.addLine(100, 100, 100, 100, new Color(24, 24, 24));
testFrame.pack();
testFrame.setVisible(true);
}
}
}
However, doing so does not display any a line. Why isn't the code displaying anything? Thanks!

Kudos for a complete example, but a few things bear mentioning:
Your line needs a non-zero size; note the coordinates required by drawLine():
comp.addLine(10, 10, 100, 100, Color.blue);
Your JComponent may need to be opaque:
comp.setOpaque(true);
Construct and manipulate Swing GUI objects only on the event dispatch thread, for example.
Don't use setPreferredSize() when you really mean to override getPreferredSize().

Related

How to keep the rectangle that I drew on the Jpanel when I draw another rectangle?

I have this code in JAVA that draws a rectangle like the paint app when I drag my mouse on the panel. Every time I click and drag to make a new rectangle, the previous one disappears. I was wondering if there is a way for it to stay on the panel. And for there to be multiple rectangles, just like the paint app on windows.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawRect extends JPanel {
int x, y, x2, y2;
public static void main(String[] args) {
JFrame f = new JFrame("Draw Box Mouse 2");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new DrawRect());
f.setSize(300, 300);
f.setVisible(true);
}
DrawRect() {
x = y = x2 = y2 = 0; //
MyMouseListener listener = new MyMouseListener();
addMouseListener(listener);
addMouseMotionListener(listener);
}
public void setStartPoint(int x, int y) {
this.x = x;
this.y = y;
}
public void setEndPoint(int x, int y) {
x2 = (x);
y2 = (y);
}
public void drawPerfectRect(Graphics g, int x, int y, int x2, int y2) {
int px = Math.min(x,x2);
int py = Math.min(y,y2);
int pw=Math.abs(x-x2);
int ph=Math.abs(y-y2);
g.drawRect(px, py, pw, ph);
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
setStartPoint(e.getX(), e.getY());
}
public void mouseDragged(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
repaint();
}
public void mouseReleased(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
drawPerfectRect(g, x, y, x2, y2);
}
}
There are a few useful things to remember writing Swing graphics programs:
paintComponent repaints the entire component every time it is called, so you need to draw everything that you want to appear. The operations you do with the Graphics object will only persist until the next call to paintComponent.
Graphics2D is more capable than Graphics. It draws nicely antialiased shapes with floating-point co-ordinates, various line styles and so on. The Graphics parameter to paintComponent is in fact always a Graphics2D instance and you can cast it to one without worrying.
The inheritance hierarchy of components is also a painting hierarchy, so you need to call super.paintComponent(g) at the start of your paintComponent method. See this question for more details.
So I've made some changes to you program:
Added a field, List<Rectangle2D> rectangles to remember the rectangles the user has created. A rectangle is added to this list each time the mouse button is raised.
Added a call to super.paintComponent
Used Graphics2D to draw the rectangles, with a more interesting line style (Stroke)
Changed your paintComponent to draw each of the rectangles in the list, plus the 'rubber-band' rectangle the user is currently drawing.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
public class DrawRect extends JPanel {
int x, y, x2, y2;
// this is the list of all the rectangles the user has drawn so far
List<Rectangle2D> rectangles = new ArrayList<>();
public static void main(String[] args) {
JFrame f = new JFrame("Draw Box Mouse 2");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new DrawRect());
f.setSize(300, 300);
f.setVisible(true);
}
DrawRect() {
x = y = x2 = y2 = 0; //
MyMouseListener listener = new MyMouseListener();
addMouseListener(listener);
addMouseMotionListener(listener);
}
public void setStartPoint(int x, int y) {
this.x = x;
this.y = y;
}
public void setEndPoint(int x, int y) {
x2 = (x);
y2 = (y);
}
// this creates a new rectangle object instead of drawing one
public Rectangle2D makePerfectRect(int x, int y, int x2, int y2) {
int px = Math.min(x,x2);
int py = Math.min(y,y2);
int pw=Math.abs(x-x2);
int ph=Math.abs(y-y2);
return new Rectangle2D.Float(px, py, pw, ph);
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
setStartPoint(e.getX(), e.getY());
}
public void mouseDragged(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
repaint();
}
public void mouseReleased(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
// when the mouse is released, we add the current rectangle to our list
rectangles.add(makePerfectRect(x,y,x2,y2));
repaint();
}
}
public void paintComponent(Graphics g) {
// use Graphics2D, you can draw much nicer lines
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g);
g.setColor(Color.RED);
// draw the rectangle the user is currently drawing
g2d.draw(makePerfectRect(x,y,x2,y2));
g.setColor(Color.BLUE);
Stroke oldStroke = g2d.getStroke();
g2d.setStroke(new BasicStroke(4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0.0f));
for (Rectangle2D r : rectangles) {
g2d.draw(r);
}
g2d.setStroke(oldStroke); // restore the original Stroke
}
}

JPanel problems with drawing ovals

I've created an application that draws a random number of ovals (with random sizes and colors) with JPanel and JFrame (Java 8 installed in Ubuntu 16.04). Everything seems to be right... but no oval is draw when I execute the code. I receave just a blank screen (JFrame appears, but only blank).
It have 3 classes: MyOval, DrawPanel and DrawTest.
MyOval Class
package drawingovals;
import java.awt.Color;
import java.awt.Graphics;
public class MyOval {
private int x1;
private int y1;
private int x2;
private int y2;
private Color myColor;
private boolean isFilled;
public MyOval(int x1, int y1, int x2, int y2, Color color, boolean isFilled) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.x2 = x2;
myColor = color;
this.isFilled = isFilled;
}
public int getUpperLeftX(){
return x1;
}
public int getUpperLeftY(){
return y1;
}
public int getWidth(){
return x2 - x1;
}
public int getHeight() {
return y2 - y1;
}
public String getColor() {
return myColor.toString();
}
public boolean getFilling(){
return isFilled;
}
public void setUpperLeftX(int value) {
x1 = value;
}
public void setUpperLeftY(int value) {
y1 = value;
}
public void setDownRightX(int value) {
x2 = value;
}
public void setDownRightY(int value) {
y2 = value;
}
public void drawNoFill(Graphics g) {
g.setColor(myColor);
g.drawOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
public void drawFill(Graphics g) {
g.setColor(myColor);
g.fillOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
}
DrawPanel Class
package drawingovals;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;
public class DrawPanel extends JPanel{
private Random randomNumbers = new Random();
private MyOval[] ovals;
public DrawPanel() {
setBackground(Color.WHITE);
ovals = new MyOval[5 + randomNumbers.nextInt(5)];
for (int count = 0; count < ovals.length; count++) {
int x1 = randomNumbers.nextInt(300);
int y1 = randomNumbers.nextInt(300);
int x2 = randomNumbers.nextInt(300);
int y2 = randomNumbers.nextInt(300);
Color color = new Color(randomNumbers.nextInt(256),
randomNumbers.nextInt(256), randomNumbers.nextInt(256));
boolean fill = randomNumbers.nextBoolean();
ovals[count] = new MyOval(x1, y1, x2, y2, color, fill);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int count = 0; count < ovals.length - 1; count++) {
ovals[count].drawFill(g);
}
}
}
DrawTest Class
package drawingovals;
import javax.swing.JFrame;
public class DrawTest {
public static void main(String[] args) {
DrawPanel panel = new DrawPanel();
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(400, 400);
application.setVisible(true);
}
}
You need to take care that your oval heights and widths contain only positive values -- your code does not do this. Consider using Math.max, Math.min, or Math.abs when obtaining your oval properties to help you achieve this.
Also, this is wrong as you're duplicating setting x2 bug ignoring y2:
this.x1 = x1;
this.y1 = y1;
this.x2 = x2; // *** these are the same
this.x2 = x2; // *** these are the same
Something like this would work:
public MyOval(int x1, int y1, int x2, int y2, Color color, boolean isFilled) {
this.x1 = Math.min(x1, x2);
this.y1 = Math.min(y1, y2);
this.x2 = Math.max(x1, x2);
this.y2 = Math.max(y1, y2);;
myColor = color;
this.isFilled = isFilled;
}
In the future, the key to solving these types of issues is to use a debugger to check the fields of your program, here the oval properties, as the program runs, and then see if they don't make sense, and then why.

How to make a continuously looping news Ticker in java

I dont know about you, but I tried so hard on how to create a news ticker. I found approaches that would append what was off the screen on to the back side of it. This caused the animation to jump by a whole character. Then I found methods that would not loop until the text was completely off the screen. After asking a ton of questions on this I thought it would be nice if I just posted my final solution for all the people wondering how to make it. Here you go.
import java.awt.Color;
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;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Scroll2 extends JPanel implements ActionListener{
private int x;
private int x2;
private int y;
private int width;
private String textIV;
private Color textColorIV;
private Color bGColorIV;
private Font f=(new Font("SansSerif", Font.BOLD,34));
Timer t;
// TODO font size
public Scroll2(String text, Color textColor, Color bGColor)
{
x=Integer.MIN_VALUE;
x2=Integer.MIN_VALUE;
y=0;
textIV=text;
this.setVisible(true);
Timer refreshTimer = new javax.swing.Timer(1000/50, this);
refreshTimer.start();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setFont(f);
if ( x == Integer.MIN_VALUE ){
width=g.getFontMetrics().stringWidth(textIV);
x = 0;
y = (int) (getHeight()*.6);
}
if ( x2 == Integer.MIN_VALUE ){
x2 = g.getFontMetrics().stringWidth(textIV);
}
g.setColor(bGColorIV);
g.fillRect(this.getX(), this.getY(), (int)this.getBounds().getWidth(), (int)this.getBounds().getHeight());
g.setColor(textColorIV);
g.drawString(textIV, x, y);
g.drawString(textIV, x2, y);
}
public void refresh ()
{
if(x>=(-width)&&x2!=Integer.MIN_VALUE)
{
x=x-2;
x2=x2-2;
}
if(x2<=-width&&x!=Integer.MIN_VALUE)
{
x2=width;
}
if(x<-width&&x!=Integer.MIN_VALUE)
{
x=width;
}
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
this.refresh();
}
}

JComboBox gets stuck

I have a problem with a JComboBox. I have an upper JPanel with the JComboBox and another JPanel below with a BufferedImage where I can draw some ovals (it has a listener to the mouse clicks). The problem, as you will see in the video, is that sometimes when I change the option in the JComboBox it does not show that change.
For example, if I select 'ALL' and then I select 'L4', 'ALL' remains shown instead of changing to 'L4', but when I click on the JComboBox, in the other drawing JPanel or on another window of the desktop, it changes to 'L4' (it should have changed before). I think that the problem is something related with having a JPanel listening for mouse clicks below the JComboBox, but I'm not sure.
Can anyone tell me how can I fix that?
Here's the link to the video I made to show the problem: http://youtu.be/8Gg2Uq3SCYw
It is also important to say that when I record the video with the QuickTime Player, all is recorded working correctly even if it hasn't worked correctly (what I mean is that I see what is in the video (link) but QuickTime records it running correctly, very very weird...)
Here's the link to the Example eclipse project I made for you, try to select different options many times, you will see what I say: https://app.sugarsync.com/iris/wf/D6421069_60887018_228038
Look at LapPanel of CircuitTracePlotView.java, there is the JComboBox.
I'm running it on a MacBookPro 10.8 (Mountain Lion)
And here is the code for the view (it is also on the link of the Example):
package view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CircuitTracePlotView extends JFrame {
private static final long serialVersionUID = 5125304890914235274L;
private int numberOfLaps;
private CircuitTracePlot plot;
private LapPanel lapPanel;
public CircuitTracePlotView() {
this.setVisible(false);
this.plot = new CircuitTracePlot();
this.lapPanel = new LapPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(this.plot, BorderLayout.CENTER);
this.getContentPane().add(this.lapPanel, BorderLayout.NORTH);
this.pack();
this.setLocationRelativeTo(null);
}
public void init(CircuitTracePlotViewController circuitTracePlotViewController, int numberOfLaps) {
this.setController(circuitTracePlotViewController);
this.setNumberOfLaps(numberOfLaps);
this.lapPanel.setLapSelection();
}
private void setController(CircuitTracePlotViewController circuitTracePlotViewController) {
this.plot.init(circuitTracePlotViewController);
}
private int getNumberOfLaps() {
return this.numberOfLaps;
}
public void setNumberOfLaps(int laps) {
this.numberOfLaps = laps;
System.out.println("NumberOfLaps" + this.numberOfLaps);
}
public void drawPoint(int x, int y) {
this.plot.drawPoint(x, y);
this.repaint();
}
public void drawLine(int x1, int y1, int x2, int y2) {
this.plot.drawLine(x1, y1, x2, y2);
}
public Dimension getPlotDimension() {
return this.plot.getPreferredSize();
}
//Drawing panel
private class CircuitTracePlot extends JPanel {
private static final long serialVersionUID = -7915054480476755069L;
private final static short LINE = 0;
private final static short OVAL = 1;
private final static int OVALHEIGHT = 10;
private final static int OVALWIDTH = 10;
BufferedImage plot;
Graphics2D plotGraphics;
private int x1;
private int x2;
private int y1;
private int y2;
private int paintType;
private CircuitTracePlot() {
this.setBackground(Color.WHITE);
}
private void init(CircuitTracePlotViewController circuitTracePlotViewController) {
this.addListeners(circuitTracePlotViewController);
this.plot = (BufferedImage)this.createImage(this.getPreferredSize().width, this.getPreferredSize().height);
this.plotGraphics = this.plot.createGraphics();
}
private void drawLine(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.paintType = LINE;
this.repaint();
}
private void drawPoint(int x1, int y1) {
this.x1 = x1;
this.y1 = y1;
this.paintType = OVAL;
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
switch (this.paintType) {
case LINE:
plotGraphics.drawLine(x1, y1, x2, y2);
g.drawImage(this.plot,0,0, this);
break;
case OVAL:
plotGraphics.fillOval(x1 - OVALWIDTH/2, y1 - OVALHEIGHT/2, OVALWIDTH, OVALHEIGHT);
g.drawImage(this.plot,0,0, this);
break;
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(700, 500);
}
private void addListeners(CircuitTracePlotViewController circuitTracePlotViewController) {
this.addMouseListener(circuitTracePlotViewController);
}
}
private class LapPanel extends JPanel{
private static final long serialVersionUID = -287427935273603789L;
//private LinkedList<JIDButton> list_LapButtons;
private JComboBox<String> JCB_Laps;
private LapPanel() {
this.setBorder(BorderFactory.createTitledBorder("Lap Selection"));
//this.list_LapButtons = new LinkedList<JIDButton>();
//JIDButton auxButton = new JIDButton(0, "<html><u>A</u>LL<html>");
//this.list_LapButtons.add(auxButton);
//this.add(auxButton);
System.out.println("NumberOfLaps" + CircuitTracePlotView.this.numberOfLaps);
}
private void setLapSelection() {
String[] auxLaps = new String[CircuitTracePlotView.this.getNumberOfLaps() + 1];
auxLaps[0] = "<html>" + "<u>" + "A" + "</u>" + "LL" + "<html>";
for (int i = 1; i <= CircuitTracePlotView.this.getNumberOfLaps(); i++) {
auxLaps[i] = "<html>" + "L" + "<u>" + i + "</u>" + "<html>";
}
this.JCB_Laps = new JComboBox<String>(auxLaps);
this.add(JCB_Laps);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(700, 65);
}
}
}
I've posted all the information that I think it's relevant, if someone needs more information just ask for it.

Smoothly animating a fractal tree

I have a Java program that will draw a fractal tree based on a recursive method and I want to make it appear to smoothly grow and I'm not sure how to do this.
The following is my code. This is a school assignment, just to make that known, but the basic assignment was only to draw a fractal tree, which I have already accomplished, the animation is secondary and more of a personal goal that I wish to accomplish.
package Question4;
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
public class FractalTree1 extends Canvas {
// fields for drawing
private JFrame frame;
private final int WINDOW_WIDTH = 1280;
private final int WINDOW_HEIGHT = 720;
public FractalTree1() {
frame = new JFrame("Fractal Tree");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.add(this);
frame.setVisible(true);
}
public static void main(String[] args) {
FractalTree1 ft = new FractalTree1();
ft.setVisible(true);
ft.setBackground(Color.black);
}
#Override
public void paint(Graphics g) {
g.setColor(Color.green);
drawFractalTree(g, WINDOW_WIDTH / 2, WINDOW_HEIGHT - 75, -90, 11);
}
public void drawFractalTree(Graphics g, int x1, int y1, double angle, int depth) {
if (depth == 0) {
} else {
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(0.5f * depth));
g2d.drawLine(x1, y1, x2, y2);
drawFractalTree(g, x2, y2, angle + 30, depth - 1);
drawFractalTree(g, x2, y2, angle - 30, depth - 1);
}
}
}
EDIT
As a follow up now...when I add the Thread.sleep() to it, it draws it awkwardly looking as that's how the recursion draws it. Would it be possible to force it to draw from the "trunk" up so it simulates an actual tree "growing"?
To get that working, you'll probably need to use double buffering. Essentially you draw on a off-screen buffer and refresh it to the screen when the drawing is done.
In your drawFractalTree() method, you'll have to add a Thread.sleep() call to delay the drawing. Adding this directly after g2d.drawLine(x1, y1, x2, y2); should do the trick. It may end up being very slow. To curb that, you can use a counter and sleep for 1ms after every 10th call.
To just start seeing some animation, add a Thread.sleep(100) call at the beginning of drawFractalTree().
Thread.sleep(100);
This works excellent if you use an image to draw from its graphics instead of drawing directly.Thus, image pixels' color will not be changed each time you draw sth on it.
package Question4;
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
public class FractalTree1 extends Canvas {
// fields for drawing
private JFrame frame;
private final int WINDOW_WIDTH = 1280;
private final int WINDOW_HEIGHT = 720;
private Image buffer = createImage(WINDOW_WIDTH,WINDOW_HEIGHT);
private Graphics bufferg = buffer.getGraphics();
public FractalTree1() {
frame = new JFrame("Fractal Tree");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.add(this);
frame.setVisible(true);
}
public static void main(String[] args) {
FractalTree1 ft = new FractalTree1();
ft.setVisible(true);
ft.setBackground(Color.black);
bufferg.setColor(Color.green);
}
#Override
public void paint(Graphics g) {
g.drawImage(buffer,0,0,null);
drawFractalTree(g, WINDOW_WIDTH / 2, WINDOW_HEIGHT - 75, -90, 11);
}
public void drawFractalTree(Graphics g, int x1, int y1, double angle, int depth) {
if (depth == 0) {
} else {
Thread.sleep(100);//It has a catch exception here;
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
Graphics2D g2d = (Graphics2D) bufferg;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(0.5f * depth));
g2d.drawLine(x1, y1, x2, y2);
repaint();
drawFractalTree(g, x2, y2, angle + 30, depth - 1);
drawFractalTree(g, x2, y2, angle - 30, depth - 1);
}
}
}

Categories

Resources