adding Glabel to form a triangle java program - java

Here is my code:
public class test extends GraphicsProgram {
private static final int LABELGAP = 30;
private static final int LINEGAP = 20;
int numLabel = 1;
double y = 75;
public void run() {
for (int i = 0; i < 8; i++) {
GLabel label = new GLabel("Hello World");
label.setFont("London-12");
double x = (getWidth() - label.getWidth() * numLabel - LABELGAP * (numLabel -1)) / 2;
double step = label.getWidth() + LABELGAP;
for (int j = 0; j < numLabel; j++) {
add(label, x, y);
x += step;
}
numLabel++;
y += LINEGAP;
}
}
}
But there is only one label per line. What's wrong?
I want to have one more label than previous line.
Also, if I put
GLabel label = new GLabel("Hello World");
label.setFont("London-12");
double x = (getWidth() - label.getWidth() * numLabel - LABELGAP * (numLabel -1)) / 2;
double step = label.getWidth() + LABELGAP;
This part of the code outside of 2nd for loop, the result is different from when I put them inside(neither is the desired result). Why?

Related

while loop returns a repeating random value rather than a new random value

I am currently just messing around with some code and I keep running into an issue. I want to create ten circles and simply have them bounce around the window. I've had a couple of problems (like when I want the circles to bounce off the wall, for some reason the 400,400 window isn't actually that size. I have the circles collide on the right by checking if x + width >= 400, but it bounces outside the screen unless I change the 400 to 380?), but my main issue is that when I create the circles, I want them to be in different locations (so they aren't colliding before they can even move). I am trying to get it so that if a circle is going to be 'inside' another circle then instead create random x and y coordinates again until it isn't inside another circle. But for some reason, if I put r.nextInt() inside the while loop it keeps giving me the same values. Can anyone help?
p.s. I wouldn't mind advice on any other mistakes I have made.
package practicedots;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PracticeDots extends JPanel {
float dots[][] = new float[10][7];
Random r = new Random();
boolean first = true;
float x = 0;
float y = 0;
float xAccel = 0;
float yAccel = 0;
int wall = 380;
int width = 50;
float radius = 0;
float centreX = 0;
float centreY = 0;
boolean collision;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new PracticeDots());
f.setPreferredSize(new Dimension(400, 400));
f.setResizable(true);
f.pack();
f.setVisible(true);
}
/**
*
* #return
*/
public float[][] CreateDots() {
if (first == true) {
for (int i = 0; i < 10; i++) {
while(collision == true){
x = r.nextInt(300);
y = r.nextInt(300);
xAccel = r.nextFloat() / 2;
yAccel = r.nextFloat() / 2;
radius = width/2;
centreX = x + radius;
centreY = y + radius;
dots[i][0] = x;
dots[i][1] = y;
dots[i][2] = xAccel;
dots[i][3] = yAccel;
dots[i][4] = radius;
dots[i][5] = centreX;
dots[i][6] = centreY;
bounce();
}
}
first = false;
} else if (first == false) {
for (int i = 0; i < 10; i++) {
dots[i][0] = dots[i][0] + dots[i][2];
dots[i][1] = dots[i][1] + dots[i][3];
if (dots[i][0] >= wall - width) {
dots[i][2] = -dots[i][2];
}
if (dots[i][1] >= wall - 20 - width) {
dots[i][3] = -dots[i][3];
}
if (dots[i][0] < 0) {
dots[i][2] = -dots[i][2];
}
if (dots[i][1] < 0) {
dots[i][3] = -dots[i][3];
}
bounce();
}
}
repaint();
return dots;
}
//(x2-x1)^2 + (y1-y2)^2 <= (r1+r2)^2
public void bounce() {
for (int i = 0; i < 10; i++) {
for (int a = 0; a < 10; a++) {
if (a != i) {
System.out.println((dots[i][0] - dots[a][0])*(dots[i][0] - dots[a][0]) + (dots[i][1] - dots[a][1])*(dots[i][1] - dots[a][1]) <= (dots[i][4] + dots[a][4]) * (dots[i][4] + dots[a][4]));
collision = (dots[i][0] - dots[a][0])*(dots[i][0] - dots[a][0]) + (dots[i][1] - dots[a][1])*(dots[i][1] - dots[a][1]) <= (dots[i][4] + dots[a][4]) * (dots[i][4] + dots[a][4]);
}
}
}
}
/**
*
* #param g
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 10; i++) {
CreateDots();
g.drawOval((int) dots[i][0], (int) dots[i][1], width, width);
g.fillOval((int) dots[i][0], (int) dots[i][1], width, width);
}
}
}
<!-- end snippet -->
There were a couple of problems:
During bounce you should return the first time you find a collision, otherwise the collision will be set to true, but then could be set back to false on the next iteration in the for-loop.
In the first == true condition, you should initialize collision to true or it will never do the while loop at all. Either that or change it to a do-while.
During paintComponent you should not call CreateDots within the for-loop since it loops over all dots itself. Just call it before.
The code seems to work with these changes (including width of 400 not 380):
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PracticeDots extends JPanel {
float dots[][] = new float[10][7];
Random r = new Random();
boolean first = true;
float x = 0;
float y = 0;
float xAccel = 0;
float yAccel = 0;
int wall = 400;
int width = 50;
float radius = 0;
float centreX = 0;
float centreY = 0;
boolean collision;
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new PracticeDots());
f.setPreferredSize(new Dimension(400, 400));
f.setResizable(true);
f.pack();
f.setVisible(true);
}
public float[][] CreateDots() {
if (first == true) {
for (int i = 0; i < 10; i++) {
do {
x = r.nextInt(300);
y = r.nextInt(300);
xAccel = r.nextFloat() / 2;
yAccel = r.nextFloat() / 2;
radius = width / 2;
centreX = x + radius;
centreY = y + radius;
dots[i][0] = x;
dots[i][1] = y;
dots[i][2] = xAccel;
dots[i][3] = yAccel;
dots[i][4] = radius;
dots[i][5] = centreX;
dots[i][6] = centreY;
bounce();
} while (collision == true);
}
first = false;
} else {
for (int i = 0; i < 10; i++) {
dots[i][0] = dots[i][0] + dots[i][2];
dots[i][1] = dots[i][1] + dots[i][3];
if (dots[i][0] >= wall - width) {
dots[i][2] = -dots[i][2];
}
if (dots[i][1] >= wall - 20 - width) {
dots[i][3] = -dots[i][3];
}
if (dots[i][0] < 0) {
dots[i][2] = -dots[i][2];
}
if (dots[i][1] < 0) {
dots[i][3] = -dots[i][3];
}
bounce();
}
}
repaint();
return dots;
}
public void bounce() {
collision = false;
for (int i = 0; i < 10; i++) {
for (int a = 0; a < 10; a++) {
if (a != i && !(dots[a][0] == 0 && dots[a][1] == 0)) {
boolean thisCollision = (dots[i][0] - dots[a][0]) * (dots[i][0] - dots[a][0]) + (dots[i][1] - dots[a][1]) * (dots[i][1] - dots[a][1]) <= (dots[i][4] + dots[a][4]) * (dots[i][4] + dots[a][4]);
// System.out.println("collision: "+collision+" i="+i+" a="+a);
if (thisCollision) {
collision = true;
return;
}
}
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
CreateDots();
for (int i = 0; i < 10; i++) {
g.drawOval((int) dots[i][0], (int) dots[i][1], width, width);
g.fillOval((int) dots[i][0], (int) dots[i][1], width, width);
}
}
}

Representing Mandelbrot and Julia Sets Graphically in Java

I'm working on a problem where I'm needing to represent the Mandelbrot set graphically using OpenCL and working on my sequential code first. However, the image it is producing isn't very good and I'm unsure if I've missed something somewhere or if this is merely an issue with a lack of resolution (so to speak). I've posted the code below along with a screenshot of what it produces - is this what I should be expecting or have I messed this up somewhere?
public class SequentialMandelbrot {
private static int[] colorMap;
private static int xSize = 200, ySize = 200;
private static float yMin = -2f, yMax = 2f;
private static float xMin = -2f, xMax = 2f;
private static float xStep = (xMax - xMin) / (float)xSize;
private static float yStep = (yMax - yMin) / (float)ySize;
private static final int maxIter = 250;
private static BufferedImage image;
private static JComponent imageComponent;
public static void main(String[] args) {
// Create the image and the component that will paint the image
initColorMap(32, Color.RED, Color.GREEN, Color.BLUE);
image = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);
imageComponent = new JPanel()
{
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0,0,this);
}
};
for (int j = 0; j < xSize; j++) {
for (int k = 0; k < ySize; k++) {
int iter = mandelbrot(j, k);
if (iter == maxIter) {
image.setRGB(j, k, 0);
} else {
int local_rgb = colorMap[iter%64];
image.setRGB(j, k, local_rgb);
}
}
}
JFrame frame = new JFrame("JOCL Simple Mandelbrot");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
imageComponent.setPreferredSize(new Dimension(xSize, ySize));
frame.add(imageComponent, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private static int mandelbrot(float j, float k) {
int t = 0;
float norm = 0;
float x = 0;
float y = 0;
float r = xMin + (j * xStep);
float i = yMin + (k * yStep);
while (t < maxIter && norm < 4) {
x = (x*x) - (y*y) + r;
y = (2*x*y) + i;
norm = (x*x) + (y*y);
t++;
}
return t;
}
I have also altered the code for the Julia set (from the number 0.45 + 0.1428i) and it produces something equally questionable:
This is your iteration loop, which is incorrect.
while (t < maxIter && norm < 4) {
x = (x*x) - (y*y) + r;
y = (2*x*y) + i;
norm = (x*x) + (y*y);
t++;
}
You are overwriting x before re-using it to calculate y. I suggest using a temporary variable, such as
while (t < maxIter && norm < 4) {
tempx = (x*x) - (y*y) + r;
y = (2*x*y) + i;
x = tempx;
norm = (x*x) + (y*y);
t++;
}
Aside: there is room for some efficiency too, as you are calculating x*x and y*y twice.

Java nested for loop incrementing second loop by first for loop?

Hi I'm learning Java and found a solution that is pretty neat,
but I'm interested in a particular line of code in the 2nd for loop.
I wouldn't know who to ask because I'm not in school for Java yet so I'm asking here,
but anyway:
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
Does this mean that 'repeat i for this number of times' is added' to 'h minus 1'? More specifically what is (-h)? Is it a pre-increment? And why is it in parenthesis?
It's again used in declaring the variable x.
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class Pyramid extends GraphicsProgram {
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Width of each brick in pixels */
private static final int BRICK_HEIGHT = 12;
/** Number of bricks in the base of the pyramid */
private static final int BRICKS_IN_BASE = 15;
public void run() {
for (int h = 0; h < BRICKS_IN_BASE; h++)
{
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
{
int k = i * BRICK_WIDTH;
int m = h * BRICK_HEIGHT;
int x = ((getWidth() - ((BRICKS_IN_BASE + (-h)) * BRICK_WIDTH)) / 2) + k;
int y = getHeight() - ((BRICK_HEIGHT + 1) + m);
GRect brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT);
add(brick);
}
}
}
}
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
is really (the (-h) is simply -1*h)
for (int i = 0; i < (BRICKS_IN_BASE - h); i++)
due to operator precedence

Need help to fix the GUI [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
The problem is that the text under the bar chart is not aligned with the bars in the bar chart. How do I make them align properly?
What more could I possibly add as details to this question to make your detector shut up? :)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SimpleBarChart extends JPanel {
private double[] value;
private String[] languages;
private String title;
private int gapBetweenBars = 40;//MODIFICATION - NOT A PART OF ORIGINAL CODE
public SimpleBarChart(double[] val, String[] lang, String t) {
languages = lang;
value = val;
title = t;
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
if (value == null || value.length == 0) {
return;
}
double minValue = 0;
double maxValue = 0;
for (int i = 0; i < value.length; i++) {
if (minValue > value[i]) {
minValue = value[i];
}
if (maxValue < value[i]) {
maxValue = value[i];
}
}
Dimension dim = getSize();
int clientWidth = dim.width;
int clientHeight = dim.height;
int barWidth = clientWidth / value.length;
barWidth = barWidth / 3;//MODIFICATION - NOT A PART OF ORIGINAL CODE
Font titleFont = new Font("Book Antiqua", Font.BOLD, 15);
FontMetrics titleFontMetrics = graphics.getFontMetrics(titleFont);
Font labelFont = new Font("Book Antiqua", Font.PLAIN, 10);
FontMetrics labelFontMetrics = graphics.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth(title);
int q = titleFontMetrics.getAscent();
int p = (clientWidth - titleWidth) / 2;
graphics.setFont(titleFont);
graphics.drawString(title, p, q);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
if (maxValue == minValue) {
return;
}
double scale = (clientHeight - top - bottom) / (maxValue - minValue);
q = clientHeight - labelFontMetrics.getDescent();
graphics.setFont(labelFont);
for (int j = 0; j < value.length; j++) {
int valueP = j * (barWidth + gapBetweenBars) + 1; //MODIFICATION - NOT A PART OF ORIGINAL CODE
int valueQ = top;
int height = (int) (value[j] * scale);
if (value[j] >= 0) {
valueQ += (int) ((maxValue - value[j]) * scale);
} else {
valueQ += (int) (maxValue * scale);
height = -height;
}
graphics.setColor(Color.blue);
graphics.fillRect(valueP, valueQ, barWidth - 2, height);
graphics.setColor(Color.black);
graphics.drawRect(valueP, valueQ, barWidth - 2, height);
int labelWidth = labelFontMetrics.stringWidth(languages[j]);
p = j * barWidth + (barWidth - labelWidth) / 2;
graphics.drawString(languages[j], p, q);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
double[] value = new double[5];
String[] languages = new String[5];
value[0] = 1;
languages[0] = "Visual Basic";
value[1] = 2;
languages[1] = "PHP";
value[2] = 3;
languages[2] = "C++";
value[3] = 4;
languages[3] = "C";
value[4] = 5;
languages[4] = "Java";
frame.getContentPane().add(new SimpleBarChart(value, languages, "Programming Languages"));
WindowListener winListener = new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
};
frame.addWindowListener(winListener);
frame.setVisible(true);
}
public void setGapBetweenBars(int gapBetweenBars) {
this.gapBetweenBars = gapBetweenBars;
}
public int getGapBetweenBars() {
return this.gapBetweenBars;
}
}
The value of p in your for loop is incorrect and should rather be:
p = j * (barWidth + gapBetweenBars) + (barWidth - labelWidth) / 2;
You forgot to take the gap into account.
use this in side for loop
int labelWidth = labelFontMetrics.stringWidth(languages[j]);
p = j * (barWidth+gapBetweenBars) + (barWidth - labelWidth) / 2;
changed calculation of space between Languages strings

Constructor is undefined, when it is clearly defined

I am making a program that plots the decay of atoms. Here is my main, which also does the logic. However, I am getting a undefined constructor error, when it is clearly defined in the other class. Why is this happening?
Caution: it isn't notated. Spare me your wrath.
import java.util.Random;
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
int chance = 6;
Random r = new Random();
int num = 40;
int[] decayed;
int reps = 25;
decayed = new int[reps];
for (int j = 1; j < reps+1; j++) {
for (int i = 0; i < num; i++) {
int c = r.nextInt(chance);
if (c == chance - 1) {
decayed[j]++;
}
}
System.out.printf("\n Trial: " + j + "\n Number left: " + num
+ "\n Decayed: " + decayed[j] + "\n\n");
num = num - decayed[j];
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new Graph(decayed[])); //"Constuctor is undefined for type int" When I am clearly specifying an array.
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
And my Graph.class. It is copied from some forum (Credit to Crieg Wood).
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Graph extends JPanel
{
int PAD = 20;
boolean drawLine = true;
boolean drawDots = true;
int dotRadius = 3;
// the y coordinates of the points to be drawn; the x coordinates are evenly spaced
int[] data;
public Graph(int points[]){ //This is the constructor which specifies type int[].
for (int i = 0; i<points.length; i++){ //Copies points[] to data[]
data[i] = points[i];
}
}
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();
g2.drawLine(PAD, PAD, PAD, h-PAD);
g2.drawLine(PAD, h-PAD, w-PAD, h-PAD);
double xScale = (w - 2*PAD) / (data.length + 1);
double maxValue = 100.0;
double yScale = (h - 2*PAD) / maxValue;
// The origin location
int x0 = PAD;
int y0 = h-PAD;
// draw connecting line
if (drawLine)
{
for (int j = 0; j < data.length-1; j++)
{
int x1 = x0 + (int)(xScale * (j+1));
int y1 = y0 - (int)(yScale * data[j]);
int x2 = x0 + (int)(xScale * (j+2));
int y2 = y0 - (int)(yScale * data[j+1]);
g2.drawLine(x1, y1, x2, y2);
}
}
// draw the points as little circles in red
if (drawDots)
{
g2.setPaint(Color.red);
for (int j = 0; j < data.length; j++)
{
int x = x0 + (int)(xScale * (j+1));
int y = y0 - (int)(yScale * data[j]);
g2.fillOval(x-dotRadius, y-dotRadius, 2*dotRadius, 2*dotRadius);
}
}
}
}
The problems here are with the usage of those [] brackets.
Try to re-write your call:
f.getContentPane().add(new Graph(decayed));
Though you were not incorrect, please consider re-writing your constructor to hold to the Java standards and conventions:
public Graph(int[] points){ // NOTE: I moved the [] to a the standard position
for (int i = 0; i<points.length; i++){
data[i] = points[i];
}
}
Your syntax is invalid, to refer to your array, simply use the variable name, without the []:
f.getContentPane().add(new Graph(decayed));
Just replace this f.getContentPane().add(new Graph(decayed[]));
with this
f.getContentPane().add(new Graph(decayed));
Just use the name of the variable that you have created without that [].
Those [] brackets are used only at the time of declaration of the method parameters for arrays and not when calling the method.

Categories

Resources