我正在尝试在屏幕上显示两个不同的图像。其中一个是位于我的 JFrame
顶部的横幅,另一个是我出于测试目的随机放置在横幅下方的。我遇到的问题是,虽然我可以通过将 WindowStructure 类的对象添加到窗口来在屏幕上显示单个图像,但我无法一次显示多个图像。屏幕上仅显示最后添加到窗口的图像:
这是窗口类:
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);
}
}
这是创建图像的实际类:
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);
}
}
最佳答案
JFrame 的默认布局管理器是 BorderLayout 。 正如文档所述:“BorderLayout 将字符串规范的缺失解释为与常量 CENTER 相同”。例如:
add(banner); // Same as p.add(banner, BorderLayout.CENTER);
add(fireball); // Same as p.add(fireball, BorderLayout.CENTER);
如果将位置指定为 add() 的第二个参数,则可以解决此问题:
add(banner, BorderLayout.NORTH);
add(fireball, BorderLayout.CENTER);
或者您可以通过在 Window 类构造函数中调用 setLayout(LayoutManager) 来为 JFrame 使用另一个布局管理器。
public class Window extends JFrame {
public Window(String name) {
super(name);
setLayout(new FlowLayout()); // or another the layout that best fit your needs...
...
布局管理器指南:http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
关于Java只能在JFrame上显示1张图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972496/