I am creating a program for my computer science program. I am trying to call a class called "StockBarChart". How would I call this class from my main class?
Edit: I have posted the code below
In this class I have created a bar chart. I am not quite sure where I have gone wrong.
public class StockBarChart extends JPanel {
private double[] values;
private String[] names;
private String title;
public StockBarChart(double[] v, String[] n, String t) {
names = n;
values = v;
title = t;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (values == null || values.length == 0)
return;
double minValue = 0;
double maxValue = 0;
for (int i = 0; i < values.length; i++) {
if (minValue > values[i])
minValue = values[i];
if (maxValue < values[i])
maxValue = values[i];
}
Dimension d = getSize();
int clientWidth = d.width;
int clientHeight = d.height;
int barWidth = clientWidth / values.length;
Font titleFont = new Font("SansSerif", Font.BOLD, 20);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth(title);
int y = titleFontMetrics.getAscent();
int x = (clientWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString(title, x, y);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
if (maxValue == minValue)
return;
double scale = (clientHeight - top - bottom) / (maxValue - minValue);
y = clientHeight - labelFontMetrics.getDescent();
g.setFont(labelFont);
for (int i = 0; i < values.length; i++) {
int valueX = i * barWidth + 1;
int valueY = top;
int height = (int) (values[i] * scale);
if (values[i] >= 0)
valueY += (int) ((maxValue - values[i]) * scale);
else {
valueY += (int) (maxValue * scale);
height = -height;
}
g.setColor(Color.red);
g.fillRect(valueX, valueY, barWidth - 2, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 2, height);
int labelWidth = labelFontMetrics.stringWidth(names[i]);
x = i * barWidth + (barWidth - labelWidth) / 2;
g.drawString(names[i], x, y);
}
}
public static void main(String[] argv) {
try{
String breadStockBeforeTrim = new String(Files.readAllBytes(Paths.get("bread.txt")));
String breadStock = breadStockBeforeTrim.trim();
int breadNumber = Integer.parseInt(breadStock);
String browniesStockBeforeTrim = new String(Files.readAllBytes(Paths.get("brownies.txt")));
String browniesStock = browniesStockBeforeTrim.trim();
int browniesNumber = Integer.parseInt(browniesStock);
JFrame f = new JFrame();
f.setSize(400, 300);
double[] values = new double[3];
String[] names = new String[3];
values[0] = 1;
names[0] = "Item 1";
values[1] = breadNumber;
names[1] = "Item 2";
values[2] = browniesNumber;
names[2] = "Item 3";
f.getContentPane().add(new
StockBarChart(values, names, "title"));
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
f.addWindowListener(wndCloser);
f.setVisible(true);
}catch(IOException b){
b.printStackTrace();
}
}
}
The answer is simple:
Here is the signature of the Constructor of your class StockBarChart:
public StockBarChart(double[] v, String[] n, String t) {
names = n;
values = v;
title = t;
}
Whenever you want to instantiate any of your class, you init it via the constructor. Even when a constructor is not written explicitly, java assigns a constructor (empty constructor) by default.
In your case, when you instantiate the class, it expects a few values which are mapped through the constructor and are necessary for the object to operate on variables, via the class methods.
Simply providing those parameters will solve your problem.
So to say, you should instantiate the Class like below:
StockBarChart stockBarChart = new StockBarChart(doubleArray,stringArray,stringValue)
If the error message says that the required types are double[] String[] and String that means that you need to give the constructor the needed parameters.
It seems that your class StockBarChart has a constructor such as:
public StockBarChart(double[] v, String[] n, String t) {}
and that means that when instantiating the class, you need to give it those double[], String[] and String:
StockBarChart stockBarChart = new StockBarChart(someSetParameterOfDouble[]Type, someString[]Parameter, someString);
You initialize those and given them to the constructor.
Related
i tried to generate bar chart from input
i would like have my code to get out put like this
enter image description here
this is my code but i have some error
i have some error in label that say should make method label and in main
can you guys help me fix this things
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
public class baronly
{
//Establish the placement of the fields for user entry
// get some error in this
Label LabelA = addLabel("A", 1,1,1,1);
IntegerField FieldA = addIntegerField(0,1,2,1,1);
Label LabelB = addLabel("B", 1,3,1,1);
IntegerField FieldB = addIntegerField(0,1,4,1,1);
Label LabelC = addLabel("C", 1,5,1,1);
IntegerField FieldC = addIntegerField(0,1,6,1,1);
Label LabelD = addLabel("D", 1,7,1,1);
IntegerField FieldD = addIntegerField(0,1,8,1,1);
Label LabelF = addLabel("F", 1,9,1,1);
IntegerField FieldF = addIntegerField(0,1,10,1,1);
//Establish a drop down menu for the drawing
//Right now we only have one choice -- Bar
//Establish variables for this program
int numberOfScores = 5;
int Xleft = 100;
int Xright = 300;
int Ytop = 100;
int Ybottom = 250; // y value entries can be up to 150
int BarWidth = 10;
int totalX , totalY;
int[ ] scores;
char graphChoice;
//Constructor to establish the initial values in the program
public baronly()
{
scores = new int[numberOfScores];
for (int i = 0; i < scores.length; i++)
scores[ i ] = 0;
totalX = Xright - Xleft + 1;
totalY = Ybottom - Ytop + 1;
}
//Allow for the menu choices
//Remember, we only have one choice right now
public void paint (Graphics g)
{
getInputData();
g.setColor (Color.red); //set color of the graph
g.drawString("Java Grades",170,290); //title
drawBarGraph(g);
}
//Get input from the screen
public void getInputData()
{
scores[0] = FieldA.getNumber();
scores[1] = FieldB.getNumber();
scores[2] = FieldC.getNumber();
scores[3] = FieldD.getNumber();
scores[4] = FieldF.getNumber();
}
//Draw the bar graph
public void drawBarGraph(Graphics g)
{
drawAxes(g);
int i, x, y, height, largestNumber, xIncrement, yIncrement;
//Compute the x and y increments
largestNumber = findLargest (scores);
xIncrement = totalX /numberOfScores;
if (largestNumber ==0)
yIncrement = 0;
else
yIncrement = totalY / largestNumber;
//Draw the bars
for(i=0; i < numberOfScores; i++)
{
x = getXCoordinate(i+1, xIncrement);
y = getYCoordinate(scores[i], yIncrement);
x = x - BarWidth / 2;
height = Ybottom - y + 1;
g.fillRect(x, y, BarWidth, height);
}
//Label x - axes with grade choices
String [ ] label = {"A", "B", "C", "D", "F"};
for(i=1; i<= numberOfScores; i++)
g.drawString(label[i-1], 100+ i*xIncrement, 270);
//Label y - axes with quantity of each grade
int topy;
if(largestNumber%10==0)
topy=largestNumber;
else
topy=(largestNumber/10+1)*10;
//i=i+5 controls y value label -- adjust for size of data
for (i=0; i<=topy; i=i+5)
{
g.drawString(String.valueOf(i), 70, Ybottom-i*yIncrement+5);
}
}
//Draw the axes for the graph
public void drawAxes (Graphics g)
{
g.drawLine(Xleft, Ytop, Xleft, Ybottom);
g.drawLine(Xleft, Ybottom, Xright, Ybottom);
}
//Determining x coordinate
public int getXCoordinate(int i, int xIncrement)
{
return Xleft + xIncrement *i;
}
//Determining y coordinate
public int getYCoordinate(int numStudents, int yIncrement)
{
return Ybottom - yIncrement * numStudents;
}
//Finding the largest value in the array
public int findLargest(int [ ] a)
{
int i;
int loc = 0;
for(i=1; i<a.length; i++)
if(a[i]>a[loc])
loc = i;
return a[loc];
}
//Main
public static void main(String[ ] args)
{
baronly frm = new baronly();
frm.setSize(400,300);
frm.setVisible(true);
}
}
that error gave says i should give method in label what that suppose to mean
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.
I'm trying to write an algorithm to satisfy this challenge. I've double, triple, and quadruple checked my logic, but I think I'm missing something obvious. This program should group each color next to similar colors, but it produces something more akin to noise.
This is sort of what I expect (taken from a similar answer):
And this is what I'm actually getting:
public class AllColors extends JFrame {
private static final int WIDTH = 256;
private static final int HEIGHT = 128;
private static long TOTAL_ITERATIONS = (WIDTH * HEIGHT) * 185000;
private static int VALUES_PER_CHANNEL =32;
private static int CHANNEL_DELTA = 256/VALUES_PER_CHANNEL;
static BufferedImage image;
private static final int SCALE = 5;
static int[][] kernel = { { 0, 0, 1, 0, 0 },
{ 0, 2, 3, 2, 0 },
{ 1, 3, 0, 3, 1 },
{ 0, 2, 3, 2, 0 },
{ 0, 0, 1, 0, 0 } };
public static void main(String[] args) {
AllColors f = new AllColors();
f.setTitle("All Colors");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
image = new BufferedImage(WIDTH * SCALE, HEIGHT * SCALE, BufferedImage.TYPE_3BYTE_BGR);
init();
//gui stuff
JPanel p = new JPanel(){
#Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.scale(SCALE, SCALE);
g2.drawImage(image, 0, 0, null);
}
};
p.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
f.add(p);
f.pack();
f.setVisible(true);
group(p);
}
//makes an image of all colors
private static void init() {
int x = 0;
int y = 0;
for(int r = 0; r < VALUES_PER_CHANNEL; r+= 1){
for(int g = 0; g < VALUES_PER_CHANNEL; g+= 1){
for(int b = 0; b < VALUES_PER_CHANNEL; b+= 1){
x++;
if(x % WIDTH == 0){
y++;
x = 0;
}
if(y >= HEIGHT)
return;
image.setRGB(x, y, new Color(r*CHANNEL_DELTA,g*CHANNEL_DELTA,b*CHANNEL_DELTA).getRGB());
}
}
}
}
//group together similar pixels
private static void group(JPanel panel){
Random rand = new Random();
for(long i = 0; i < TOTAL_ITERATIONS; i++){
Point first = new Point(rand.nextInt(WIDTH), rand.nextInt(HEIGHT));
Point second = new Point(rand.nextInt(WIDTH), rand.nextInt(HEIGHT));
trySwitch(first, second);
if(i % (WIDTH * HEIGHT) == 0){
System.out.println(i / (WIDTH * HEIGHT));
panel.repaint();
}
}
}
private static void swap(Point first, Point second){
int temp = image.getRGB(second.x, second.y);
image.setRGB(second.x, second.y, image.getRGB(first.x, first.y));
image.setRGB(first.x, first.y, temp);
}
//get how similar the neighbors are
private static int getNeighborDelta(int imageX, int imageY){
Color center = new Color(image.getRGB(imageX, imageY));
int sum = 0;
for (int x = 0; x < kernel[0].length; x++)
{
for (int y = 0; y < kernel.length; y++)
{
int weight = kernel[x][y];
if (weight <= 0)
{
continue;
}
int xOffset = x - (kernel[0].length / 2);
int yOffset = y - (kernel.length / 2);
try{
sum += getDistance(new Color(image.getRGB(imageX + xOffset, imageY + yOffset)), center) * weight;
}catch(ArrayIndexOutOfBoundsException e){
//if out of image
}
}
}
return sum;
}
//switches if the neighbors will be more similar
private static void trySwitch(Point first, Point second){
double firstDistance = getNeighborDelta(first.x, first.y);
swap(first, second);
double secondDistance = getNeighborDelta(first.x, first.y);
if(secondDistance > firstDistance)
swap(first, second);
}
//get similarity between colors
private static double getDistance(Color one, Color two){
int r = Math.abs(two.getRed() - one.getRed());
int g = Math.abs(two.getGreen() - one.getGreen());
int b = Math.abs(two.getBlue() - one.getBlue());
return r + g + b;
}
}
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
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.