2014年4月16日 星期三

Swing:元件:JLabel、ImageIcon

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


class Frame4 extends JFrame {
 private JPanel contentPane;
 String [] imgName = new String[]{"banana","strawberry","watermelon"};
 JLabel[] lbl = new JLabel[imgName.length];
 JLabel[] lblImg = new JLabel[imgName.length];
 Frame4(){
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100,100,700,300);
  
  contentPane = new JPanel();
  setContentPane(contentPane);
  contentPane.setLayout(null);
  
  for (int i=0; i < imgName.length;i++){
   lblImg[i] = new JLabel();
   lblImg[i].setIcon(new ImageIcon("./src/"+imgName[i]+".jpeg"));
   //lblImg[i].setIcon(new ImageIcon("/Users/elvismeng/Documents/java_workspace/Swing/src/"+imgName[i]+".jpeg"));
   lblImg[i].setBounds(i * 200 + 20, 30, 180,135);
   contentPane.add(lblImg[i]);
   lbl[i] = new JLabel(imgName[i]);
   lbl[i].setBounds(i*200 + 100, 180, 100,20);
   contentPane.add(lbl[i]);
  }
  setVisible(true);
  
 }
}

public class FrameImageIcon {

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

執行結果

沒有留言:

張貼留言