Cutter Cutter - 2 months ago 19
Java Question

Colour background of JPanel from different class?

Trying to change the background colour of my JPanel from a different class using a variable. Why is this giving me an error? (Really new to java, sorry...)

import java.awt.Color;

import javax.swing.*;

public class window {

public window(int x, int y, boolean isVisible, boolean isResizable, Color col){
JFrame jframe = new JFrame();
int xSize = x;
int ySize = y;
jframe.setSize(xSize, ySize);
jframe.setVisible(isVisible);
jframe.setResizable(isResizable);

JPanel jpanel = new JPanel();
jframe.add(jpanel);
jpanel.setSize(xSize - 100, ySize - 100);
jpanel.setOpaque(true);
jpanel.setBackground(Color.col);
jpanel.setVisible(true);

}

}


My main class does this:

import java.awt.Color;


public class design {

public static void main(String[] args) {
window window1 = new window(400, 200, true, true, Color.green);
window window2 = new window(1000, 720, true, true, Color.red);
}

}


The error it is giving me is 'col cannot be resolved to a field'. Which I know means that it doesn't understand what col is doing there but that's what I'm confused by because I've declared it as a colour...

Answer

You refer to the variable get from the constructor.

Just change the jpanel.setBackground(Color.col); to:

jpanel.setBackground(col);