I am trying to display two different images on my screen. one of which is a banner that goes at the top of my JFrame
, and another that I just placed randomly below the banner for testing purposes. The issue I am having is that while I can display a single image on the screen by adding an object of class WindowStructure
to my window, I am not able to display more than one image at a time. Only the last image added to the window is displayed on the screen:
Here is the window class:
import javax.swing.JFrame;
public class Window extends JFrame {
public Window(String name) {
super(name);
setSize(1200, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
WindowStructure banner = new WindowStructure("Beatles Logo.jpg", 0, 0, getWidth(), 75);
WindowStructure fireball = new WindowStructure("fireball.png", 100, 100, 100, 100);
add(banner); //banner
add(fireball);
setVisible(true);
while(true){
repaint();
}
}
public void paint(Graphics g
) {
super.paintComponents(g);
}
}
Here's the actual class that creates the image:
public class WindowStructure extends JPanel {
ImageIcon imageIcon;
int xLoc, yLoc, xSize, ySize;
public WindowStructure(String bannerImg, int xLoc, int yLoc, int xSize, int ySize){
URL bannerImgURL = getClass().getResource(bannerImg);
imageIcon = new ImageIcon(bannerImgURL);
this.xLoc = xLoc;
this.yLoc = yLoc;
this.xSize = xSize;
this.ySize = ySize;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(imageIcon.getImage(), xLoc, yLoc, xSize, ySize, null);
}
}
The JFrame javadocs state that the default layout manager used is BorderLayout. To add multiple components, you have to specify a different place in the layout to put each one (
NORTH
,SOUTH
,EAST
,WEST
,CENTER
). By default it'sBorderLayout.CENTER
if not specified, which is why you only see the last one added.The default layout manager for JFrame is BorderLayout. As the documentation says: "BorderLayout interprets the absence of a string specification the same as the constant CENTER". For instance:
You can fix this if you specify the location as a second argument to add():
Or you can use another layout manager for the JFrame by invoking setLayout(LayoutManager) in your Window class constructor.
Guide about layout managers: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html