java只显示frame,Java只能在JFrame上显示1个图像

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 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:

add(banner); // Same as p.add(banner, BorderLayout.CENTER);

add(fireball); // Same as p.add(fireball, BorderLayout.CENTER);

You can fix this if you specify the location as a second argument to add():

add(banner, BorderLayout.NORTH);

add(fireball, BorderLayout.CENTER);

Or you can use another layout manager for the JFrame by invoking setLayout(LayoutManager) in your Window class constructor.

public class Window extends JFrame {

public Window(String name) {

super(name);

setLayout(new FlowLayout()); // or another the layout that best fit your needs...

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值