0

let me ask you a question. I have a folder with pictures in different sizes, from that I read a picture randomly, reduce its size and deduce using a JLabel on a jpanel - it's simple. The fact that the withdrawal of one picture can be displayed at the right coordinates, and the other can bounce on the meter.Why does it happen? Random pictured ignore SetBounds and bounds of other containers.

    private void initialize() throws IOException {
    frame = new JFrame();
    frame.setBounds(100, 100, 1150, 664);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    panel = new JPanel ();
    panel.setBounds(10, 10, 1150, 664);
    frame.getContentPane().add(panel);

    File f = new File ("C:/Users/user/Desktop/Ramms");
    String[] names = f.list();
    all_Images= new ImageIcon[names.length];
    for(int i=0; i<names.length; i++){
        all_Images[i]= new ImageIcon ("C:/Users/user/Desktop/Ramms/"+names[i]);
    }
    selected_Image = all_Images[random(0,all_Images.length)];
    w= selected_Image.getIconWidth()/scl;
    h= selected_Image.getIconHeight()/scl;
    Image img = selected_Image.getImage(); 
    bic = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 
    Graphics g = bic.createGraphics(); 
    g.drawImage(img, 0, 0, w, h, null); 
    newIcon = new ImageIcon(bic); 
    panel.setLayout(null);

    JLabel label1 = new JLabel(newIcon);
    panel.add(label1).setBounds(0,100,w,h);         
}
  • 2
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Jun 17 '17 at 15:51
  • 1
    Don't use a null layout. Swing was designed to be used with layout managers. – camickr Jun 17 '17 at 16:13

1 Answers1

2

reduce its size

Doesn't look like you are reducing its size to me:

bic = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 
Graphics g = bic.createGraphics(); 
g.drawImage(img, 0, 0, w, h, null); 
newIcon = new ImageIcon(bic); 

The size of the Icon is the size of the created BufferedImage.

It doesn't know or care what you draw on the BufferedImage.

A couple of solutions:

  1. When you create the BufferedImage you need to create the image at its scaled size.

  2. Use the Image.getScaledInstance(...) method to resize the image.

camickr
  • 321,443
  • 19
  • 166
  • 288