import java.awt.Graphics; import javax.swing.JFrame; public class MyFrame extends JFrame { public MyFrame() { setTitle("MyFrame"); setSize(250, 250); setVisible(true); } public void paint(Graphics g) { super.paint(g); g.drawRect(50, 50, 150, 100); } public static void main(String[] args) { new MyFrame(); } }
import java.awt.Graphics; import java.awt.Image; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JPanel; public class MyPanel extends JPanel { private Image img; public MyPanel() { try { File file = new File("image.jpg"); img = ImageIO.read(file); } catch(Exception e) { e.printStackTrace(); } } public void paint(Graphics g) { super.paint(g); g.drawImage(img, 0, 0, null); } }In this example, we create a JPanel and load an image from a file using the ImageIO class. We then override the paint method to draw the image on the panel using the g.drawImage method.