Java只能在JFrame上显示1个图像 [英] Java can only display 1 image on JFrame
问题描述
我想在屏幕上显示两个不同的图像。其中一个横幅位于我的 JFrame
的顶部,另一个横幅放在横幅下面以进行测试。我遇到的问题是,虽然我可以通过在窗口中添加类 WindowStructure
的对象来在屏幕上显示单个图像,但我无法显示多个一次成像。屏幕上只显示添加到窗口的最后一个图像:
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:
这是窗口类:
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);
}
}
推荐答案
JFrame的默认布局管理器是 BorderLayout 。
正如文档所说:BorderLayout解释缺少字符串规范与常量CENTER相同。例如:
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);
如果您将位置指定为add()的第二个参数,则可以解决此问题:
You can fix this if you specify the location as a second argument to add():
add(banner, BorderLayout.NORTH);
add(fireball, BorderLayout.CENTER);
或者你可以通过在Window类构造函数中调用setLayout(LayoutManager)来为JFrame使用另一个布局管理器。
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...
...
布局管理员指南: http://docs.oracle.com/javase/ tutorial / uiswing / layout / visual.html
这篇关于Java只能在JFrame上显示1个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!