I'm trying to design a GUI using SWING.My problem is that I'm not sure how the paintComponent method works. I'm trying to display 2 images but only the one from PanClass is displayed.Here is the relevant code(2 classes) .
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.awt.Image;
public class LP3 extends JPanel
{
public static BufferedImage image;
public static BufferedImage image2;
private JFrame frame=new JFrame();
private PanClass Panel=new PanClass();
public LP3()
{
try
{
image2=ImageIO.read(new File("New Game.png"));
}
catch (IOException e)
{
//Nothing
}
frame.setSize(1000,100);
frame.setResizable(true);
frame.add(Panel);
Panel.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
public void paintComponent(Graphics g)
{
g.drawImage(image2,0,0,null);
}
}
Class No2:
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.awt.Image;
public class PanClass extends JPanel
{
private static BufferedImage theimage;
private static BufferedImage image2;
private JPanel a=new JPanel();
public PanClass()
{
a.setLayout(null);
a.setOpaque(true);
try
{
theimage = ImageIO.read(new File(design4.jpg"));
}
catch (IOException e)
{
//Not handled.
}
}
public void paintComponent(Graphics g)
{
g.drawImage(theimage,0,0,null);
}
}
The code as it is now displays only the image from PanClass. If I get to add the drawing of both images to be done in the PanClass then both will be correctly drawn. I am interested in knowing why this happens as I'm more interested in learning how it works rather than getting the job done. Also If I create a JFrame and a JLayered Pane in a class, then create 2 more classes drawing an image with paintComponent() (using similar code to the above) and then add an instance of each class on the Layered Pane on a different Layer of the first class, why nothing is displayed?
(My main method is supposed to be on LP3 but I'm just using an IDE that allows you to call methods directly on instances without having a main method-used for learning)