-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageScaler.java
More file actions
44 lines (39 loc) · 1.38 KB
/
Copy pathImageScaler.java
File metadata and controls
44 lines (39 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package Rent_Rover;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ImageScaler {
// ---------------------------
// For JLabel
public static void setScaledImage(JLabel label, String imagePath) {
ImageIcon icon = new ImageIcon(imagePath);
Image img = icon.getImage().getScaledInstance(
label.getWidth(),
label.getHeight(),
Image.SCALE_SMOOTH
);
label.setIcon(new ImageIcon(img));
}
// ---------------------------
// For JPanel as background
public static JPanel setPanelBackground(JPanel panel, String imagePath) {
ImageIcon icon = new ImageIcon(imagePath);
Image img = icon.getImage().getScaledInstance(
panel.getWidth(),
panel.getHeight(),
Image.SCALE_SMOOTH
);
// Create a JPanel with overridden paintComponent
JPanel bgPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
};
bgPanel.setLayout(panel.getLayout()); // preserve original layout
return bgPanel;
}
}