如何在JLabel上显示多个图像

时间:2014-01-08 16:39:05

标签: java swing jlabel

这是一个类项目,我需要显示多个图像,但它只打印出最后一个label.setIcon。我该怎么办?

 package Rectangle;
 import java.awt.*;  
 import javax.swing.*;

 public class Rectangle extends JFrame { 


 public Rectangle(String arg) { 

  JPanel panel = new JPanel(); 
    panel.setBackground(Color.BLACK); 
    ImageIcon icon = new ImageIcon(this.getClass().getResource("1676858-livingforest2011.jpg"));
    ImageIcon icon1 = new ImageIcon(this.getClass().getResource("20496aa0.gif"));
    ImageIcon icon2 = new ImageIcon(this.getClass().getResource("akuma-ragingdemon-yes.gif"));
    JLabel label = new JLabel(); 
    label.setIcon(icon2); 
    label.setIcon(icon1); 
    label.setIcon(icon);
    panel.add(label);
    this.getContentPane().add(panel); 

  }
      public static void main(String[] args) {
      Rectangle forestFrame = new Rectangle(args.length == 0 ? null : args[3]);
      forestFrame.setSize(1698,770);
      forestFrame.setVisible(true); 
      forestFrame.setVisible(true);

  }
}

1 个答案:

答案 0 :(得分:2)

这是因为JLabel只能容纳一个Image。要解决您的问题,您可以为每个图像创建一个带有3个标签的JPanel。检查下一个例子:

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Example extends JPanel {

    public Example() {
         ImageIcon icon = new ImageIcon(this.getClass().getResource(IMAGE1));
         ImageIcon icon1 = new ImageIcon(this.getClass().getResource(IMAGE2));
         ImageIcon icon2 = new ImageIcon(this.getClass().getResource(IMAGE3));
         JLabel label1 = new JLabel(icon); 
         JLabel label2 = new JLabel(icon1); 
         JLabel label3 = new JLabel(icon2); 

         add(label1);
         add(label2);
         add(label3);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.add(new Example());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

IMAGE(1,2,3) - 是你的照片。