Rainfall Java program bug - java

The thing is that I'm a beginner on this of programming and I'm trying to make a program that simulates a rainfall. My problem is when I want to make an array of various raindrops fall they didn't.
Previously I've made a class for a drop, and I made the array in other class.
So when I execute the program, this paint all the array of drops in different x positions but those didn't move down.
This is the code of Drop class:
public class Drop
{
private Random random = new Random();
private int x = random.nextInt(600);
private int y;
private int yspeed;
public Drop()
{
random = new Random();
}
public void fall()
{
y = y + yspeed;
}
public void draw(Graphics g)
{
g.setColor(Color.BLUE);
g.drawLine(x, y, x, y + 15);
}
}
And this is the class where it's painted:
public class Panel extends JPanel
{
private Drop[] drops = new Drop[100];
private Drop d = new Drop();
private static final long serialVersionUID = 1L;
public Panel()
{
setBackground(Color.CYAN);
for (int i = 0; i < drops.length; i++)
{
drops[i] = new Drop();
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < drops.length; i++)
{
d.fall();
drops[i].draw(g);
}
}
}
I'm a beginner on this and I'll appreciate any help you give me. Thanks.

Related

Java Swing, I am using a for loop in draw but only the last element is rendered on panel

Edited as an MRE. I wasn't really sure how to write the code without extending JFrame or JPanel. This will reproduce the same error I am seeing. I am trying to render bars on the JPanel, but it seems that only the last iteration of the for loop in the PlotPanel class is being drawn.
package com.company;
import java.awt.*;
import javax.swing.*;
public class VisualizeAlgorithms {
public static int initPosX = 0;
public static int initPosY = 0;
public static int numBars = 200;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
PlotFrame frame = new PlotFrame();
});
}
}
class PlotFrame extends JFrame {
PlotPanel plotPanel;
PlotFrame() {
plotPanel = new PlotPanel();
this.add(plotPanel);
this.setTitle("Plot");
this.setBackground(Color.DARK_GRAY);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
public int[] createArray(int numBars) {
int[] numsArray = new int[numBars];
for (int i = 0; i < numBars; i++) {
numsArray[i] = i + 1;
}
return numsArray;
}
}
class PlotPanel extends JPanel{
static final int PLOT_WIDTH = 1200;
static final int PLOT_HEIGHT = 800;
static final int MAX_BAR_HEIGHT = PLOT_HEIGHT;
static final int BAR_WIDTH = PLOT_WIDTH / VisualizeAlgorithms.numBars;
Dimension plotSize = new Dimension(PLOT_WIDTH, PLOT_HEIGHT);
PlotPanel() {
this.setPreferredSize(plotSize);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.CYAN);
draw(g);
}
public void draw(Graphics g){
int numBars = VisualizeAlgorithms.numBars;
for (int i = 0; i < numBars; i++) {
g.fillRect(BAR_WIDTH * i, VisualizeAlgorithms.initPosY, BAR_WIDTH, ((i+1)/numBars)*(MAX_BAR_HEIGHT));
}
}
}
Not sure if I can accept comments as answers, so I posted the answer here. It was indeed changing the rectangle height to int h = ((i+1)*MAX_BAR_HEIGHT/numBars). Thanks both to #AndrewThompson and #c0der not only for the answer but the additional information as well.
Aside: #c0der gave great advice re "when in doubt, print out". I recommend using this change:
public void draw(Graphics g){
int numBars = VisualizeAlgorithms.numBars;
for (int i = 0; i < numBars; i++) {
int x = BAR_WIDTH * I;
int y = VisualizeAlgorithms.initPosY;
int w = BAR_WIDTH;
int h = ((i+1)/numBars)*(MAX_BAR_HEIGHT);
System.out.println(String.format("x,y WxH: %1s,%1s %1sx%1s", x,y,w,h));
g.fillRect(x,y,w,h);
}
}
(print the values used for fillRect)

Drawing new Graphics in ArrayList

I have an application, in which a car is moving on a panel and it creates sound waves - circles. I want to :
1) have a few circles at the moment of opening the frame
2) when the Start button is selected I want them to move and I want more circles to be created, one after another, until the stop button is selected
the problem is:
1) when the frame is opened there are 5 circles, but they totally do not move
2) 5 new circles appears, but from the same XY position, they are just bigger - I want one circle after another, it grows, and next one appears
here is my code, I would appreciate some helpful sample or could you tell me where my mistake is. I used amount of 5 just to have some samples of waves.
public class WaveParameters {
int xPos=0;
int yPos = 375;
int width=60;
int height=60;
int velX = 0 ;
private Color color = Color.WHITE;
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getX() {
return xPos;
}
public void setX(int xPos) {
this.xPos = xPos;
}
public int getWidth(){
return width;}
public int getHeight(){
return height;}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void paint(Graphics g){
g.setColor(getColor());
g.drawOval(xPos,yPos,width/2,height/2);
}
}
Here is the panel of animation:
public class PanelAnimation extends JPanel implements ActionListener{
List<WaveParameters> waves = new ArrayList<WaveParameters>();
public PanelAnimation(ResourceBundle bundle) {
super();
resourceBundle = bundle;
t.start();
try {
imageBackground = ImageIO.read(newFile("bg.png"));
} catch (IOException ex) {
// handle exception...
}
}
CarParametrs pAuto = new CarParametrs();
HumanParametrs pHuman = new HumanParametrs() ;
Timer t = new Timer(60,this);
//WaveParameters pWave = new WaveParameters();
private BufferedImage imageBackground;
MainFrame mf;
public void addAuto(){
CarParametrs ap = new CarParametrs();
ap.setX(0);
pAuto = ap;
}
public void addHuman(){
HumanParametrs acz = new HumanParametrs();
acz.setX(0);
pHuman = acz;
}
public void addWave() {
for (int i=0; i<5; i++) {
WaveParameters wave = new WaveParameters();
// wave.setX(pAuto.xPos);
wave.setColor(Color.white);
wave.setWidth(wave.width*i);
wave.setHeight(wave.height*i);
waves.add(wave);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imageBackground, 0, 0, null);
pAuto.paint(g);
pHuman.paint(g);
//if(mf.buttonStart.isSelected()) {
addWave();
//for (int i=0; i<5; i++) {
for (WaveParameters w : waves) {
// waves.add(new WaveParameters());
w.setX(pAuto.xPos);
w.paint(g);
//}
}
//}
}
public void actionPerformed(ActionEvent e) {
CarParametrs pa = pAuto;
pa.xPos += pa.velX;
/*//WaveParameters wp = pWave;
wp.xPos = pa.xPos;
wp.xPos+=wp.velX;
wp.height+=wp.velX;
wp.width+=wp.velX;
wp.yPos-=wp.velX/5 ;*/
for (WaveParameters w : waves) {
w.xPos = pa.xPos;
w.xPos+=w.velX;
w.height+=w.velX;
w.width+=w.velX;
w.yPos-=w.velX/5 ;
}
repaint();
}
and here is a wave-part of action listener for Start Button:
List<WaveParameters> wave = panelAnimation.waves;
for (WaveParameters w : wave) {
for (int i=0;i<5;i++) {
wave.add(new WaveParameters());
w.velX = Integer.parseInt(button2.getName());
w.xPos += w.velX;
w.width++;
w.height++;
w.yPos-=w.velX/5;
}
}
panelAnimation.repaint();
The five new bigger circles that appear are likely due to the last chunk of code where you iterate through all the waves in panel animation.
The "wave.add(new WaveParameters());" seems unnecessary, and may be the reason why your old waves are staying. Delete that line, and it may work.

How do I paint multiple objetcs that move at different speeds in Java?

I am working on homework for class, and its late because I can't seem to understand the material despite all the research that I am doing. I am a beginner and do not know much in the way of java. Also, this is my first post so please be forgiving when you are reading this.
I am building on source code from my textbook, which I updated recently for past homework, but now I am trying to generate a class that draws multiple squares and moves those objects independently and at different speeds. They will all need to rebound off the walls as well. I followed the instructions and created two arrays that will hold the random x and y values between 1 and 10. However, I struggle with arrays and I am sure that I am not doing it correctly. So, I would love some feedback to see if I have it set up correctly.
I have a the jpanel pulling up and drawing, and as long as there is 1 square it is working fine bouncing off the walls, but things change when I draw more than one. The do not move independently and they also share the same speed. Some even disappear from time to time. This has really thrown me off. I appreciate any help!
In short, I am trying to paint new squares that all travel in different directions and at different speeds. Per the instructions we are suppose create and use a two arrays that handle the x and y values.
Here is what I have so far:
public class DotsPanel extends JPanel
{
private int delay = 15;
private final int SIZE = 7, IMAGE_SIZE = 3; // radius of each dot
private Timer timer;
private int x, y, i;
private ArrayList<Point> pointList;
static int [] xarray = new int [1000];
static int [] yarray = new int [1000];
Random rand = new Random();
//-----------------------------------------------------------------
// Constructor: Sets up this panel to listen for mouse events.
//-----------------------------------------------------------------
public DotsPanel()
{
pointList = new ArrayList<Point>();
int [] xarray = new int [1000];
int [] yarray = new int [1000];
timer = new Timer(delay, new ReboundListener());
addMouseListener (new DotsListener());
addMouseMotionListener (new DotsListener());
setBackground(Color.gray);
setPreferredSize(new Dimension(700, 500));
for(int i = 0; i < xarray.length; i++)
{
xarray[i] = rand.nextInt(7);
yarray[i] = rand.nextInt(7);
}
timer.start();
}
//-----------------------------------------------------------------
// Draws all of the dots stored in the list.
//-----------------------------------------------------------------
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor(Color.BLUE);
for (Point spot : pointList)
{
page.fillRect(spot.x-SIZE, spot.y-SIZE, 25, 25);
page.drawString("Count: " + pointList.size(), 5, 15);
}
}
//*****************************************************************
// Represents the listener for mouse events.
//*****************************************************************
private class DotsListener implements MouseListener, MouseMotionListener
{
//--------------------------------------------------------------
// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is pressed.
//--------------------------------------------------------------
public void mousePressed(MouseEvent event)
{
pointList.add(event.getPoint());
repaint();
}
public void mouseDragged(MouseEvent event)
{
// initially I had two xarray and yarray in here just like in
// mouseClicked
// but it did not change anything when removed
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseClicked(MouseEvent event)
{
xarray[i] = rand.nextInt(7);
yarray[i] = rand.nextInt(7);
}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseMoved(MouseEvent e) {}
}
private class ReboundListener implements ActionListener
{
//--------------------------------------------------------------
// Updates the position of the image and possibly the direction
// of movement whenever the timer fires an action event.
//--------------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
for (Point spot : pointList)
{
spot.x += xarray[i];
spot.y += yarray[i];
if (spot.x <= 0 || spot.x >= 700)
xarray[i] = xarray[i] * -1;
if (spot.y <= 0 || spot.y >= 500)
yarray[i] = yarray[i] * -1;
repaint();
}
}
}
}
However, I struggle with arrays and I am sure that I am not doing it correctly.
I wouldn't use Arrays.
Instead, have a Ball object manage its own state. Then you can have different color, speed, size etc for each Ball. Then when the Timer fires you just calculate the new position and repaint the Ball.
Here is an example to get you started:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class BallAnimation4
{
private static void createAndShowUI()
{
BallPanel panel = new BallPanel();
JFrame frame = new JFrame("BallAnimation4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setSize(800, 600);
frame.setLocationRelativeTo( null );
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible( true );
panel.addBalls(5);
panel.startAnimation();
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
class BallPanel extends JPanel implements ActionListener
{
private ArrayList<Ball> balls = new ArrayList<Ball>();
public BallPanel()
{
setLayout( null );
setBackground( Color.BLACK );
}
public void addBalls(int ballCount)
{
Random random = new Random();
for (int i = 0; i < ballCount; i++)
{
Ball ball = new Ball();
ball.setRandomColor(true);
ball.setLocation(random.nextInt(getWidth()), random.nextInt(getHeight()));
ball.setMoveRate(32, 32, 1, 1, true);
// ball.setMoveRate(16, 16, 1, 1, true);
ball.setSize(32, 32);
balls.add( ball );
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Ball ball: balls)
{
ball.draw(g);
}
}
public void startAnimation()
{
Timer timer = new Timer(75, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
move();
repaint();
}
private void move()
{
for (Ball ball : balls)
{
ball.move(this);
}
}
class Ball
{
public Color color = Color.BLACK;
public int x = 0;
public int y = 0;
public int width = 1;
public int height = 1;
private int moveX = 1;
private int moveY = 1;
private int directionX = 1;
private int directionY = 1;
private int xScale = moveX;
private int yScale = moveY;
private boolean randomMove = false;
private boolean randomColor = false;
private Random myRand = null;
public Ball()
{
myRand = new Random();
setRandomColor(randomColor);
}
public void move(JPanel parent)
{
int iRight = parent.getSize().width;
int iBottom = parent.getSize().height;
x += 5 + (xScale * directionX);
y += 5 + (yScale * directionY);
if (x <= 0)
{
x = 0;
directionX *= (-1);
xScale = randomMove ? myRand.nextInt(moveX) : moveX;
if (randomColor) setRandomColor(randomColor);
}
if (x >= iRight - width)
{
x = iRight - width;
directionX *= (-1);
xScale = randomMove ? myRand.nextInt(moveX) : moveX;
if (randomColor) setRandomColor(randomColor);
}
if (y <= 0)
{
y = 0;
directionY *= (-1);
yScale = randomMove ? myRand.nextInt(moveY) : moveY;
if (randomColor) setRandomColor(randomColor);
}
if (y >= iBottom - height)
{
y = iBottom - height;
directionY *= (-1);
yScale = randomMove ? myRand.nextInt(moveY) : moveY;
if (randomColor) setRandomColor(randomColor);
}
}
public void draw(Graphics g)
{
g.setColor(color);
g.fillOval(x, y, width, height);
}
public void setColor(Color c)
{
color = c;
}
public void setLocation(int x, int y)
{
this.x = x;
this.y = y;
}
public void setMoveRate(int xMove, int yMove, int xDir, int yDir, boolean randMove)
{
this.moveX = xMove;
this.moveY = yMove;
directionX = xDir;
directionY = yDir;
randomMove = randMove;
}
public void setRandomColor(boolean randomColor)
{
this.randomColor = randomColor;
switch (myRand.nextInt(3))
{
case 0: color = Color.BLUE;
break;
case 1: color = Color.GREEN;
break;
case 2: color = Color.RED;
break;
default: color = Color.BLACK;
break;
}
}
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
}
}
Since your Arrays only contain the Point you want to paint you don't have any information about the speed each point should be moved at. The best you could do is create a random amount each point should be moved each time its location is changed. This would give erratic movement as each time you move a point the distance would be random.
If you want more constant speed then you would need to create a second Array to contain the distance each point should move every time.
This starts to get messy creating a new Array every time you want a new property to be unique for the object you want to paint. That is why the approach to create a custom Object with multiple properties is easier to manage.

Drawing functions, JFrame wrong results

I have a Problem, I tried to build up a code to visualise Functions.
package main;
import java.awt.*;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyPanel extends JPanel{
private static final long serialVersionUID = -6649271997955423098L;
#Override
public void paintComponent(Graphics g)
{
//super.paintComponents(g); only show code how it works
//g.setColor(Color.cyan);
//g.fillRect(10, 20, 35, 78);
paintStuff(g);
paintBackgroundComponents(g); // the navigation cross in the background
paintFunctions(g); //Both
leftPaintLineFunction(g); //with test Functions
rightPaintLineFunction(g);
}
/**
* Own Method for drawing lines. Needs Graphics g!
* #param g
*/
private void paintStuff(Graphics g)
{
g.setColor(Color.black);
g.drawString("Integral Veranschaulichung", (Main.length)-(Main.length/3),((Main.width) - (Main.width/12)));
}
private void paintBackgroundComponents(Graphics g)
{
g.drawLine((Main.length)/2, Main.width, (Main.length)/2, 0);
g.drawLine(0, (Main.width)/2, Main.length, (Main.width)/2);
g.setColor(Color.red);
g.drawString("X", (Main.length-(Main.length/8)) , ((Main.width/2) - (Main.width/80)));
g.drawString("Y", ((Main.length/2)+(Main.length/80)) , ((Main.width) - (Main.width/8)));
}
private void paintFunctions(Graphics g)
{
g.setColor(Color.blue);
for(int x=(0 - Main.length); x < Main.length; x++) //fills all possible values (limited through length)
{
g.drawOval((x) + (Main.length/2-1), Functions.solveTestFunction(x)+(Main.width/2-1), 3, 3);
}
}
//needs different methods for left and right Side
private void leftPaintLineFunction(Graphics g)
{
int [] pointOneX = new int [Main.length*2];
int [] pointOneY = new int [Main.length*2];
for(int x = 0; x < Main.length; x++)
{
pointOneX[x] = (((x)*(-1)) + (Main.length/2-1));
pointOneY[x]= (Functions.solveTestFunction(x) + (Main.width/2-1));
System.out.print(pointOneX[x]+" ");
System.out.print(pointOneY[x]);
}
g.drawPolyline(pointOneX, pointOneY, 100);
}
private void rightPaintLineFunction(Graphics g)
{
int [] pointOneX = new int [Main.length*2];
int [] pointOneY = new int [Main.length*2];
for(int x = 0; x < Main.length; x++)
{
pointOneX[x] = ((x) + (Main.length/2+2)); //no clue why 2?
pointOneY[x]= (Functions.solveTestFunction(x) + (Main.width/2));
System.out.print(pointOneX[x]+" ");
System.out.print(pointOneY[x]);
}
g.drawPolyline(pointOneX, pointOneY, 100);
}
}
My other class is:
package main;
public class Functions
{
int x = 0;
public static int solveTestFunction(int x) //simpel test function
{
int y=0;
y = (x^2)*(-1);//-1 cause the gui uses changed sides
return y;
}
}
And my main method is this one:
package main;
import javax.swing.JFrame;
public class Main {
static int length = 1000; // Playgrounds measures
static int width = 1000;
public static void main(String[] args)
{
JFrame frame = new JFrame("My Drawings");
MyPanel panel = new MyPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(length, width); //playground
frame.add(panel);
frame.setVisible(true);
}
}
I split the method rightpaintLineFUnctions() in left and right. Cause that was the only way I get them to work. When I tried x*x for my testFunction everything worked quit good. But since Iwrote it in this form x^2 it didn't worked correct. Some help would be very nice.

How to refer ChangeListener of one class to another class?

I DISCARD ALL THESE CODE AND WORK ON TOTALLY DIFFERENT ONE>>>
NO NEED TO ANSWER ANYMORE
I got a homework from my professor. He told us to make applet paint program using 4 classes.
Main; LightSourcePanel;DrawingPanel;PalettePanel;
(The basic code are not giving; only the class)
The program will take Mouse input and draw circle when I make a circular line. And the circle will have a 'glowing effect' depend on the lightSource (Use JSlider as light). When the JSlider is slided, the circle glowing effect change real time.
I am having problem referring the LightSource event Listener to the Drawing so It change the 'int light' inside the DrawingPanel. I don't know why the refering in the JColorChooser work while this one don't.
(It gave me java "non-static method cannot be referenced from a static" and I can't change it to static since I need to call repaint() method )
This is my Third class assignment and professor just taught us basic action listener in a single class. So I have no idea what Am I doing. If possible please explain my mistake in detail.
Main code:
public class HW3_to_4 extends Applet {
public void init (){
Dimension d = this.getSize();
setLayout(new BorderLayout());
JPanel Pale = new PalettePanel();
Pale.setBorder(BorderFactory.createLineBorder(Color.black, 5));
JPanel Light = new LightSourcePanel();
Light.setBorder(BorderFactory.createLineBorder(Color.black, 5));
JPanel Draw = new DrawingPanel();
Cursor c = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
Draw.setCursor(c);
Draw.setBorder(BorderFactory.createLineBorder(Color.green, 3));
add(Pale, BorderLayout.SOUTH );
add(Light,BorderLayout.NORTH);
add(Draw,BorderLayout.CENTER);
}
}
PalettePanel Code:
class PalettePanel extends JPanel implements ChangeListener {
JColorChooser j;
public PalettePanel () {
j = new JColorChooser ();
j.setPreviewPanel(new JPanel());
j.getSelectionModel().addChangeListener(this);
this.add(j);
}
public void stateChanged (ChangeEvent e){
Color a = j.getColor();
DrawingPanel.changecolor (a);
}
}
DrawingPanel Code & sub class inside (DrawingCanvas and Polyline)
I rip this off from a example page in YAIP.
:
public class DrawingPanel extends JPanel {
private List<PolyLine> lines = new ArrayList<PolyLine>();
private static PolyLine currentline;
private int maxX,maxY,difX, difY,minX,minY;
private static int lightSource = 0;
public static final int CANVAS_WIDTH = 2000;
public static final int CANVAS_HEIGHT = 800;
public static int[][] circle = new int[1000][4];
public static int check = 0;
public static Color c = Color.RED;
public DrawingPanel(){
DrawingCanvas canvas = new DrawingCanvas();
Dimension d = new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT);
canvas.setPreferredSize(d);
canvas.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
currentline = new PolyLine();
currentline.line_color = c;
lines.add(currentline);
currentline.add(e.getX(), e.getY());
}
});
canvas.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentline.add(e.getX(), e.getY());
repaint();
}
});
canvas.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
for(int i = 0; i<currentline.xList.size()-1; i++){
if(maxX<currentline.xList.get(i)){
maxX = currentline.xList.get(i);
}
}
for(int i = 0; i<currentline.yList.size()-1; i++){
if(maxY<currentline.yList.get(i)){
maxY = currentline.yList.get(i);
}
}
minX = maxX;
for(int i = 0; i<currentline.xList.size()-1; i++){
if(minX>currentline.xList.get(i)){
minX = currentline.xList.get(i);
}
}
minY = maxY;
for(int i = 0; i<currentline.yList.size()-1; i++){
if(minY>currentline.yList.get(i)){
minY = currentline.yList.get(i);
}
}
difX = maxX - minX;
difY = maxY - minY;
currentline.addcircle(minX,minY, difX, difY);
circle[check][0] = minX;
circle[check][1] = minY;
circle[check][2] = difX;
circle[check][3] = difY;
check++;
repaint();
maxX = 0; difX = 0;
maxY = 0; difY = 0;
}
});
this.add(canvas);
}
public static void changecolor(Color b){
c = b;
}
public void lightChange (int light){
lightSource = light;
RE();
}
public void RE (){
for (int x = 0; x< check ; x++) currentline.addcircle(circle[x][0],circle[x][1], circle[x][2],circle[x][3],lightSource);
repaint();
}
private class DrawingCanvas extends JPanel{
public void paint(Graphics g){
for(PolyLine line : lines){
g.setColor(line.line_color);
line.draw(g);
}
}
}
static class PolyLine{
public Color line_color = Color.RED;
private List <Integer> xList;
private List <Integer> yList;
boolean drawcircle = false;
int minx, miny, difx, dify, light;
public PolyLine() {
xList = new ArrayList<Integer>();
yList = new ArrayList<Integer>();
}
public void add(int x, int y){
xList.add(x);
yList.add(y);
}
public void addcircle(int x, int y, int difx, int dify){
this.minx = x; this.miny = y; this.difx = difx; this.dify = dify;
drawcircle = true;
}
public void addcircle(int x, int y, int difx, int dify, int light){
this.minx = x; this.miny = y; this.difx = difx; this.dify = dify; this.light = light;
drawcircle = true;
}
public void draw(Graphics g){
if(drawcircle){
g.fillOval(minx, miny, difx, dify);
g.setColor(Color.WHITE);
g.fillOval((minx+difx/4)+light, miny+dify/4, difx/4, dify/4);
g.setColor(line_color);
}else{
for(int i = 0; i<xList.size()-1; i++){
g.drawLine((int)xList.get(i), (int)yList.get(i), (int)xList.get(i + 1),
(int)yList.get(i + 1));
}
}
}}}
>
Here is the problem.
LightSourcePanel Code:
class LightSourcePanel extends JPanel implements ChangeListener {
static JSlider j;
public LightSourcePanel (){
j = new JSlider(0,180,90);
j.setMajorTickSpacing(45);
j.setMinorTickSpacing(5);
j.setPaintLabels(true);
j.setPaintTicks (true);
j.setPreferredSize(new Dimension (1500,50));
j.addChangeListener(this);
this.add(j);
}
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
lightChange(j.getValue()); // problem <<<<<< FAIL
}}
First off, change the changecolor(Color) method in DrawingPanel to remove the static keyword. Then you need an instance of DrawingColor to use the class. I would store the instance of it in a field just like JColorChooser is stored.

Categories