import javax.swing.*; import java.awt.*; public class MyPanel extends JPanel { @Override public void paint(Graphics g) { super.paint(g); g.setColor(Color.RED); g.drawRect(50, 50, 100, 100); } public static void main(String[] args) { JFrame frame = new JFrame("JPanel Example"); MyPanel panel = new MyPanel(); frame.add(panel); frame.setSize(300, 300); frame.setVisible(true); } }
import javax.swing.*; import java.awt.*; public class MyFrame extends JFrame { public void paint(Graphics g) { super.paint(g); ImageIcon imgIcon = new ImageIcon(getClass().getResource("image.jpg")); Image img = imgIcon.getImage(); g.drawImage(img, 50, 50, this); } public static void main(String[] args) { MyFrame frame = new MyFrame(); frame.setSize(400, 400); frame.setVisible(true); } }This example demonstrates how to draw an image on a JFrame using the paint method. The paint method is overridden to call the super class paint method, load an image from the resource folder and then draw it on the frame using drawImage() method. The package library for both the examples is javax.swing.