Reputation: 69
I am trying to call the paint()
method from another class, but it just doesn't work.
Here is the code:
Main.java
:
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private int WIDTH = 600;
private int HEIGHT = 400;
private String NAME = "Dark Ages";
private String VERSION = "0.0.1 Pre-Alpha";
static boolean running = false;
private Image dbImage;
private Graphics dbg;
public Main() {
//Initialize window
JFrame frame = new JFrame();
frame.setTitle(NAME + " - " + VERSION);
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//Running
running = true;
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
// Draw Images
repaint();
}
public static void main(String args[]) {
new Main();
Player player = new Player();
}
}
Player.java
:
public class Player {
public void paint(Graphics g) {
g.drawRect(100, 100, 100, 100);
}
}
Upvotes: 2
Views: 13880
Reputation: 285403
How do I call the paint() method from another class in java?
In brief, you don't. And in fact, you shouldn't call it directly from the same class either. Instead you should change the state of the class (change its fields), and then call repaint()
on it, which will suggest to the JVM that the component should be painted.
Other issues and suggestions:
JFrame
, JDialog
or other top-level window. These windows have too many roles to play behind the scenes that you don't really want to mess with how they render themselves or their children (unless you really know what you're doing and have definite need).paintComponent(...)
method override of a JPanel
or other JComponent
s.paintComponent(...)
override, don't forget to call the super
's method: super.paintComponent(g);
. This will allow Swing to do housekeeping drawing, such as erasing old out of date or deleted images, before you do your drawing.Player
class extends no Swing component and is added to no top level window, so its code will do nothing useful. Again, read the tutorials.repaint()
from within paint(...)
or paintComponent(...)
.Please post modified code if possible.
: please don't ask us to create code for you as that's your job. Please understand that the more code you create, the better a coder you'll be, and because of this, most of us don't feel that we should cheat you out of the opportunity to create your own code. Useful Java Tutorials:
Upvotes: 5