2015年2月19日 星期四

[Java] resize image + imagebutton

  1.  // resize image + make imagebutton

  2.  JPanel panel = new JPanel();
  3.              panel.setLayout(null); // set 了layout是null後必需調用setBounds
  4.              panel.setBounds(0, 0, 200 , 200); // 參數1: x座標; 2:y座標; 3:width; 4:height

  5.              
  6.      ImageIcon img = new ImageIcon(getClass().getResource("/lam/images/1.jpg"));
  7.  
  8.               // resize img width and height to 100,100

  9.               Image image = img.getImage();
  10.               Image newimg = image.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
  11.               img = new ImageIcon(newimg);
  12.  
  13.                // add image to button
  14.                              
  15.               JButton btn = new JButton();
  16.               btn.setBorder(LineBorder.createGrayLineBorder());
  17.               btn.setIcon(img);  
  18.               btn.setBounds(0, 0, 150, 120);

  19.       panel.add(btn);



沒有留言:

張貼留言