Non-Working paintComponent method
Code :
import javax.swing.*;
import java.awt.*;
public class firstGUI extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
Image image = new ImageIcon("dist.jpg").getImage();
g.drawImage(image,0,0, this);
}
}
Compiles perfectly, but when I run it, it just shows a fo开发者_如何学编程rm. No picture(or any other operation in paintComponent
) shows up. Is there something I'm missing?
Your paintComponent
method is an instance method of your firstGUI
class (a JPanel
). The problem is that you are not creating an instance of firstGUI
and adding it to the frame.
The following replacement main
method instantiates firstGUI
and adds it to the contentPane
of the frame:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.getContentPane().add(new firstGUI());
frame.setVisible(true);
}
精彩评论