Automatic Image Resizing on a JLabel
When displaying an image on a JPanel using a JLabel, it's often desired to automatically adjust the image's size to fit the label's dimensions. By default, the JLabel will maintain the original image's aspect ratio and scale it to fit within the label's available space.
To achieve automatic image resizing, one approach is to utilize a custom component that extends JPanel and handles the scaled image rendering. This allows for more control over the scaling behavior, such as specifying whether to fit or fill the image within the label.
Resizing Options
There are two main resizing options available for images on a JLabel:
Custom Component for Resizable Images
The following code showcases a custom component, ScalablePane, that manages image scaling based on the fit/fill option:
public class ScalablePane extends JPanel { // ... (code omitted for brevity) @Override protected void paintComponent(Graphics g) { // Draw the scaled image super.paintComponent(g); if (scaled != null) { g.drawImage(scaled, x, y, this); } else if (master != null) { g.drawImage(master, x, y, this); } } // ... (code omitted for brevity) }
Example Usage
To use the ScalablePane component, you can instantiate it and set the desired image:
ScalablePane scalablePane = new ScalablePane(image); // Set the fit/fill option scalablePane.setToFit(true); // Fit image within the component // Add the component to your JPanel yourJPanel.add(scalablePane);
The above is the detailed content of How to Automatically Resize Images within a JLabel?. For more information, please follow other related articles on the PHP Chinese website!