hello i'm having trouble drawing arrows from center of a circle to center of the next one, each circle is from a xml elsewhere let's consider size is 14.
why does my code seems not to do the trick?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.swing.JFrame;
Just setting the frame
public class GRAPHICS_REPRESENTATION extends JFrame {
private Vector<Point> point_tab;
public GRAPHICS_REPRESENTATION() {
super("graphic");
point_tab = new Vector<Point>(0);
setSize(800, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Drawing a circle (found and reworked from here)
// Convenience method to draw from center with radius
public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {
Graphics2D cg2 = (Graphics2D) cg.create();
cg2.drawOval(xCenter - r, yCenter - r, r, r);
}// end drawCircle
the problem method
private void disposeScene(Graphics g1, int x1, int y1, int r) {
Graphics2D g = (Graphics2D) g1.create();
AffineTransform at = g.getTransform();
AffineTransform at2 = new AffineTransform();
at2 = AffineTransform.getScaleInstance(0.5, 0.5); // scaling à faire en 1er
g.transform(at2); // prise en compte de la matrice
at2 = AffineTransform.getTranslateInstance(getWidth() / 2 + x1 + r / 2, getHeight() / 2 - y1 - r / 2); // centrage
g.transform(at2);
double angle = (double) Math.cos(0);
for (int i = 0; i < 14; i++) {
angle = Math.rint(angle / (i + 1));
g.setColor(Color.RED);
drawCircle(g, 0, 0, 2 * r);
Point center = new Point();
center.setLocation(g.getTransform().getTranslateX() / 2 + r / 2 + x1 / 2,
g.getTransform().getTranslateY() / 2 - r / 2 - y1 / 2);
point_tab.add(center);
at2.concatenate(AffineTransform.getRotateInstance(angle)); // rotation autour d'un centre
g.transform(at2);
System.out.println(point_tab.elementAt(i).getX() + "," + point_tab.elementAt(i).getY());
g.setColor(Color.BLUE);
if (i + 1 < point_tab.size()) {
drawArrow(g, point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY(),
point_tab.elementAt(i + 1).getX(), point_tab.elementAt(i + 1).getY());
} else {
drawArrow(g, point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY(),
point_tab.elementAt(0).getX(), point_tab.elementAt(0).getY());
}
}
g.setTransform(at);
}
drawing an arrow from src to dst (found here and reworked)
private final int ARR_SIZE = 4;
private void drawArrow(Graphics g1, double xsrc, double ysrc, double xdst, double ydst) {
Graphics2D g = (Graphics2D) g1.create();
double dx = xdst - xsrc, dy = ydst - ysrc; // distances
double angle = Math.atan2(dy, dx);
int len = (int) Math.sqrt(dx * dx + dy * dy);
AffineTransform at = g.getTransform();
AffineTransform at2 = new AffineTransform();
at2=AffineTransform.getTranslateInstance(xsrc, ysrc);
at2.concatenate(AffineTransform.getRotateInstance(angle));
g.transform(at2);
// Draw horizontal arrow starting in (0, 0)
g.drawLine(0, 0, len, 0);
g.fillPolygon(new int[] { len, len - ARR_SIZE, len - ARR_SIZE, len }, new int[] { 0, -ARR_SIZE, ARR_SIZE, 0 },
4);
g.setTransform(at);
}
main method
public void paint(Graphics g) {
disposeScene(g, getWidth()/4,getHeight()/4,40);
}
Here the solution I found by myself
/**
* #brief draw the scene with all shapes set up
* #param g1
* #param x1
* #param y1
* #param xtg
* #param r
*/
private void disposeScene(Graphics g1, int x1, int y1, XML_TO_GRAPH xtg, int r) {
Graphics2D g = (Graphics2D) g1.create();
g.translate(getWidth() / 2, getHeight() / 2);
drawCircle(g, 0, 0, (x1+y1)/2); // cercle fictif
for (int i = 0; i < xtg.getsceneVector().size(); i++) {
double angle = Math.toRadians(360.0); // radian mieux 2pi
angle = (angle*i / xtg.getsceneVector().size());
System.out.println("angle(" + i + ")=" + angle);
g.setColor(Color.RED);
drawCircle(g, (int) (Math.cos(angle) * x1), (int) (Math.sin(angle) * y1), r);
Point center_big_circle = new Point();
center_big_circle.setLocation((0), (0)); // centre du grand cercle fictif
Point center_little_circle = new Point();
center_little_circle.setLocation((Math.cos(angle) * (x1)), (Math.sin(angle) * (y1))); // décalage vers les
// bords
System.out.println("centre(" + i + ")=" + center_little_circle.getX() + "," + center_little_circle.getY());
point_tab.add(center_little_circle);
g.setColor(Color.BLACK);
drawString(g, (int) center_little_circle.getX()-r, (int) center_little_circle.getY()-r, 16, "scène : " + i);
System.out.println(point_tab.elementAt(i).getX() + "," + point_tab.elementAt(i).getY());
g.setColor(Color.BLUE);
if (i + 1 < point_tab.size()) {// si existe
drawArrow(g, point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY(),
point_tab.elementAt(i + 1).getX(), point_tab.elementAt(i + 1).getY());
// g.setColor(Color.BLACK);
// drawString(g, (int)(( point_tab.elementAt(i+1).getX()-
point_tab.elementAt(i).getX())/2), (int) ((point_tab.elementAt(i+1).getY()-
point_tab.elementAt(i).getY())/2), 16, "X : " +
xtg.getcount_occurence().toString());
//idem
drawArrow(g, point_tab.elementAt(i+1).getX(), point_tab.elementAt(i+1).getY(),
point_tab.elementAt(i).getX(), point_tab.elementAt(i).getY());
// drawString(g, (int)(( point_tab.elementAt(i).getX()-
point_tab.elementAt(i+1).getX())/2), (int) ((point_tab.elementAt(i).getY()-
point_tab.elementAt(i+1).getY())/2), 16, "X : " +
xtg.getcount_occurence().toString());
}
}
}
and
// Convenience method to draw from center with radius
/**
*
* #param cg
* #param xCenter
* #param yCenter
* #param r
*/
public void drawCircle(Graphics cg, int xCenter, int yCenter, int r) {
Graphics2D cg2 = (Graphics2D) cg.create();
System.out.println("Center at: " + (xCenter - r) + "," + (yCenter - r));
cg2.drawOval(xCenter - r, yCenter - r, 2 * r, 2 * r);
}// end drawCircle
and convenient drawString method :
/**
*
* #param g1
* #param x
* #param y
* #param size
* #param str
*/
private void drawString(Graphics g1, int x, int y, int size, String str) {
Graphics2D g = (Graphics2D) g1.create();
g.setFont(new Font("Times New Roman", Font.PLAIN, size));
g.drawString(str, x, y);
}
and paint :
public void paint(Graphics g) {
disposeScene(g, (int) (getWidth() / 3), (int) (getHeight() / 3), 20);
}
Related
I'm trying to make some shapes with Java. I created two rectangles with two different colors but I want to create a star shape and I can't find useful source to help me doing this.
Here is my code:
import java.awt.*;
import javax.swing.*;
public class shapes extends JPanel{
#Override
public void paintComponent(Graphics GPHCS){
super.paintComponent(GPHCS);
GPHCS.setColor(Color.BLUE);
GPHCS.fillRect(25,25,100,30);
GPHCS.setColor(Color.GRAY);
GPHCS.fillRect(25,65,100,30);
GPHCS.setColor(new Color(190,81,215));
GPHCS.drawString("This is my text", 25, 120);
}
}
You could try using a polygon and some basic math:
int midX = 500;
int midY = 340;
int radius[] = {118,40,90,40};
int nPoints = 16;
int[] X = new int[nPoints];
int[] Y = new int[nPoints];
for (double current=0.0; current<nPoints; current++)
{
int i = (int) current;
double x = Math.cos(current*((2*Math.PI)/max))*radius[i % 4];
double y = Math.sin(current*((2*Math.PI)/max))*radius[i % 4];
X[i] = (int) x+midX;
Y[i] = (int) y+midY;
}
g.setColor(Color.WHITE);
g.fillPolygon(X, Y, nPoints);
You can also use existing classes e.g. http://java-sl.com/shapes.html for regular polygons and stars.
The Polygon class can be considered as a legacy class that has been there since Java 1.0, but should hardly be used any more in new code. The odd way of specifying the x/y coordinates in separate arrays, and, more importantly, the fact that it only supports int[] arrays limits its application areas. Although it implements the Shape interface, there are more modern implementations of this interface that can be used to represent polygons. In most cases, describing the polygon as a Path2D is easier and more flexible. One can create a Path2D p = new Path2D.Double(); and then do a sequence of moveTo and lineTo calls to geneate the desired shape.
The following program shows how the Path2D class may be used to generate star shapes. The most important method is the createStar method. It is very generic. It receives
the center coordinates for the star
the inner and outer radius of the star
the number of rays that the star should have
the angle where the first ray should be (i.e. the rotation angle of the star)
If desired, a simpler method may be wrapped around this one - as with the createDefaultStar example in the code below.
The program shows different stars, painted as lines and filled with different colors and radial gradient paints, as examples:
The complete program as a MCVE:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RadialGradientPaint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Path2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawStarShape
{
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);
f.getContentPane().add(new DrawStarShapePanel());
f.setSize(600, 600);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class DrawStarShapePanel extends JPanel
{
#Override
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr;
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g.draw(createDefaultStar(50, 200, 200));
g.setPaint(Color.RED);
g.fill(createStar(400, 400, 40, 60, 10, 0));
g.setPaint(new RadialGradientPaint(
new Point(400, 200), 60, new float[] { 0, 1 },
new Color[] { Color.RED, Color.YELLOW }));
g.fill(createStar(400, 200, 20, 60, 8, 0));
g.setPaint(new RadialGradientPaint(
new Point(200, 400), 50, new float[] { 0, 0.3f, 1 },
new Color[] { Color.RED, Color.YELLOW, Color.ORANGE }));
g.fill(createStar(200, 400, 40, 50, 20, 0));
}
private static Shape createDefaultStar(double radius, double centerX,
double centerY)
{
return createStar(centerX, centerY, radius, radius * 2.63, 5,
Math.toRadians(-18));
}
private static Shape createStar(double centerX, double centerY,
double innerRadius, double outerRadius, int numRays,
double startAngleRad)
{
Path2D path = new Path2D.Double();
double deltaAngleRad = Math.PI / numRays;
for (int i = 0; i < numRays * 2; i++)
{
double angleRad = startAngleRad + i * deltaAngleRad;
double ca = Math.cos(angleRad);
double sa = Math.sin(angleRad);
double relX = ca;
double relY = sa;
if ((i & 1) == 0)
{
relX *= outerRadius;
relY *= outerRadius;
}
else
{
relX *= innerRadius;
relY *= innerRadius;
}
if (i == 0)
{
path.moveTo(centerX + relX, centerY + relY);
}
else
{
path.lineTo(centerX + relX, centerY + relY);
}
}
path.closePath();
return path;
}
}
I have 2 method.
1)
public static Bitmap drawStar(int W, int H, int color, boolean andRing)
{
Path path = new Path();
Bitmap output = Bitmap.createBitmap(W, H, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
float midW ,min ,fat ,half ,radius;
if(andRing)
{
midW = W / 2;
min = Math.min(W, H);
half = min / 2;
midW = midW - half;
fat = min / 17;
radius = half - fat;
paint.setStrokeWidth(fat);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(midW + half, half, radius, paint);
path.reset();
paint.setStyle(Paint.Style.FILL);
path.moveTo( half * 0.5f, half * 0.84f);
path.lineTo( half * 1.5f, half * 0.84f);
path.lineTo( half * 0.68f, half * 1.45f);
path.lineTo( half * 1.0f, half * 0.5f);
path.lineTo( half * 1.32f, half * 1.45f);
path.lineTo( half * 0.5f, half * 0.84f);
}
else
{
min = Math.min(W, H);
half = min/2;
path.reset();
paint.setStyle(Paint.Style.FILL);
path.moveTo( half * 0.1f , half * 0.65f);
path.lineTo( half * 1.9f , half * 0.65f);
path.lineTo( half * 0.40f , half * 1.65f);
path.lineTo( half , 0 );
path.lineTo( half * 1.60f, half * 1.65f);
path.lineTo( half * 0.1f, half * 0.65f);
}
canvas.drawPath(path, paint);
return output;
}
2)
public static Bitmap drawStar(int W,int H,int spikes,int innerRadius,int outerRadius, int backColor,boolean border, int borderColor)
{
if(W < 10)
W = 10;
if(H < 10)
H = 10;
if(spikes < 5)
spikes = 5;
int smallL = W;
if(H < W)
smallL = H;
if(outerRadius > smallL/2)
outerRadius = smallL/2;
if(innerRadius < 5)
innerRadius = 5;
if(border)
{
outerRadius -=2;
innerRadius -=2;
}
Path path = new Path();
Bitmap output = Bitmap.createBitmap(W, H, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(backColor);
int cx = W/2;
int cy = H/2;
double rot = Math.PI / 2 * 3;
float x,y;
double step = Math.PI / spikes;
path.moveTo(cx, cy - outerRadius);
for (int i = 0; i < spikes; i++)
{
x = (float) (cx + Math.cos(rot) * outerRadius);
y = (float) (cy + Math.sin(rot) * outerRadius);
path.lineTo(x, y);
rot += step;
x = (float) (cx + Math.cos(rot) * innerRadius);
y = (float) (cy + Math.sin(rot) * innerRadius);
path.lineTo(x, y);
rot += step;
}
path.lineTo(cx, cy - outerRadius);
path.close();
canvas.drawPath(path, paint);
if(border)
{
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
paint.setColor(borderColor);
canvas.drawPath(path, paint);
}
return output;
}
I am working on a compass in java. First I created a UI prototyp for my compass and created a working SSCCE of it, where you can click on the panel and the needle is pointed to another direction, which differs about 15 degree. This is the code:
public class TestFrame extends JFrame {
public TestFrame() {
initComponents();
}
public void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(new Point((int) (Toolkit.getDefaultToolkit().getScreenSize().width / 2) - 400, (int) (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - 250));
setSize(500, 500);
setVisible(true);
CompassPanel c = new CompassPanel();
add(c, BorderLayout.CENTER);
}
public class CompassPanel extends JPanel {
Image bufImage;
Graphics bufG;
private int circleX, circleY, circleRadius;
private int[] xPoints, yPoints;
private double rotationAngle = Math.toRadians(0);
public CompassPanel() {
setVisible(true);
addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
rotationAngle = rotationAngle + Math.toRadians(15);
repaint();
}
});
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
circleRadius = (int) (getWidth() * 0.7);
circleX = 50;
circleY = 50;
g2d.setColor(Color.BLACK);
for (int angle = 0; angle <= 360; angle += 5) {
double sin = Math.sin(Math.toRadians(angle));
double cos = Math.cos(Math.toRadians(angle));
int x1 = (int) ((circleX + circleRadius / 2) - cos * (circleRadius * 0.37) - sin * (circleRadius * 0.37));
int y1 = (int) ((circleY + circleRadius / 2) + sin * (circleRadius * 0.37) - cos * (circleRadius * 0.37));
g2d.setColor(Color.BLACK);
g2d.drawLine(x1, y1, (circleX + circleRadius / 2), (circleY + circleRadius / 2));
}
g2d.setFont(new Font("Arial", Font.BOLD, 11));
g2d.drawString("WEST", circleX - 45, circleY + circleRadius / 2 + 4);
g2d.drawString("EAST", circleX + circleRadius + 13, circleY + circleRadius / 2 + 4);
g2d.drawString("NORTH", circleX + circleRadius / 2 - 14, circleY - 15);
g2d.drawString("SOUTH", circleX + circleRadius / 2 - 14, circleY + circleRadius + 25);
g2d.setColor(Color.WHITE);
g2d.fillOval(circleX, circleY, circleRadius, circleRadius);
g2d.setColor(Color.BLACK);
g2d.drawOval(circleX, circleY, circleRadius, circleRadius);
xPoints = new int[] { (int) (circleX + circleRadius / 2),
(int) (circleX + circleRadius * 0.25),
(int) (circleX + circleRadius / 2),
(int) (circleX + circleRadius * 0.75) };
yPoints = new int[] { (int) (circleY + 30),
(int) (circleY + circleRadius * 0.85),
(int) (circleY + circleRadius * 0.6),
(int) (circleY + circleRadius * 0.85) };
Polygon fillPoly = new Polygon(xPoints, yPoints, 4);
Polygon outerPoly = new Polygon(xPoints, yPoints, 4);
int rotationX = circleX + (circleRadius / 2);
int rotationY = circleX + (circleRadius / 2);
g2d.setColor(Color.green);
g2d.fillOval(rotationX, rotationY, 5, 5);
AffineTransform a = g2d.getTransform().getRotateInstance(rotationAngle, rotationX, rotationY);
g2d.setTransform(a);
g2d.setColor(Color.RED);
g2d.fillPolygon(fillPoly);
g2d.setColor(Color.black);
g2d.draw(outerPoly);
}
#Override
public void update(Graphics g) {
int w = this.getSize().width;
int h = this.getSize().height;
if (bufImage == null) {
bufImage = this.createImage(w, h);
bufG = bufImage.getGraphics();
}
bufG.setColor(this.getBackground());
bufG.fillRect(0, 0, w, h);
bufG.setColor(this.getForeground());
paint(bufG);
g.drawImage(bufImage, 0, 0, this);
}
public void setRotationAngle(int angle) {
rotationAngle = angle;
}
}
public static void main(String[] args) {
new TestFrame();
}
}
When I implement this panel into my application, the needle is not drawn as it is in the SSCCE. It is drawn a bit higher and on the left of the position it is meant to be. When I click on the panel and rotate the needle, the rotation works fine and the needle is painted where it belongs.
I add the panel like this to my application. The sensorPanel is a JPanel in a TabbedPane.
public JPanel createSensorPanel(){
sensorPanel = new JPanel(new MigLayout("fill, insets 3"));
CompassPanel compassPanel = new CompassPanel();
sensorPanel.add(compassPanel, "wrap");
return sensorPanel;
}
Why is the Polygon of the needle not drawn at the position it is drawn in the SSCCE?
EDIT:
Here is a picture of the problem.
If you look closer what's going on on your image, than you'll see, that affine transform is the problem.
Looks like that affine transforms are related to top parent not the current child component (see java Affine Transform correct order).
The quick and dirty solution would be to translate the arrow as the parents are translated (based on this answer)
AffineTransform a = g2d.getTransform().
getRotateInstance(rotationAngle, rotationX, rotationY)
.translate(parent.getX(), parent.getY()) // use instance of real parent instead
.translate(tabpane.getX(), tabpane.getY()); // use instance of JTabbedPane instead
But much more convenient would be some common solution, something like this one.
I wrote this polar clock today and i am almost finished exept i want to align my text inside the line similar to this. Does anyone know how to do this? Ive tried to use FontRenderContext and font metrics but i cant seem to get it to work. Here is the whole source code so you can compile it and see for yourselves.
import java.applet.Applet;
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.Calendar;
import java.util.TimeZone;
public class Clock extends Applet implements Runnable {
int[][] colorsInt = {{20,20,20},{100,100,50},{50,100,100},{10,170,50},{79,29,245},{24,69,234},{253,24,103}};
Color[] colors;
int size;
int radius;
boolean anitalias = false;
static final float HPI = (float)(Math.PI / 180f);
public void start() {
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
new Thread(this).start();
}
public void run() {
setSize(500, 500); // For AppletViewer, remove later.
// Set up the graphics stuff, double-buffering.
BufferedImage screen = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)screen.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
WritableRaster wr = screen.getRaster();
Graphics appletGraphics = getGraphics();
// Some variables to use for the fps.
long fpstn = 1000000000 / 600;
int tick = 0, fps = 0, acc = 0;
long lastTime = System.nanoTime();
// Vars
Calendar c;
size = 500;
radius = size / 2;
Arc2D.Float arch;
float scale, radians;
long miliSecond;
int second, minute, hour, month, year, dayOfWeek, dayOfMonth, dayOfYear, daysInMonth, daysInYear;
float[] tvars = new float[6];
float[] vars = new float[6];
String[] names = new String[6];
FontMetrics fm = g.getFontMetrics();
Font font = g.getFont();
FontRenderContext frc = g.getFontRenderContext();
GlyphVector gv = font.createGlyphVector(frc, "Hello world");
int length = gv.getNumGlyphs();
// Init
initColors();
for (int i = 0; i < vars.length; i++)
vars[i] = 0;
// Game loop.
while (true) {
long now = System.nanoTime();
acc += now - lastTime;
tick++;
if (acc >= 1000000000L) {
acc -= 1000000000L;
fps = tick;
tick = 0;
}
// Update
c = Calendar.getInstance();
miliSecond = c.get(Calendar.MILLISECOND);
second = c.get(Calendar.SECOND);
minute = c.get(Calendar.MINUTE);
hour = c.get(Calendar.HOUR_OF_DAY);
dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
dayOfYear = c.get(Calendar.DAY_OF_YEAR);
dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
month = c.get(Calendar.MONTH);
daysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
daysInYear = c.getActualMaximum(Calendar.DAY_OF_YEAR);
tvars[0] = (second * 1000 + miliSecond) / 60000f * 360f;
tvars[1] = (minute * 60f + second) / 3600f * 360f;
tvars[2] = (hour * 60f + minute) / 1440f * 360f;
tvars[3] = ((dayOfWeek - 2) * 24f + hour) / 168f * 360f;
tvars[4] = ((dayOfMonth - 1) * 24f + hour) / (daysInMonth * 24f) * 360f;
tvars[5] = dayOfYear / (float)daysInYear * 360f;
for (int i = 0; i < vars.length; i++) {
if (tvars[i] - vars[i] > 1) {
vars[i] += (tvars[i] - vars[i]) / 15;
} else if(tvars[i] - vars[i] < -1) {
vars[i] -= (vars[i] - tvars[i]) / 15;
} else {
vars[i] = tvars[i];
}
}
names[0] = second + " Second" + (second > 1 ? "s" : "");
lastTime = now;
// Render
g.setColor(colors[0]);
g.fillRect(0, 0, size, size);
for (int i = 0; i < vars.length; i++) {
scale = i / (float)vars.length * radius * 1.7f;
g.setColor(colors[0]);
g.fillOval((int)(scale / 2), (int)(scale / 2), (int)(size - scale), (int)(size - scale));
g.setColor(colors[i + 1]);
scale += 15;
arch = new Arc2D.Float(scale / 2, scale / 2, size - scale, size - scale, 450 - vars[i], vars[i], Arc2D.PIE);
g.fill(arch);
g.setColor(Color.WHITE);
radians = (vars[i]) * HPI;// vars[i] - 90
scale = ((float)(vars.length - i) / (float)vars.length * (float)radius / 2f * 1.7f) + 15f;
g.translate(radius, radius);
System.out.println(i + ": " + ((1 - scale / radius) * 2));
for (int j = 0; j < names[0].length(); j++) {
char ch = names[0].charAt(j);
radians = ((vars[i] - (names[0].length() - j) * 2) * (1 + (1 - scale / radius) * 2)) * HPI;
g.rotate(radians);
g.drawString(ch + "", 0, -scale);
g.rotate(-radians);
}
g.translate(-radius, -radius);
/*float x = (float)Math.cos(radians) * scale;
float y = (float)Math.sin(radians) * (vars.length - i) / vars.length * radius / 2 * 1.7f;
g.drawRect((int)x + size / 2, (int)y + size / 2, 10, 10);*/
}
scale = vars.length / (float)vars.length * radius * 1.7f;
g.setColor(colors[0]);
g.fillOval((int)(scale / 2), (int)(scale / 2), (int)(size - scale), (int)(size - scale));
g.setColor(Color.WHITE);
g.drawString("FPS " + String.valueOf(fps), 20, 30);
// Draw the entire results on the screen.
appletGraphics.drawImage(screen, 0, 0, null);
do {
Thread.yield();
} while (System.nanoTime() - lastTime < 0);
if (!isActive()) {
return;
}
}
}
public void initColors() {
colors = new Color[colorsInt.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = new Color(colorsInt[i][0], colorsInt[i][1], colorsInt[i][2]);
}
}
}
Here's a simple example of rotating text.
Addendum: You'll want to adjust the the text's radial starting point by stringWidth(name[n]). Your program appears to be rotating individual characters in a effort to follow the arc, while the example appears to be drawing the text in a straight line tangent to the arc. The latter approach may prove simpler. For example, this variation centers the labels across the arc's getStartPoint():
for (int i = 0; i < vars.length; i++) {
...
String s = names[0];
int w = fm.stringWidth(s);
int h = fm.getHeight() + fm.getMaxDescent();
Point2D p = arch.getStartPoint();
int x = (int) p.getX();
int y = (int) p.getY();
radians = (vars[i]) * HPI;
g.rotate(radians, x, y);
g.drawString(s, x - w / 2, y + h);
g.rotate(-radians, x, y);
}
For convenience the code above does rotate() to and fro; for comparison, here's the original example showing repeated concatenations of rotate():
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/6238037 */
public class RotateText extends JPanel {
private static final Font f = new Font("Serif", Font.BOLD, 32);
private static final String s = "Hello World!";
private static final Color[] colors = {
Color.red, Color.green, Color.blue, Color.cyan
};
private Graphics2D g2d;
private AffineTransform at;
public RotateText() {
setPreferredSize(new Dimension(400, 400));
}
#Override
public void paintComponent(Graphics g) {
g2d = (Graphics2D) g;
g2d.setFont(f);
g2d.setColor(Color.black);
g2d.fillRect(0, 0, getWidth(), getHeight());
at = g2d.getTransform();
int w = this.getWidth();
int h = this.getHeight();
int w2 = g2d.getFontMetrics().stringWidth(s) / 2;
int h2 = 2 * g2d.getFontMetrics().getHeight() / 3;
render(0, w / 2 - w2, h - h2);
render(1, h2, h / 2 - w2);
render(2, w / 2 + w2, h2);
render(3, w - h2, h / 2 + w2);
g2d.setTransform(at);
g2d.setColor(Color.yellow);
g2d.fillRect(w / 3, h / 3, w / 3, h / 3);
}
private void render(int n, int x, int y) {
g2d.setColor(colors[n]);
g2d.setTransform(at);
g2d.rotate(n * Math.PI / 2, x, y);
g2d.drawString(s, x, y);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
//#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new RotateText(), BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
}
You have to be able to draw text along the curves. There are several ways to do it, but the simplest one is to use Stroke API. You can find an example at http://www.jhlabs.com/java/java2d/strokes/
The other way is using affine transforms. The example is at http://www.java2s.com/Code/Java/2D-Graphics-GUI/Drawtextalongacurve.htm
I'm trying to develop some sort of paint using Java.
I have a JComponent that is located inside of a JPanel.
I already can draw lines and rectangles into that JComponent.
Now, how can I export this drawings as an image (png, gif, jpg)?
I tried this:
BufferedImage b = new BufferedImage(1700,1100,BufferedImage.TYPE_INT_RGB);
this.print(getGraphics());
try{ImageIO.write(b,"png",new File("test.png"));}catch (Exception e) {}
But that only creates a .png file all black.
Help!!!
RESOLVED!!!
BufferedImage bi = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
this.paint(g); //this == JComponent
g.dispose();
try{ImageIO.write(bi,"png",new File("test.png"));}catch (Exception e) {}
First of all, print() is the incorrect method.
What I guess should work (haven't tested it yet) is:
get the BufferedImage's Graphics (b.createGraphics()) and use that graphics object to paint() your panel/component.
(e.g. yourPanel.paint(b.createGraphics());)
this is a demo:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
#SuppressWarnings("serial")
public class DrawGraph extends JPanel {
private static final int PREF_W = 1000;
private static final int PREF_H = 800;
private static final int BORDER_GAP = 25;
private static final int PADDING = 25;
private static final Color GRAPH_COLOR = Color.green;
private static final Color GRAPH_POINT_COLOR = new Color(100, 100, 100, 180);
private static final Color GRID_COLOR = new Color(200, 200, 200, 200);
private static final Stroke GRAPH_STROKE = new BasicStroke(3f);
private static final int GRAPH_POINT_WIDTH = 4;
private static final int Y_HATCH_CNT = 10;
private List<Double> scores;
public DrawGraph(List<Double> scores2) {
this.scores = scores2;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double xScale = ((double) getWidth() - (2 * BORDER_GAP)-PADDING) / (scores.size() - 1);
double yScale = ((double) getHeight() - (2 * BORDER_GAP)-PADDING) / (getMaxScore() - getMinScore());
List<Point> graphPoints = new ArrayList<Point>();
for (int i = 0; i < scores.size(); i++) {
int x1 = (int) (i * xScale + BORDER_GAP + PADDING);
int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + BORDER_GAP);
graphPoints.add(new Point(x1, y1));
}
g2.setColor(Color.WHITE);
g2.fillRect(BORDER_GAP + PADDING, BORDER_GAP, getWidth() - (2 * BORDER_GAP) - PADDING, getHeight() - 2 * BORDER_GAP - PADDING);
g2.setColor(Color.BLACK);
g2.drawLine(BORDER_GAP + PADDING, getHeight() - BORDER_GAP - PADDING, BORDER_GAP + PADDING, BORDER_GAP);
g2.drawLine(BORDER_GAP + PADDING, getHeight() - BORDER_GAP - PADDING, getWidth() - BORDER_GAP, getHeight() - BORDER_GAP - PADDING);
for (int i = 0; i < Y_HATCH_CNT + 1; i++) {
int x0 = BORDER_GAP + PADDING;
int x1 = GRAPH_POINT_WIDTH + BORDER_GAP + PADDING;
int y0 = getHeight() - ((i * (getHeight() - BORDER_GAP * 2 - PADDING)) / Y_HATCH_CNT + BORDER_GAP + PADDING);
int y1 = y0;
if (scores.size() > 0) {
g2.setColor(GRID_COLOR);
g2.drawLine(BORDER_GAP + PADDING + 1 + GRAPH_POINT_WIDTH, y0, getWidth() - BORDER_GAP, y1);
g2.setColor(Color.BLACK);
String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / Y_HATCH_CNT)) * 100)) / 100.0 + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(yLabel);
g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
}
g2.drawLine(x0, y0, x1, y1);
}
for (int i = 0; i < scores.size(); i++) {
if (scores.size() > 1) {
int x0 = i * (getWidth() - BORDER_GAP * 2 - PADDING) / (scores.size() - 1) + BORDER_GAP + PADDING;
int x1 = x0;
int y0 = getHeight() - BORDER_GAP - PADDING;
int y1 = y0 - GRAPH_POINT_WIDTH;
if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) {
g2.setColor(GRID_COLOR);
g2.drawLine(x0, getHeight() - BORDER_GAP - PADDING - 1 - GRAPH_POINT_WIDTH, x1, BORDER_GAP);
g2.setColor(Color.BLACK);
String xLabel = i + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(xLabel);
g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
}
g2.drawLine(x0, y0, x1, y1);
}
}
Stroke oldStroke = g2.getStroke();
g2.setColor(GRAPH_COLOR);
g2.setStroke(GRAPH_STROKE);
for (int i = 0; i < graphPoints.size() - 1; i++) {
int x1 = graphPoints.get(i).x;
int y1 = graphPoints.get(i).y;
int x2 = graphPoints.get(i + 1).x;
int y2 = graphPoints.get(i + 1).y;
g2.drawLine(x1, y1, x2, y2);
}
g2.setStroke(oldStroke);
g2.setColor(GRAPH_POINT_COLOR);
for (int i = 0; i < graphPoints.size(); i++) {
int x = graphPoints.get(i).x - GRAPH_POINT_WIDTH / 2;
int y = graphPoints.get(i).y - GRAPH_POINT_WIDTH / 2;;
int ovalW = GRAPH_POINT_WIDTH;
int ovalH = GRAPH_POINT_WIDTH;
g2.fillOval(x, y, ovalW, ovalH);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private double getMinScore() {
double minScore = Double.MAX_VALUE;
for (Double score : scores) {
minScore = Math.min(minScore, score);
}
return minScore;
}
private double getMaxScore() {
double maxScore = Double.MIN_VALUE;
for (Double score : scores) {
maxScore = Math.max(maxScore, score);
}
return maxScore;
}
public static void createAndShowGui(ArrayList<Double> scores, String s) {
DrawGraph mainPanel = new DrawGraph(scores);
JFrame frame = new JFrame(s);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.getContentPane().add(new JButton(new AbstractAction("Save Image") {
#Override
public void actionPerformed(ActionEvent e) {
mainPanel.saveImage(new File("graph.png"));
}
}),BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void saveImage(File file){
BufferedImage bi = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
this.paint(g);
g.dispose();
try{
ImageIO.write(bi,"png",file);
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
final ArrayList<Double> inputValues = new ArrayList<Double>();
inputValues.add(1d);
inputValues.add(2d);
// Read input values from text document and store in ArrayList
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DrawGraph.createAndShowGui(inputValues, "MyGraphTitle");
}
});
}
}
you can change it by youself.
Can anyone guide me how to code the arrow line in different direction.
wa and wl is positive the rectangle will be on top of the x-axis. Below example shown if wl is negative and wa is positive. The code below shown how i code the rectangle shape. x1 is the varaible to state where to start at x axis. e1 is the length of the shape, wa1 and wl1 is the height. wsign to determine the height wa1 or wl1 should display at negative side or positive side.
if (Math.abs(wl1) > Math.abs(wa1)) {
y_scale = (load_y0 - 40) / (double) Math.abs(wl1);
} else {
y_scale = (load_y0 - 40) / (double) Math.abs(wa1);
}
g.drawLine((int) ((double) x0 + x1 * x_scale), (int) (load_y),
(int) ((double) x0 + x1 * x_scale),
(int) (load_y + (wa1 * y_scale) * -1));
g.drawLine((int) ((double) x0 + (x1 + e1) * x_scale),
(int) (load_y), (int) ((double) x0 + (x1 + e1)
* x_scale), (int) (load_y + (wl1 * y_scale)
* -1));
g.drawLine((int) ((double) x0 + x1 * x_scale),
(int) (load_y + (wa1 * y_scale * -1)),
(int) ((double) x0 + (x1 + e1) * x_scale),
(int) (load_y + (wl1 * y_scale) * -1));
Here is a simple routine (adopted from here) for drawing arbitrary arrows:
import static java.awt.geom.AffineTransform.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class Main {
public static void main(String args[]) {
JFrame t = new JFrame();
t.add(new JComponent() {
private final int ARR_SIZE = 4;
void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
Graphics2D g = (Graphics2D) g1.create();
double dx = x2 - x1, dy = y2 - y1;
double angle = Math.atan2(dy, dx);
int len = (int) Math.sqrt(dx*dx + dy*dy);
AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
at.concatenate(AffineTransform.getRotateInstance(angle));
g.transform(at);
// Draw horizontal arrow starting in (0, 0)
g.drawLine(0, 0, len, 0);
g.fillPolygon(new int[] {len, len-ARR_SIZE, len-ARR_SIZE, len},
new int[] {0, -ARR_SIZE, ARR_SIZE, 0}, 4);
}
public void paintComponent(Graphics g) {
for (int x = 15; x < 200; x += 16)
drawArrow(g, x, x, x, 150);
drawArrow(g, 30, 300, 300, 190);
}
});
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setSize(400, 400);
t.setVisible(true);
}
}
Result:
Simple arrow sample
/**
* #param fromPoint end of the arrow
* #param rotationDeg rotation angle of line
* #param length arrow length
* #param wingsAngleDeg wingspan of arrow
* #return Path2D arrow shape
*/
public static Path2D createArrowForLine(
Point2D fromPoint,
double rotationDeg,
double length,
double wingsAngleDeg) {
double ax = fromPoint.getX();
double ay = fromPoint.getY();
double radB = Math.toRadians(-rotationDeg + wingsAngleDeg);
double radC = Math.toRadians(-rotationDeg - wingsAngleDeg);
Path2D resultPath = new Path2D.Double();
resultPath.moveTo(length * Math.cos(radB) + ax, length * Math.sin(radB) + ay);
resultPath.lineTo(ax, ay);
resultPath.lineTo(length * Math.cos(radC) + ax, length * Math.sin(radC) + ay);
return resultPath;
}