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 form. No picture(or any other operation in paintComponent) shows up. Is there something I'm missing?

Answers


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);
}

Need Your Help

use common template for all pages of website

php html architecture templates

ok, the title did not make much sense but this is what i am planning to do. I have designed a template for my website, with head body and div for specific stuff and everything. The website consist...

Backup and restore SQL Server Management Studio job schedule

sql sql-server stored-procedures sql-job

I've got a job in SQL Server Management Studio and I want to back up the schedule that it runs on so that the schedule can be applied to other jobs that I add. I know that I can get what I assume i...