How to display coordinates as Strings with Graphics2D in Java? - java

I have a Voronoi diagram being displayed thanks to the Graphics2D class. I would like to know how to display a String in one of black dots located within the patterns. I've tried things such as labels, etc., and can't manage to output a String anywhere in the diagram.
Here's how the code looks:
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
// d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); // Euclidian
d = Math.abs(x1 - x2) + Math.abs(y1 - y2); // Manhattan
// d = Math.pow(Math.pow(Math.abs(x1 - x2), p) + Math.pow(Math.abs(y1 - y2), p), (1 / p)); // Minkovski
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}

Related

JAVA: mouseDragged getX and getY raw data erratic

I am trying to code a paint like program (for fun), but to challenge myself I tried to do it using setRGB method, but I see that when I move the mouse fast the behavior of the stroke gets erratic, do you know how to "soft" the data get from methods getX and getY? or why I am getting random points colored
Thank you in advance and sorry for my english. :)
public class Canvas extends JPanel implements ActionListener, MouseMotionListener, MouseListener {
int canvasW;
int canvasH;
BufferedImage imgCanvas;
int X1;
int Y1;
int X0;
int Y0;
int sizeCanvas = 10;
int expCanvas = 2 * sizeCanvas - 1;
public Canvas(int width, int height) {
canvasH = height;
canvasW = width;
setPreferredSize(new Dimension(width, height));
setBorder(BorderFactory.createLineBorder(Color.black));
setBackground(Color.white);
CanvasImage(width, height);
addMouseListener(this);
addMouseMotionListener(this);
}
public BufferedImage CanvasImage(int width, int height) {
imgCanvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
return imgCanvas;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(imgCanvas, null, null);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public void drawer() {
int deltaX = abs(X1 - X0);
int deltaY = abs(Y1 - Y0);
double m;
double b;
if (deltaX >= deltaY) {
if (deltaY == 0) {
m = 0;
} else {
m = (X0 - X1) / (Y0 - Y1);
}
b = Y0 - m * X0;
if (X1 > X0) {
for (int i = X0; i <= X1; i++) {
imgCanvas.setRGB(i, (int) (m * i + b), Color.BLACK.getRGB());
System.out.println(i + " ; " + (int) (m * i + b));
}
} else {
for (int i = X0; i >= X1; i--) {
imgCanvas.setRGB(i, (int) (m * i + b), Color.BLACK.getRGB());
System.out.println(i + " ; " + (int) (m * i + b));
}
}
} else {
if (deltaX == 0) {
m = 0;
} else {
m = (Y0 - Y1) / (X0 - X1);
}
b = X0 - m * Y0;
if (Y1 > Y0) {
for (int i = Y0; i <= Y1; i++) {
imgCanvas.setRGB((int) (m * i + b), i, Color.BLACK.getRGB());
}
} else {
for (int i = Y0; i >= Y1; i--) {
imgCanvas.setRGB((int) (m * i + b), i, Color.BLACK.getRGB());
}
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
X1 = e.getX();
Y1 = e.getY();
drawer();
repaint();
X0 = X1;
Y0 = Y1;
}
#Override
public void mousePressed(MouseEvent e) {
X0 = e.getX();
Y0 = e.getY();
}

What's wrong with image rotation code?

The image rotates with code below, but wrong, some black dots appears on original image. I believe it's something with rotation code. Any solution? Thanks. The image dimensions is 32x32 pixels loaded on center of screen (320x240).
public class RendPanel extends JPanel {
private static final long serialVersionUID = 1L;
int widthe = 320;
int heighte = 240;
double angle = Math.toRadians(220);
double sin = Math.sin(angle);
double cos = Math.cos(angle);
double x0 = 0.5 * (widthe - 1); // point to rotate about
double y0 = 0.5 * (heighte - 1); // center of image
public static BufferedImage fbuffer;
public RendPanel(int width, int height) {
fbuffer = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB);
BufferedImage in = null;
try { in = ImageIO.read(new File("square.png")); } //32x32 square .png
catch (IOException e) { e.printStackTrace(); }
for (int i = 0; i < in.getWidth(); i++) {
for (int j = 0; j < in.getHeight(); j++) {
fbuffer.setRGB(i + (320 / 2) - 16, j + (240 / 2) - 16, in.getRGB(i, j));
}
}
BufferedImage neww = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < widthe; x++) {
for (int y = 0; y < heighte; y++) {
if(x >= x0 - 32 && x <= x0 + 32 && y >= y0 - 32 && y <= y0 + 32){
double a = x - x0;
double b = y - y0;
int xx = (int) (+a * cos - b * sin + x0);
int yy = (int) (+a * sin + b * cos + y0);
// plot pixel (x, y) the same color as (xx, yy) if it's in bounds
if (xx >= 0 && xx < width && yy >= 0 && yy < height) {
neww.setRGB(xx, yy, fbuffer.getRGB(x, y));
}
}
}
}
fbuffer = neww;
repaint();
setPreferredSize(new Dimension(width, height));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(fbuffer, 0, 0, null);
}
}
A beginner's mistake (sorry).
Taking every source pixel in turn, transforming the coordinates to the destination and copying the pixel value is not the right way.because the regular input grid will not map to a regular grid, and there will be voids (and overlaps).
The correct way is to scan the destination image (so that every destination pixel is reached) and counter-transform the coordinates to fetch the pixel value from the source.
As a refinement, you can use the four neighboring pixel from where you land in the source and perform bilinear interpolation, to reduce aliasing.
Man, it's strange, because in this code it works properly!
Heres a working code:
public class RendPanel extends JPanel {
private static final long serialVersionUID = 1L;
int widthe = 320;
int heighte = 240;
int ang = 0;
double x0 = 0.5 * (widthe - 1); // point to rotate about
double y0 = 0.5 * (heighte - 1); // center of image
public static BufferedImage fbuffer;
public RendPanel(int width, int height) {
fbuffer = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB);
BufferedImage in = null;
try { in = ImageIO.read(new File("square.png")); } //32x32 square .png
catch (IOException e) { e.printStackTrace(); }
for (int i = 0; i < in.getWidth(); i++) {
for (int j = 0; j < in.getHeight(); j++) {
fbuffer.setRGB(i + (320 / 2) - 16, j + (240 / 2) - 16, in.getRGB(i, j));
}
}
setPreferredSize(new Dimension(width, height));
}
BufferedImage neww;
public void r(){
neww = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB);
double angle = Math.toRadians(ang);
double sin = Math.sin(angle);
double cos = Math.cos(angle);
for (int x = 0; x < widthe; x++) {
for (int y = 0; y < heighte; y++) {
if(x >= x0 - 32 && x <= x0 + 32 && y >= y0 - 32 && y <= y0 + 32){
double a = x - x0;
double b = y - y0;
int xx = (int) (+a * cos - b * sin + x0);
int yy = (int) (+a * sin + b * cos + y0);
// plot pixel (x, y) the same color as (xx, yy) if it's in bounds
if (xx >= 0 && xx < widthe && yy >= 0 && yy < heighte) {
neww.setRGB(x, y, fbuffer.getRGB(xx, yy));
}
}
}
}
ang++;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(neww, 0, 0, null);
}
}
Thanks for:
https://introcs.cs.princeton.edu/java/31datatype/Rotation.java.html
EDIT:
You have to invert the vars on bf2.setRGB(x, y, fbuffer.getRGB(xx, yy)); to the rotated coordinate.

Circle to Circle collision in Java

So I am doing circle to circle collision in java. I am aware that there are many similiar questions like mine on this website but my problem is unique from all of them. When I run my code, the circle's collide with each other once every 4 times. Meaning: 3 times they will go through without colliding with one another but one time they will collide. Any help is greatly appreciated.
public class Ball {
float x, y; // coordinates of ball rectangle
float xo, yo;
float vx = 2, vy = 2; // coordinates of velocity vector
Color colour; // ball colour
float d; // diameter of the ball or sizes of ball rectangle
Ellipse2D.Float circle;
// overloaded constructor
Ball(int x, int y, int vx, int vy, int d, Color colour) {
this.x = x;
this.y = y;
this.d = d;
xo = x;
yo = y;
this.setColour(colour);
this.setVelocity(vx, vy);
circle = new Ellipse2D.Float(x, y, d, d);
}
public void setColour(Color colour) {
this.colour = colour;
}
public void setVelocity(int vx, int vy) {
this.vx = vx;
this.vy = vy;
}
public void show(Graphics g) {
((Graphics2D) g).setPaint(colour);
circle.setFrame(x, y, d, d);
((Graphics2D) g).fill(circle);
xo = x;
yo = y;
}
public void hide(Graphics g) {
Color c = ((Graphics2D) g).getBackground();
((Graphics2D) g).setPaint(c);
circle.setFrame(xo, yo, d, d);
((Graphics2D) g).fill(circle);
}
public void setPosition(float x, float y) {
this.x = x;
this.y = y;
}
public void move(int a, int b, int xh, int yh) {
if (vy > 0) {
if (y + d + vy - yh - b > 0) {
y = yh + b - d;
vy = -vy;
} else
y += vy;
} else {
if (y + vy <= b) {
y = b;
vy = -vy;
} else
y += vy;
}
if (vx > 0) {
if (x + d + vx - xh - a > 0) {
x = xh + a - d;
vx = -vx;
} else
x += vx;
} else {
if (x + vx <= a) {
x = a;
vx = -vx;
} else
x += vx;
}
}
The Collision Detector is in the class below
public class Game extends JFrame {
int ah, bh, xh, yh; // parameters of the rectangle frame
Color[] ColorAr = { Color.red, Color.blue, Color.pink, Color.green,
Color.yellow, Color.magenta, Color.black, Color.orange, Color.gray,
Color.cyan };
Ball b[];
int quantity = 4;
public void paint(Graphics g) {
int i;
((Graphics2D) g).setPaint(Color.black);
((Graphics2D) g).drawRect(ah, bh, xh, yh);
for (i = quantity - 1; i >= 0; i--) {
b[i].hide(g);
}
for (i = 0; i < quantity; i++) {
b[i].show(g);
}
}
public void prepare() {
int i;
ah = 20;
bh = 40;
xh = 400;
yh = 400;
b = new Ball[quantity];
for (i = 0; i < quantity; i++) {
b[i] = new Ball((int) (Math.random() * (300 - 1 + 1)) + 1, 100, 1,
1, 26, ColorAr[(int) (Math.random() * 9)]);
}
}
public void collision() {
int radius = 13;
int distance = 2 * radius;
if (b[1].x + distance == b[0].x && b[1].y == b[0].y
|| b[1].x - distance == b[0].x && b[1].y == b[0].y) {
b[1].vx = -b[1].vx;
b[0].vx = -b[0].vx;
}
}
public void run() {
int i;
while (true) {
for (i = 0; i < quantity; i++)
b[i].move(ah, bh, xh, yh);// move balls
collision();
for (int j = 0; j < 10000000; j++)
; // delay;
// collision();
repaint();
}
}
public static void main(String args[]) {
Game frame = new Game();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setBackground(Color.white);
frame.setSize(450, 470);
frame.prepare();
frame.setVisible(true);
frame.run();
}
}
For two circles:
First calculate the sum of lengths: radius_1 + radius_2 (the first and the second circle).
Collision of two circles can be detected if you calculate the length of (imaginary) line between centers. If THAT length <= radius_1 + radius_2, two circles are colliding.

Graphics paint component and loop trouble

I can not seem to figure out why my concentric circles are not lining up. My loops seem correct to me and the measurements are correct but for some reason the last few circles are off-centered. That's the first issue I'm having. The second issue is, i can't seem to get the concentric circles to print in each square. Once again, i can't seem to find any issue in my logic, but obviously there is an issue. Any help on this at all would be great.
This should be the end product
*Now this is my source code- ExampleGUI.java *
import javax.swing.*;
public class ExampleGUI {
public static void main(String args []) {
JFrame frame = new JFrame("Example Graphics");
ExamplePanel panel = new ExamplePanel();
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(3);
frame.pack();
frame.setVisible(true);
}
}
* ExamplePanel.java *
import java.awt.*;
import javax.swing.*;
public class ExamplePanel extends JPanel{
public ExamplePanel() {
setPreferredSize(new Dimension (600, 600));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
int x2 = 5;
int y = 500;
int y2 = 505;
int w = 100;
int w2 = 90;
int h = 100;
int h2 = 90;
int i, j, k;
for(j = 1; j < 7; j++) {
x = 0;
x2 = x + 5;
for(i = 1; i < 7; i++) {
if ((i + j) % 2 == 0) {
g.setColor(Color.white);
} else {
g.setColor(Color.yellow);
}
g.fillRect(x, y, w, h);
g.setColor(Color.black);
g.drawRect(x, y, w, h);
g.setColor(Color.green);
g.fillOval(x2, y2, w2, h2);
for(k = 1; k < 7; k++) {
g.setColor(Color.black);
g.drawOval(x2, y2, w2, h2);
x2 = x2 + 5;
y2 = y2 + 5;
w2 = w2 - 10;
h2 = h2 - 10;
}
x = x + w;
x2 = x2 + w2 + 10;
}
x = x + w;
y = y - h;
y2 = (y2 - h2) - 10;
}
}
}
* This is what my program looks like when i run it. It doesn't look like the other picture for some reason *
Basically, you "spiral" loop is modifying the state of variables that are required elsewhere
What I would do, is create a new series of variables, initialized to the current state and modify those instead...
int ix = x2;
int iy = y2;
int ih = h2;
int iw = w2;
for (k = 1; k < 7; k++) {
g.setColor(Color.black);
g.drawOval(ix, iy, iw, ih);
ix = ix + 5;
iy = iy + 5;
iw = iw - 10;
ih = ih - 10;
}

Drawing a simple 2D graph in java

I got a below java code which plots a 2D graph where x axis has values 1,2,3,......20
and y axis has values 21,14,18..........18
The code works perfectly but the only problem is that the graph does not shows the corresponding x and y values on x axis and y axis respectively. I know it could be a small addition to the code. but i am new to java graphics and i am not able to figure out where to add the relevant code considering the time constraint.
/*Sample code */
public class GraphingData extends JPanel {
int[] data = {
21, 14, 18, 03, 86, 88, 74, 87, 54, 77,
61, 55, 48, 60, 49, 36, 38, 27, 20, 18
};
final int PAD = 20;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
// Draw ordinate.
g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
// Draw abcissa.
g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
// Draw labels.
Font font = g2.getFont();
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = font.getLineMetrics("0", frc);
float sh = lm.getAscent() + lm.getDescent();
// Ordinate label.
String s = "Average Byte Value";
float sy = PAD + ((h - 2*PAD) - s.length()*sh)/2 + lm.getAscent();
for(int i = 0; i < s.length(); i++) {
String letter = String.valueOf(s.charAt(i));
float sw = (float)font.getStringBounds(letter, frc).getWidth();
float sx = (PAD - sw)/2;
g2.drawString(letter, sx, sy);
sy += sh;
}
// Abcissa label.
s = "file blocks";
sy = h - PAD + (PAD - sh)/2 + lm.getAscent();
float sw = (float)font.getStringBounds(s, frc).getWidth();
float sx = (w - sw)/2;
g2.drawString(s, sx, sy);
// Draw lines.
double xInc = (double)(w - 2*PAD)/(data.length-1);
double scale = (double)(h - 2*PAD)/getMax();
g2.setPaint(Color.green.darker());
for(int i = 0; i < data.length-1; i++) {
double x1 = PAD + i*xInc;
double y1 = h - PAD - scale*data[i];
double x2 = PAD + (i+1)*xInc;
double y2 = h - PAD - scale*data[i+1];
g2.draw(new Line2D.Double(x1, y1, x2, y2));
}
// Mark data points.
g2.setPaint(Color.red);
for(int i = 0; i < data.length; i++) {
double x = PAD + i*xInc;
double y = h - PAD - scale*data[i];
g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
}
}
private int getMax() {
int max = -Integer.MAX_VALUE;
for(int i = 0; i < data.length; i++) {
if(data[i] > max)
max = data[i];
}
return max;
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new GraphingData());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
public void drawGrid(Graphics g)
{
g.setColor(Color.black);
int rows = model.maxy-model.miny+1;
int cols = model.maxx-model.minx+1;
int colWidth = (getWidth()-paddingFromRight - ylabelWidth)/cols;
int rowHeight = (getHeight()-xlabelHeight-headingHeight)/rows;
int endX = ylabelWidth + cols * colWidth;
int endY = headingHeight + rows*rowHeight;
for (int k = 0; k <= cols; k++)
{
g.drawLine(ylabelWidth+colWidth*k, headingHeight, ylabelWidth+colWidth*k, endY); //getHeight()-xlabelHeight
}
for (int k = 0; k <= rows;k++)
{
g.drawLine(ylabelWidth, headingHeight+rowHeight*k,endX, headingHeight+rowHeight*k);
}
}
public void drawLines(Graphics g)
{
ArrayList<Line> lines = model.getLines();
Random random = new Random(50);
for (int k = 0; k < lines.size(); k++)
{
g.setColor(new Color(255-50*k, 50*k, 2*50*k));
//g.setColor(Color.red);
drawLine(g, lines.get(k));
}
}
public void drawLine(Graphics g, Line line)
{
ArrayList<Point> points = line.points;
for (int k = 0; k<points.size()-1;k++)
{
//scale up points
Point p1 = points.get(k);
Point p2 = points.get(k+1);
g.drawLine(scaleUpX(p1.x), scaleUpY(p1.y), scaleUpX(p2.x), scaleUpY(p2.y));
g.fillOval(scaleUpX(p1.x)-5, scaleUpY(p1.y)-5, 10, 10);
}
Point p1 = points.get(points.size()-1);
g.fillOval(scaleUpX(p1.x)-5, scaleUpY(p1.y)-5, 10, 10);
}
public int scaleUpX(int x)
{
int cols = model.maxx-model.minx+1;
int colWidth = (getWidth()-paddingFromRight - ylabelWidth)/cols;
return ylabelWidth+colWidth*x;
}
public int scaleUpY(int y)
{
int rows = model.maxy-model.miny+1;
int rowHeight = (getHeight()-xlabelHeight-headingHeight)/(rows);
//int endY = getHeight()-xlabelHeight;
int endY = headingHeight+rows*rowHeight;
return endY - rowHeight*y;
}
public void drawLabels(Graphics g)
{
Dimension d = getSize();
//xlabel
g.drawString(model.xlabel, d.width/2, d.height-xlabelHeight/4);
//ylabel
g.drawString(model.ylabel, 0+5, d.height/2);
//xaxis
int rows = model.maxy-model.miny+1;
int cols = model.maxx-model.minx+1;
int colWidth = (getWidth()-paddingFromRight - ylabelWidth)/cols;
int rowHeight = (getHeight()-xlabelHeight-headingHeight)/rows;
for (int k = 0;k<=cols;k++)
{
g.drawString(String.valueOf(model.minx+k), ylabelWidth+k*colWidth-5, rowHeight*rows+headingHeight+15);
}
//yaxis
for (int k = 0;k<=rows;k++)
{
g.drawString(String.valueOf(model.maxy-k+1),ylabelWidth-15,headingHeight+k*rowHeight);
}
//heading
FontMetrics fm = g.getFontMetrics();
g.setFont(g.getFont().deriveFont((float)25.0));
g.drawString(model.title, d.width/2-fm.stringWidth(model.title), headingHeight/2+headingHeight/4);
}

Categories