我试图在我的主要方法中添加一个JLabel与鸡的形象。当我将标签添加到框架时,没有任何显示。我还需要将鸡放在带坐标的框架上。这是我的代码:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.Container;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TEST extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
TEST(){
add(new ContentPanel());
setSize(1440, 500);
}
public static void main(String[] args) {
TEST jrframe = new TEST();
jrframe.setVisible(true);
JLabel chicken = new JLabel(" ");
ImageIcon chick = new ImageIcon("chicken.gif");
chicken.setIcon(chick);
JPanel p1 = new JPanel();
p1.add(chicken);
jrframe.add(p1);
p1.setLocation(0, 0);
}
}
class ContentPanel extends JPanel{
Image bgimage = null;
ContentPanel() {
MediaTracker mt = new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage("level0.gif");
mt.addImage(bgimage, 0);
try {
mt.waitForAll();
} catch (InterruptedException e){
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bgimage, 1, 1, null);
}
}
答案 0 :(得分:0)
您正在向已经可见的帧添加组件。执行此操作时,您需要通知LayoutManager这是正在发生的,或者更好的是在添加组件后移动调用setVisible(true)
。