import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; public class MyPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.fillRect(50, 50, 100, 100); } }
import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JPanel; public class MyPanel extends JPanel { private Image img; public MyPanel() { img = new ImageIcon("image.jpg").getImage(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img, 0, 0, null); } }In this example, a subclass of JPanel is created with an image loaded from a file in the constructor. The paintComponent() method is overridden to draw the image at (0,0) with its original size. The package library used in these examples is javax.swing.