Java GUI problem in paintComponent?
Hi everyone. I can't seem to get my java code to work. I suspect it's a problem with the way I've coded my paintComponent methods, but for the life of me I can't figure out where the problem is.
Instead of drawing a pretty picture on screen, all I get is a vast expanse of nothing. Any/all input would be greatly appreciated :) Oh, and yes - the image file is definitely in the correct directory.
Code :
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrontEnd extends JFrame {
public FrontEnd() {
Image miniIcon = new ImageIcon("icon.gif").getImage();
this.setIconImage(miniIcon);
MainScreen mainScr = new MainScreen();
add(mainScr);
mainScr.repaint();
}
public static void main(String args[]) {
FrontEnd window = new FrontEnd();
window.setTitle("Blah");
window.setSize(400, 400);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
//#####################################################################################################
class MainScreen extends JPanel {
public MainScreen() {
JPanel p = new JPanel(new GridLayout(1, 1, 0, 0));
System.out.println("Container panel created");
Image image = new ImageIcon("icon.gif").getImage();
ImageViewer viewPanel = new ImageViewer(image);
add(viewPanel);
viewPanel.repaint();
}
protected void paintComponent(Graphics g) {
ImageViewer.repaint();
System.out.println("The main screen is redrawn");
}
}
//#####################################################################################################
class ImageViewer extends JPanel {
private java.awt.Image image;
public ImageViewer(Image image) {
this.image = image;
System.out.println("ImageViewer constructor called");
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
System.out.println("ImageViewer paintComponent called");
}
}
Re: Java GUI problem - paintComponent?
Hello Richard,
When I attempt to compile this in Eclipse, I straight away get an error here in the MainScreen class:
Code :
protected void paintComponent(Graphics g) {
[B]ImageViewer.repaint();
[/B] System.out.println("The main screen is redrawn");
}
"Cannot make a static reference to a non static method repaint() from the type Component"
I'm looking into how to fix this..
Re: Java GUI problem - paintComponent?
ImageViewer.repaint();
What is it you hope to redraw when you call this? Becuase as far as I am aware, that is COMPLETELY Illegal. The only way to call repaint is on an instance not class, ie as a static function.
repaint is definded as
public void repaint();
not,
public static void repaint();
thus it cannot be called in a static manner.
This is confusing to explain lol. One last try,
You cannot call a non-static function on a class, you must call it on an instance of a class.
Regards,
Chris