Background
Im total Java newbie, today I started learning it (with thenewboston.org). I already know how to make simple windows/forms/gui, how to draw lines etc.
My goal is to create in Java gauge like this:
This is gauge which I created in .NET C# WPF, and now I want to rewrite this to Java.
Main question:
How to create triangle or other shape with some transparency and rotate it?
I tried to draw something by using Graphics object like this:
public void paint(Graphics g){
g.drawLine(0, 0, 100, 100);
}
But I think this is wrong direction, because when I put something on graphics - it just stays there, I can't move or rotate it.
I have to clear whole graphics and draw it again to make kind of "animation", or there is easier way?
Edit:
I already know how to antialias (Hovercraft Full Of Eels already helped me in this - thanks).
Edit2:
My code actually looks like this:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainWindow extends JPanel {
private Point p1 = new Point(100, 100);
private Point p2 = new Point(740, 450);
public MainWindow() {
this.setPreferredSize(new Dimension(800, 600));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawLines(g);
}
private void drawLines(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.DARK_GRAY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
private void display() {
JFrame f = new JFrame("Main Window");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new MainWindow().display();
}
}
You state:
I tried to draw something by using Graphics object like this:
public void paint(Graphics g){
g.drawLine(0, 0, 100, 100);
}
But I think this is wrong direction, because when I put something on graphics - it just stays there, I can't move or rotate it.
I have to clear whole graphics and draw it again to make kind of "animation", or there is easier way?
Suggestions:
Don't hard-code your numbers. Use class fields (variables) instead so that your program can change the position of items drawn easily.
Don't override a component's paint(...) method. Instead override the paintComponent(Graphics g) method of an object that derives from JComponent or one of its children such as JPanel. This will give you the benefit of automatic double-buffering for smoother animation, and also will reduce the likelihood of erroneous drawing of a component's children or borders.
Cast your Graphics object to a Graphics2D object so that you can do more advanced drawing using classes that implement the Shape interface, including Rectangle2D, Ellipse2D, Line2D, Path2D, and many more.
Draw the background image as a BufferedImage using Graphics#drawImage(...) method, and then draw your moving images on top of this, again using the Graphics2D object and again changing the images drawn based on the state of the object (the values held by its fields).
Be careful when doing animations that you obey Swing threading rules, that you don't have any animation or game loops that tie up the Swing thread. A Swing Timer can allow you to create a quick and easy (albeit somewhat primitive) game loop.
For example:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class DailAnimation extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 350;
private static final Point2D CENTER = new Point2D.Double(PREF_W / 2.0,
PREF_W / 2.0);
private static final double RADIUS = PREF_W / 2.0;
private static final Color LARGE_TICK_COLOR = Color.green;
private static final Color CENTER_HUB_COLOR = Color.LIGHT_GRAY;
private static final Stroke LARGE_TICK_STROKE = new BasicStroke(3f);
private static final int LRG_TICK_COUNT = 9;
private static final double TOTAL_LRG_TICKS = 12;
private static final double LRG_TICK_OUTER_RAD = 0.9;
private static final double LRG_TICK_INNER_RAD = 0.8;
private static final int START_TICK = 10;
private static final double CENTER_HUB_RADIUS = 10;
public static final int MAX_SPEED = 100;
private static final double INIT_SPEED = 0;
private static final double DIAL_INNER_RAD = 0.02;
private static final double DIAL_OUTER_RAD = 0.75;
private static final Color DIAL_COLOR = Color.DARK_GRAY;
private BufferedImage backgroundImg;
private double speed;
private double theta;
private double cosTheta;
private double sinTheta;
public DailAnimation() {
setBackground(Color.white);
backgroundImg = createBackgroundImg();
setSpeed(INIT_SPEED);
}
public void setSpeed(double speed) {
if (speed < 0) {
speed = 0;
} else if (speed > MAX_SPEED) {
speed = MAX_SPEED;
}
this.speed = speed;
this.theta = ((speed / MAX_SPEED) * LRG_TICK_COUNT * 2.0 + START_TICK)
* Math.PI / TOTAL_LRG_TICKS;
cosTheta = Math.cos(theta);
sinTheta = Math.sin(theta);
repaint();
}
private BufferedImage createBackgroundImg() {
BufferedImage img = new BufferedImage(PREF_W, PREF_H,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(LARGE_TICK_COLOR);
g2.setStroke(LARGE_TICK_STROKE);
for (int i = 0; i < LRG_TICK_COUNT; i++) {
double theta = (i * 2.0 + START_TICK) * Math.PI / TOTAL_LRG_TICKS;
double cosTheta = Math.cos(theta);
double sinTheta = Math.sin(theta);
int x1 = (int) (LRG_TICK_INNER_RAD * RADIUS * cosTheta + CENTER.getX());
int y1 = (int) (LRG_TICK_INNER_RAD * RADIUS * sinTheta + CENTER.getY());
int x2 = (int) (LRG_TICK_OUTER_RAD * RADIUS * cosTheta + CENTER.getX());
int y2 = (int) (LRG_TICK_OUTER_RAD * RADIUS * sinTheta + CENTER.getY());
g2.drawLine(x1, y1, x2, y2);
}
g2.setColor(CENTER_HUB_COLOR);
int x = (int) (CENTER.getX() - CENTER_HUB_RADIUS);
int y = (int) (CENTER.getY() - CENTER_HUB_RADIUS);
int width = (int) (2 * CENTER_HUB_RADIUS);
int height = width;
g2.fillOval(x, y, width, height);
// g2.draw(ellipse);
g2.dispose();
return img;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(DIAL_COLOR);
int x1 = (int) (DIAL_INNER_RAD * RADIUS * cosTheta + CENTER.getX());
int y1 = (int) (DIAL_INNER_RAD * RADIUS * sinTheta + CENTER.getY());
int x2 = (int) (DIAL_OUTER_RAD * RADIUS * cosTheta + CENTER.getX());
int y2 = (int) (DIAL_OUTER_RAD * RADIUS * sinTheta + CENTER.getY());
g.drawLine(x1, y1, x2, y2);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
final DailAnimation mainPanel = new DailAnimation();
JFrame frame = new JFrame("DailAnimation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
int delay = 100;
new Timer(delay, new ActionListener() {
int speed = 0;
#Override
public void actionPerformed(ActionEvent evt) {
speed ++;
if (speed > DailAnimation.MAX_SPEED) {
((Timer)evt.getSource()).stop();
}
mainPanel.setSpeed(speed);
}
}).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Drawing a line via Graphics.drawLine() writes pixels directly to whatever is backing the Graphics instance. If you want to rotate the line, you must calculate what its coordinates should be when rotated. This is the only way to draw things in AWT and Swing.
You could write a needle class that maintained its angle, and then have it handle its rendering every frame.
Related
I'm currently working on a 2D game in Java for school. We have to use an Abstract Factory design pattern. For the 2D implementation I use a factory as follows:
public class Java2DFact extends AbstractFactory {
public Display display;
private Graphics g;
public Java2DFact() {
display = new Display(2000, 1200);
}
#Override
public PlayerShip getPlayership()
{
return new Java2DPlayership(display.panel);
}
In my display class I create a JFrame and Jpanel
public class Display {
public JFrame frame;
public JPanel panel;
public int width, height;
public Display(int width, int height) {
this.width = width;
this.height = height;
frame = new JFrame();
frame.setTitle("SpaceInvaders");
frame.setSize(1200,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel = new JPanel(){
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
}
};
panel.setFocusable(true);
frame.add(panel);
}
}
Now from my main gameloop I call the visualize method inside the Java2DPLayership class to visualize my Playership
public class Java2DPlayership extends PlayerShip {
private JPanel panel;
private Graphics2D g2d;
private Image image;
private BufferStrategy bs;
public Java2DPlayership(JPanel panel) {
super();
this.panel = panel;
}
public void visualize() {
try {
image = ImageIO.read(new File("src/Bee.gif"));
Graphics2D g = (Graphics2D) bs.getDrawGraphics();
//g.setColor(new Color(0, 0, 0));
//g.fillRect(10, 10, 12, 8);
g.drawImage(image, (int) super.getMovementComponent().x, (int) super.getMovementComponent().y, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
panel.repaint();
} catch(Exception e){
System.out.println(e.toString());
}
}
}
My goal is to pass around the JPanel to every entity and let it draw its contents onto the panel before showing it. However I can't seem to figure out how to do this. When using this approach by changing the Graphics of the panel I get a lot of flickering.
Here is a fully functional, albeit simple example, I wrote some time ago. It just has a bunch of balls bouncing off the sides of the panel. Notice that the render method of the Ball class accepts the graphics context from paintComponent. If I had more classes that needed to be rendered, I could have created a Renderable interface and have each class implement it. Then I could have a list of Renderable objects and just go thru them and call the method. But as I also said, that would need to happen quickly to avoid tying up the EDT.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Bounce extends JPanel {
private static final int COLOR_BOUND = 256;
private final static double INC = 1;
private final static int DIAMETER = 40;
private final static int NBALLS = 20;
private final static int DELAY = 5;
private final static int PANEL_WIDTH = 800;
private final static int PANEL_HEIGHT = 600;
private final static int LEFT_EDGE = 0;
private final static int TOP_EDGE = 0;
private JFrame frame;
private double rightEdge;
private double bottomEdge;
private List<Ball> balls = new ArrayList<>();
private Random rand = new Random();
private List<Long> times = new ArrayList<>();
private int width;
private int height;
public Bounce(int width, int height) {
this.width = width;
this.height = height;
frame = new JFrame("Bounce");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
addComponentListener(new MyComponentListener());
frame.pack();
frame.setLocationRelativeTo(null);
rightEdge = width - DIAMETER;
bottomEdge = height - DIAMETER;
for (int j = 0; j < NBALLS; j++) {
int r = rand.nextInt(COLOR_BOUND);
int g = rand.nextInt(COLOR_BOUND);
int b = rand.nextInt(COLOR_BOUND);
Ball bb = new Ball(new Color(r, g, b), DIAMETER);
balls.add(bb);
}
frame.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
public static void main(String[] args) {
new Bounce(PANEL_WIDTH, PANEL_HEIGHT).start();
}
public void start() {
/**
* Note: Using sleep gives a better response time than
* either the Swing timer or the utility timer. For a DELAY
* of 5 msecs between updates, the sleep "wakes up" every 5
* to 6 msecs while the other two options are about every
* 15 to 16 msecs. Not certain why this is happening though
* since the other timers are run on threads.
*
*/
Timer timer = new Timer(0,(ae)-> {repaint();
for (Ball b : balls) {
b.updateDirection();
}} );
timer.setDelay(5); // 5 ms.
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ball ball : balls) {
ball.render(g2d);
}
}
class MyComponentListener extends ComponentAdapter {
public void componentResized(ComponentEvent ce) {
Component comp = ce.getComponent();
rightEdge = comp.getWidth() - DIAMETER;
bottomEdge = comp.getHeight() - DIAMETER;
for (Ball b : balls) {
b.init();
}
}
}
class Ball {
private Color color;
public double x;
private double y;
private double yy;
private int ydir = 1;
private int xdir = 1;
private double slope;
private int diameter;
public Ball(Color color, int diameter) {
this.color = color;
this.diameter = diameter;
init();
}
public void init() {
// Local constants not uses outside of method
// Provides default slope and direction for ball
slope = Math.random() * .25 + .50;
x = (int) (rightEdge * Math.random());
yy = (int) (bottomEdge * Math.random()) + diameter;
xdir = Math.random() > .5 ? -1
: 1;
ydir = Math.random() > .5 ? -1
: 1;
y = yy;
}
public void render(Graphics2D g2d) {
g2d.setColor(color);
g2d.fillOval((int) x, (int) y, diameter, diameter);
}
public void updateDirection() {
x += (xdir * INC);
yy += (ydir * INC);
y = yy * slope;
if (x < LEFT_EDGE || x > rightEdge) {
xdir = -xdir;
}
if (y < TOP_EDGE || y > bottomEdge) {
ydir = -ydir;
}
}
}
}
I need the simplest way to rescale a drawing in java (for example a rectangle...). I found a way to "stretch" them:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.Dimension;
public class Stretch extends JFrame {
int originalHeight = 600;
int originalWidth = 600;
public Stretch() {
super("Stretch");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(originalWidth, originalHeight);
}
public static void main(String[] args) {
Stretch s = new Stretch();
s.setVisible(true);
}
public void paint(Graphics g) {
Dimension size = this.getBounds().getSize();
int rectWidth = 100;
int rectHeight = 130;
g.setColor(Color.white);
g.fillRect(0, 0, size.width, size.height);
g.setColor(Color.black);
g.drawRect(100, 100, rectWidth + size.width - originalWidth, rectHeight + size.height - originalHeight);
}
}
As you can see the formula is like that:
g.drawRect(100, 100, rectWidth + size.width - originalWidth, rectHeight + size.height - originalHeight);
Now how can I rescale the drawing? Width and height have to maintain the same proportion.
Thank you.
There are bascially two different approaches for this:
You can "scale the whole Graphics"
You can scale the actual shapes
The difference may be subtle in some cases, but can be important: When you scale the whole Graphics, then everything will be scaled. Particularly, when you scale it about 2.0, and then draw a line with a width of 1.0, the line will be drawn 2 pixels wide. Whether or not this is desired depends on the application case.
In order to scale the actual shapes, you can not use the drawRect method. Instead you will have to create Shape instances that represent the geometric shapes. You can then create scaled versions of these shapes with AffineTransform#createTransformedShape.
Here is an example that compares both approaches (and corrects some of the other issues that have been in your code). In both cases, the same rectangle with an original size of (10,13) is painted, scaled by a factor of 5.0.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ScalingDrawnObjects
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ScalingDrawnObjectsPanel p = new ScalingDrawnObjectsPanel();
f.getContentPane().add(p);
f.setSize(600,400);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class ScalingDrawnObjectsPanel extends JPanel
{
#Override
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D)gr;
Shape rectangle = new Rectangle2D.Double(2, 2, 10, 13);
g.setColor(Color.RED);
drawWithScaledGraphics(g, rectangle);
g.translate(100, 0);
drawScaledObject(g, rectangle);
}
private static void drawWithScaledGraphics(Graphics2D g, Shape shape)
{
AffineTransform oldAt = g.getTransform();
g.scale(5.0, 5.0);
g.draw(shape);
g.setTransform(oldAt);
}
private static void drawScaledObject(Graphics2D g, Shape shape)
{
AffineTransform at = AffineTransform.getScaleInstance(5.0, 5.0);
g.draw(at.createTransformedShape(shape));
}
}
EDIT In response to the comment
The code that I posted is not "complicated". It is as compilcated as it has to be, but not more. You should not extend JFrame and you should not override paint. You should create the GUI on the EDT. You should ...
However, you should not use code like the following, but maybe this is what you're looking for
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.Dimension;
public class Stretch extends JFrame {
int originalHeight = 600;
int originalWidth = 600;
public Stretch() {
super("Stretch");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(originalWidth, originalHeight);
}
public static void main(String[] args) {
Stretch s = new Stretch();
s.setVisible(true);
}
public void paint(Graphics g) {
Dimension size = this.getBounds().getSize();
int rectWidth = 100;
int rectHeight = 130;
g.setColor(Color.white);
g.fillRect(0, 0, size.width, size.height);
g.setColor(Color.black);
int w = rectWidth + size.width - originalWidth;
int h = rectHeight + size.height - originalHeight;
double sx = (double)w / rectWidth;
double sy = (double)h / rectHeight;
double s = Math.min(sx, sy);
int fw = (int)(s * rectWidth);
int fh = (int)(s * rectHeight);
g.drawRect(100, 100, fw, fh);
}
}
How about multiplying the width and the height by the scale you want?
So if you want to scale it by 2:
g.drawRect(100, 100, 2 * (rectWidth + size.width - originalWidth), 2 * (rectHeight + size.height - originalHeight));
I was reading Core Java and encountered this code snippet:
package draw;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DrawTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new DrawFrame();
frame.setTitle("DrawTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
public DrawFrame()
{
add(new DrawComponent());
pack();
}
}
class DrawComponent extends JComponent
{
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 400;
public void paintCompent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// draw a rectangle
double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
// draw a diagonal line
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
// draw a circle with the same center
double centerX = rect.getCenterX();
double centerY = rect.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
public Dimension getPreferredSize()
{
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
I tried this code on Eclipse, it did run but, instead of rectangles, ellipse, diagonal lines and circle, there appeared nothing in the frame. I double-checked the code against the book, there was no typo. What is wrong?
There's a spelling mistake...
public void paintCompent(Graphics g) {
should be
public void paintComponent(Graphics g) {
This is why you should use the #Override annotation, as it will give you a compile time error when you try to override a method that doesn't exist within the parent hierarcy.
You should also be calling super.paintComponent(g); before performing any custom painting
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);
}
}
}
This must be rather trivial and straight forward, but I cannot figure it out.
This is what my JPanel looks like, it is added to a JFrame:
private class RadarPanel extends JPanel {
public RadarPanel() {
super();
this.repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//painting logic here
//repaint in 500 ms
this.repaint(500);
}
}
Now, when I resize the JFrame this JPanel starts getting redrawn all the time. However, when I do not resize the JFrame the JPanel's paintComponent method does not seem to get called, even though I call repaint in the constructor.
Any advice? Thanks.
UPDATE:
more complete code (everything except drawing logic):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PlayerRadar extends JFrame {
private static final long serialVersionUID = 230324190;
//settings
private static final int windowWidth = 300;
private static final int windowHeight = 300;
private static final int maxDistance = 250;
//components
private PlayerRadar radarWindow;
private JPanel radarPanel;
public PlayerRadar(String title) {
super(title);
//set reference
radarWindow = this;
//create radar window
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
this.setAlwaysOnTop(true);
this.setBackground(new Color(0xFFFFFF));
this.setBounds(screenSize.width - windowWidth, 0, windowWidth, windowHeight);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
radarWindow.setVisible(false);
}
});
this.setVisible(true);
//create a JPanel for drawing
radarPanel = new RadarPanel();
radarPanel.setBounds(0, 0, windowWidth, windowHeight);
radarPanel.setBackground(new Color(0xFFFFFF));
//add to frame
this.getContentPane().add(radarPanel);
}
private class RadarPanel extends JPanel {
private static final long serialVersionUID = 230324191;
private static final int repaintInterval = 500;
public RadarPanel() {
super();
}
#Override
public void paint(Graphics g) {
super.paint(g);
//draw player oval (center of the frame)
g.setColor(Color.BLUE); //blue
int ovalWidth = (int) Math.round(this.getWidth() / 30);
int ovalHeight = (int) Math.round(this.getHeight() / 30);
int playerLocalX = (int) Math.round(this.getWidth() / 2);
int playerLocalY = (int) Math.round(this.getHeight() / 2);
int ovalX = playerLocalX - ovalWidth / 2;
int ovalY = playerLocalY - ovalHeight / 2;
g.fillOval(ovalX, ovalY, ovalWidth, ovalHeight);
g.setColor(Color.BLACK); //black
g.drawOval(ovalX, ovalY, ovalWidth, ovalHeight);
//get info of the player itself
PlayerInfo thisPlayer = GameUtil.getPlayerInfo();
float playerPosZ = thisPlayer.position[0];
float playerPosX = thisPlayer.position[2];
//float playerRotRad = thisPlayer.rotation;
//set rectangle specs
int rectWidth = this.getWidth() / 40;
int rectHeight = this.getWidth() / 40;
//only continue if we have information about our player
if (thisPlayer != null) {
//get nearby players
ArrayList<PlayerInfo> playersInfo = GameUtil.getNearbyPlayers();
//for each other player, draw a rectangle
for (PlayerInfo playerInfo : playersInfo) {
//get data
float posZ = playerInfo.position[0];
float posX = playerInfo.position[2];
//float rotRad = playerInfo.rotation;
//calculate relative x and y
int rectX = playerLocalX + Math.round((posX - playerPosX) / maxDistance * this.getWidth() / 2) - rectWidth / 2;
int rectY = playerLocalY + ovalHeight / 2 + Math.round((playerPosZ - posZ) / maxDistance * this.getHeight() / 2) - rectHeight / 2;
//draw rectangle
g.setColor(Color.RED);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
g.setColor(Color.BLACK);
g.drawRect(rectX, rectY, rectWidth, rectHeight);
}
}
//repaint soon
this.repaint(repaintInterval);
}
}
}
You where correct the first time. Custom painting is done in the paintComponent() method, NOT the paint() method.
You should NEVER invoke repaint() from within the paintComponent() method, since that will result in an infinite loop.
If you want to animate the painting, then you should be using a Swing Timer to schedule the animation.
You should not be using use setSize(). That is the job of the layout manager. Instead you can override the getPreferredSize() method of the panel (or use setPreferredSize()) and then you can pack() the frame, instead of setting its size.
The panel should be added to the frame BEFORE the frame is made visible otherwise it has a size of (0, 0) which means there is nothing to paint.
It won't repaint until your form is shown and graphics is initialized. I don't think calling repaint in constructor is a good idea. It will repaint once the component is visible.