0
讓我問你一個問題。我有一個包含不同大小圖片的文件夾,我隨機讀取一張圖片,縮小它的大小並在jpanel上使用JLabel進行推演 - 這很簡單。事實上,一幅畫的撤回可以顯示在正確的座標上,另一幅可以反彈在米上。爲什麼會發生?隨機照片忽略SetBounds和其他容器的邊界。輸出到屏幕時圖像的位置不正確
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);
}
1)爲了更好地幫助越早,張貼[MCVE]或[簡要,獨立的,正確的示例](http://www.sscce.org/)。 2)獲取圖像的一種方法是通過[本問答](http://stackoverflow.com/q/19209650/418556)中的圖像進行熱鏈接。 –
請勿使用空佈局。 Swing旨在與佈局經理一起使用。 – camickr