How to find variable g in this code? - java

How to find variable g in this code? I would like to draw line using fillRect from paintComponent.
Please help.
import java.awt.*;
import java.lang.String.*;
import java.util.Scanner;
import java.io.IOException;
import javax.swing.*;
class Test extends JPanel {
public static void main(String[] args) {
String x1;
String x2;
String y1;
String y2;
Scanner sc = new Scanner(System.in);
System.out.print("Podaj pierwsza wspolrzedna pierwszego punktu: ");
x1 = sc.nextLine();
System.out.print("Podaj druga wspolrzedna pierwszego punktu: ");
x2 = sc.nextLine();
System.out.print("Podaj pierwsza wspolrzedna drugiego punktu: ");
y1 = sc.nextLine();
System.out.print("Podaj druga wspolrzedna drugiego punktu: ");
y2 = sc.nextLine();
Test nowy = new Test();
DDA2 dda2 = new DDA2();
dda2.licz(x1, x2, y1, y2);
JFrame ramka = new JFrame();
ramka.setSize(300,300);
ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ramka.getContentPane().add(new Test());
ramka.setVisible(true);
}
}
class DDA2 {
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
}
public void licz(String xx1, String xx2, String yy1, String yy2){
double dxx1 = Double.parseDouble(xx1);
double dxx2 = Double.parseDouble(xx2);
double dyy1 = Double.parseDouble(yy1);
double dyy2 = Double.parseDouble(yy2);
double dx = dxx2 - dxx1;
double dy = dyy2 - dyy1;
if (Math.abs(dx) >= Math.abs(dy))
{
double m = Math.abs(dx);
System.out.println("DX" + m);
}
else
{
// ALGORYTYM PRZYROSTOWY
double m = Math.abs(dy);
//System.out.println("DY" + m);
double x = dxx1;
double y = dyy1;
for (int i=1; i <= m; i++)
{
x = x + dx/m;
y = y + dy/m;
g.fillRect((int) x, (int) y, 1, 1);
}
}
System.out.println("Wspolrzednie punktu pierwszego to: " + "(" + dxx1 + "; " + dxx2 +")");
System.out.println("Wspolrzednie punktu drugiego to: " + "(" + dyy1 + "; " + dyy2 + ")");
}
}

You need to override the paintComponent(Graphics g) method in the class that extends the JPanel, i.e. your Test class. You wrote a paintComponent method in a class DDA2 but that does nothing.
In the paintComponent method you can then call:
g.fillRect(x, y, w, h);

In addition to what Vincent says, it looks like you want to have the fillRect taking place in your licz method. No problem. Simply call your licz method from the paintComponent method. (It's easiest to do this if your method is defined in the same class as the paintComponent method, by the way.)

Related

Drawing Floats and Controlling Decimal Place

If you run this program you will notice that the table that displays the celsius conversion looks funky. What I have been trying to do is have it stop at the tenth place. I really would I appreciate any feedback. Thanks in advance.
Output:
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class Foo extends Frame
{
public Foo()
{
setTitle(" Fahrenheit To Celsius Chart");
setSize(400, 600);
setVisible(true);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public static void main(String[] args)
{
Foo chart = new Foo();
}
public void paint (Graphics g)
{
for(int i = 0; i < 25; i++)
{
g.setColor(Color.BLACK);
g.setFont(new Font("SansSerif", Font.BOLD, 14 ));
g.drawString("Fahrenheit", 70, 110);
g.drawString("Celsius", 200, 110);
int[] tempF = new int[25];
int y = 100, x = 130;
int y1 = 215, x1 = 130;
tempF[0] = 0;
int counter = 0;
while(counter < 26)
{
int index = 0;
String Fahrenheit = String.valueOf(tempF[index]);
double tempC = (tempF[index] - 32) * (5/9.0);
String Celsius = String.valueOf(tempC);
String formatedCelcius = String.format("%.1f", tempC);
g.drawString(Fahrenheit, y, x);
g.drawString(Celsius, y1, x1);
x += 15;
x1 += 15;
tempF[index] += 10;
index++;
counter++;
}
}
}
}
The code for rendering the temperatures should look like:
String Fahrenheit = String.valueOf(tempF[index]);
double tempC = (tempF[index] - 32) * (5/9.0);
String formattedCelcius = String.format("%.1f", tempC);
g.drawString(Fahrenheit, y, x);
g.drawString(formattedCelcius, y1, x1);
In your code, you did:
String.format("%.1f", Celsius);
Rather than:
String.format("%.1f", tempC);
(I hope the difference is clear)
The %f format specifier expects a Double argument (like tempC) but you were passing in a String (Celsius)
This caused a java.util.IllegalFormatConversionException: f != java.lang.String (which you may not have seen as the exception was thrown into the Swing event thread) which aborted the rest of paint method.
Thank you everyone for your feedback. I found the solution. The Math class has a function round() that did the trick. I put this in and it fixed the issue:
double tempC = (tempF[index] - 32) * (5/9.0);
double c = Math.round(tempC);
After changing this I'm getting the proper output:
Final Output
Again, thank you all for your feedback.
Best regards,
DDKGM

Java - A value resets to 0 unexpectedly

I'm making a derivative calculator that asks the user for the degree of their polynomial and then the coefficients for each term, partly because I'm an inexperienced programmer and can't parse input like 3x^4/4 + sin(x).
Here's my class.
package beta;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class DerivativeCalculator
{
public DerivativeCalculator(String d, String v)
{
int degree = Integer.parseInt(d);
double value = Double.parseDouble(v);
coeffList = new ArrayList<Double>();
for (int i = 0; i <= degree; i++)
{
String console = JOptionPane.showInputDialog("Enter the coefficient of the "
+ "x^" + i + " term.");
Double coeff = Double.parseDouble(console);
coeffList.add(coeff);
}
}
public double calc()
{
double dx = 0.0001;
double x1 = value;
double y1 = 0;
for (int d = degree; d >= 0; d--)
{
y1 += coeffList.get(d) * Math.pow(x1, d);
}
double x2 = x1 + dx;
double y2 = 0;
for (int d = degree; d >= 0; d--)
{
y2 += coeffList.get(d) * Math.pow(x2, d);
}
double slope = (y2 - y1)/ (x2 - x1);
DecimalFormat round = new DecimalFormat("##.##");
round.setRoundingMode(RoundingMode.DOWN);
return Double.valueOf(round.format(slope));
}
public String getEquation()
{
String equation = "";
for (int d = degree; d >= 0; d--)
{
equation = equation + String.valueOf(coeffList.get(d)) + "x^" + String.valueOf(d) + " + ";
}
return equation;
}
public String getValue()
{
return String.valueOf(value);
}
private int degree;
private double value;
private List<Double> coeffList;
}
Now here's my test class.
package beta;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
public class DerivativeCalculatorTest extends JApplet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
String d = JOptionPane.showInputDialog("Enter the degree of your polynomial: ");
String v = JOptionPane.showInputDialog("Enter the x value "
+ "at which you want to take the derivative");
DerivativeCalculator myDerivCalc = new DerivativeCalculator(d, v);
g2.drawString(String.valueOf(myDerivCalc.calc()), 10, 100);
g2.drawString(myDerivCalc.getEquation(), 10, 40);
g2.drawString(myDerivCalc.getValue(), 10, 70);
}
}
Running this creates an applet window that displays
5.0x^0+
0.0
0.0
which is not the correct derivative.
I debugged my program and everything runs as expected until the view switches to my test class and it executes g2.drawString(String.valueOf(myDerivCalc.calc()), 10, 100);
After it executes this line, degree (the degree of the polynomial) resets to 0 even though the user entered 5. This then messes up all the for loops in my class.
Why does this happen? Any suggestions on fixing this? Thanks
You redefine degree and value as local variables inside your constructor. They shadow your class variables with the same name.
Do not re-declare them.
Instead of
int degree = <something>;
double value = <something>;
you need
degree = <something>;
value = <something>;
Isn't 5.0x^0 = 5.0 * 1 = 5.0, and the derivative of that is 0..
I believe your code is working.

I'm trying to draw a new dot every 250 milliseconds but it only draws a dot once

//I'm trying to draw a new dot every 250 milliseconds but it only draws the dot a single time. I have tried fixing it many times, but it still will only paint a single dot, rather than one after 250 milliseconds. Is this a problem with the timer or the paint method? Here is the code:
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Window extends JPanel{
private int size;
private static double maxValue;
private double elevation;
private double vertV;
public double horizV;
public double gravity;
public double range;
public double time;
public double t = 0;
public Window(int s, double v, double e, double v2, double g,double h,double r,double t){
size = s;
maxValue = v;
elevation = e;
vertV = v2;
gravity = g;
horizV = h;
range = r;
time = t;
setPreferredSize(new Dimension(size, size));
}
public void paintComponent(Graphics g){
g.drawLine(size/25, 0,size/25, size);
g.drawLine(0, size - (size/25), size, size - (size/25));
double[] lines = getLine();
int x = size/5 + (size/25), y = size - (size/25);
int x2 = x;
for(int i = 0; i < 4; i++){
g.drawLine(x, y+5, x, y-5);
g.drawString(lines[i]+"",x-size/50,y+size/30);
x+=x2;
}
int yx = size/25, yy = size - (size/5 + (size/25));
int y2 = size/5 + (size/25);
for(int i=0;i<4;i++){
g.drawLine(yx-5, yy, yx+5, yy);
g.drawString(lines[i]+"",yx-size/25,yy+size/30);
yy -= y2;
}
drawDots(g);
}
//this is the place where i make the dots but it only makes one.
//used to be a for loop but i altered it to an if statement so i could paint one dot at a time
public void drawDots(Graphics g)
{
double ratio = (size-((size/25)*2))/maxValue;
double fx;
double xvalue;
// This for loop is where dots are drawn, each iteration draws one dot. It starts at zero, and counts up to the time variable t.
if(t<=time)
{
t+=0.025;
t = Math.round(t*1000.0)/1000.0;
fx = function(t);
xvalue = xfunction(t);
if(fx >= 0){
System.out.print("Time: " + t + " " + "Range: " + xvalue + " " + "Height: ");
System.out.println(fx);
g.drawLine((int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)),
(int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)));
}
}
}
//where i make the timer
//250 mill
public void dostuff()
{
int delay = 250;
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
repaint();
}
};
new Timer(delay, taskPerformer).start();
}
public double xfunction(double t){
double x = 0.0;
x = Math.round(horizV * t * 1000.0)/1000.0;
return x;
}
public double function(double t){
double fx = 0.0;
fx = Math.round((vertV*t + .5*(-(gravity))*(t*t) + elevation)*1000.0)/1000.0;
return fx;
}
private static double[] getLine(){
double increment = maxValue / 4;
double currentLine = 0;
double[] lines = new double[4];
for(int i = 0; i < 4; i++){
currentLine+=increment;
lines[i] = Math.round(currentLine * 10.0)/10.0;
}
return lines;
}
}
This is the original version of the code that displays the projectile's motion, but it does not wait 250 milliseconds between drawing each point:
import javax.swing.JPanel;
import java.awt.*;
public class Window extends JPanel{
private int size;
private static double maxValue;
private double elevation;
private double vertV;
public double horizV;
public double gravity;
public double range;
public double time;
public Window(int s, double v, double e, double v2, double g,double h,double r,double t){
size = s;
maxValue = v;
elevation = e;
vertV = v2;
gravity = g;
horizV = h;
range = r;
time = t;
setPreferredSize(new Dimension(size, size));
}
public void paintComponent(Graphics g){
g.drawLine(size/25, 0,size/25, size);
g.drawLine(0, size - (size/25), size, size - (size/25));
double[] lines = getLine();
int x = size/5 + (size/25), y = size - (size/25);
int x2 = x;
for(int i = 0; i < 4; i++){
g.drawLine(x, y+5, x, y-5);
g.drawString(lines[i]+"",x-size/50,y+size/30);
x+=x2;
}
int yx = size/25, yy = size - (size/5 + (size/25));
int y2 = size/5 + (size/25);
for(int i=0;i<4;i++){
g.drawLine(yx-5, yy, yx+5, yy);
g.drawString(lines[i]+"",yx-size/25,yy+size/30);
yy -= y2;
}
drawDots(g);
}
public void drawDots(Graphics g){
double ratio = (size-((size/25)*2))/maxValue;
double fx;
double xvalue;
// This for loop is where dots are drawn, each iteration draws one dot. It starts at zero, and counts up to the time variable t.
for(double t=0;t<=time; t+=0.025){
t = Math.round(t*1000.0)/1000.0;
fx = function(t);
xvalue = xfunction(t);
if(fx >= 0){
System.out.print("Time: " + t + " " + "Range: " + xvalue + " " + "Height: ");
System.out.println(fx);
g.drawLine((int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)),
(int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)));
}
}
}
public double xfunction(double t){
double x = 0.0;
x = Math.round(horizV * t * 1000.0)/1000.0;
return x;
}
public double function(double t){
double fx = 0.0;
fx = Math.round((vertV*t + .5*(-(gravity))*(t*t) + elevation)*1000.0)/1000.0;
return fx;
}
private static double[] getLine(){
double increment = maxValue / 4;
double currentLine = 0;
double[] lines = new double[4];
for(int i = 0; i < 4; i++){
currentLine+=increment;
lines[i] = Math.round(currentLine * 10.0)/10.0;
}
return lines;
}
}

Unexpected paint order in for loop

Could anyone help me figure out why my circle is not printing out on top of the square all the way to the top? The square seems to print out onto the frame perfectly fine but I've been unable to figure out why the loop stops after the 2nd row but never completing up to the 6th row. thank guys!
This is my main ExampleGUI.java class
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);
}
}
This is my method/constructor class 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;
for (j = 1; j < 7; j++) {
x = 0;
x2 = x + 5;
System.out.println(x + " " + y);
for (i = 1; i < 7; i++) {
g.setColor(Color.red);
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);
g.setColor(Color.black);
g.drawOval(x2, y2, w2, h2);
x = x + w;
x2 = x2 + w2 + 10;
}
x = x + w;
y2 = 505;
y = y - h;
y2 = (y2 - h2) - 10;
}
}
}
You have to remove your y2= 505;
You have mistakenly set your y2 to the same value each iteration :)

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