Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try something like this:</p> <pre><code>import java.awt.*; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; public class SG2B2 { JFrame frame; public static void main(String[] args) { SG2B2 gui = new SG2B2(); gui.createUI(); } public void createUI() { frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyDrawPanel drawPanel = new MyDrawPanel(); frame.getContentPane().add(BorderLayout.CENTER, drawPanel); frame.setSize(300, 400); frame.setVisible(true); } class MyDrawPanel extends JPanel { Image image; private final String pic = "Logo.jpg"; public MyDrawPanel() { image = new ImageIcon(pic).getImage(); image = scaleImage(image); } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.drawImage(image, 0, 0, this); } private Image scaleImage(Image rawImage) { Image scaledImage = null; System.out.println("Scaling"); try { int rawImageWidth = rawImage.getWidth(this); int rawImageHeight = rawImage.getHeight(this); int paneWidth = (int) getWidth(); int paneHeight = (int) getHeight(); System.out.println("Image W = " + rawImageWidth + ", H = " + rawImageHeight + "; Pane W = " + paneWidth + ", H = " + paneHeight); // preserve the original ratio float widthRatio = (float) rawImageWidth / (float) paneWidth; float heightRatio = (float) rawImageHeight / (float) paneHeight; int widthFactor = -1; int heightFactor = -1; if ((widthRatio &gt; heightRatio) &amp;&amp; (widthRatio &gt; 1.0)) { widthFactor = paneWidth; } else if ((heightRatio &gt; widthRatio) &amp;&amp; (heightRatio &gt; 1.0)) { heightFactor = paneHeight; } System.out.println("widthRatio = " + String.format("%.3f", widthRatio) + ", heightRatio = " + String.format("%.3f", heightRatio)); System.out.println("widthFactor = " + widthFactor + ", heightFactor = " + heightFactor); if ((widthFactor &lt; 0) &amp;&amp; (heightFactor &lt; 0)) { scaledImage = rawImage; } else { scaledImage = rawImage.getScaledInstance(widthFactor, heightFactor, Image.SCALE_SMOOTH); // load the new image, 'getScaledInstance' loads asynchronously MediaTracker tracker = new MediaTracker(this); tracker.addImage(scaledImage, 0); tracker.waitForID(0); } } catch (InterruptedException ie) { System.err.println("load interrupt: " + ie.getMessage()); } catch (Exception e) { e.printStackTrace(); } return (scaledImage); } } } </code></pre> <p>which will ultimately scale the image to the <code>JPanel</code>'s size by using <code>getScaledInstance(int width, int height, ImageObserver io)</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload