Can't call paint() method from another class
Hi, so I'm planning to create a basic game with levels which are each painted from their own seperate level classes. I've made a class called 'Level1' which has the paint method which I want to use in and then also a class which I want to call the method in. When I try to call 'paint(g)' it gives the error g cannot be resolved as a variable.
Here's my code, any help will be much appreciated.
Level1
Code :
package maze;
import java.awt.*;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Level1 extends JPanel {
private Image wall;
public Level1(){
ImageIcon ii = new ImageIcon(this.getClass().getResource("wall.png"));
wall = ii.getImage();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = ( Graphics2D )g;
for(int i = 0; i <= 18; i++){
g2.drawImage(wall, i*30, 0, this);
g2.drawImage(wall, i*30, 540, this);
g2.drawImage(wall, 0, i*30, this);
g2.drawImage(wall, 570, i*30, this);
g2.drawImage(wall, 120, i*30, this);
}
}
}
Board
Code :
package maze;
import java.awt.*;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import maze.Level1;
public class Board extends JPanel {
Level1 level1 = new Level1();
public Board() {
setFocusable(true);
setBackground(Color.DARK_GRAY);
setDoubleBuffered(true);
setSize(400, 300);
level1.paint(g);
}
}
Re: Can't call paint() method from another class
First, you should override paintComponent, and not paint. Second, you should not call this method directly. Rather, add each component to its parent. This alone when added to a top level component hierarchy is often all that is needed. If you wish to repaint the component, then call repaint(). If you are still having problems, then I suggest posting an SSCCE and describe exactly what the problem is.
Re: Can't call paint() method from another class
Sorry to sound really stupid, but how would I do all that?
Re: Can't call paint() method from another class
The first place I'd start looking would be the Swing Custom Painting Tutorials. I think that most of us learned our Swing graphics starting at this site.
Re: Can't call paint() method from another class
Had a quick look at that and looks very helpful, I'll go through it properly afterschool, thankyou very much!