1

My java code below uses a panel to display a button and image. The problem is the image is not scaling to fit in the screen. Meaning the image in full is not being display only a part of the image is being displayed. I am pretty sure you have to use paintComponent to do this.

Pic

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*; 

public class frame {  
    JFrame f;  

    frame() throws IOException{  
        f = new JFrame();  
        JButton b1 = new JButton("NORTH");;  
        JLabel b2 = new JLabel("SOUTH");;  
        ImageIcon img = new ImageIcon("a.png");
        b2 = new JLabel("", img, JLabel.CENTER);
        f.add(b1,BorderLayout.NORTH);  
        f.add(b2,BorderLayout.CENTER);  
        f.setSize(300,300);  
        f.setVisible(true);  
    } 

    public static void main(String[] args) throws IOException {  
        new frame();  
    } 

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
    }
}  
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    The code seen above does not compile, so cannot be an example of a run-time problem. Add `@Override` notation to methods you think are being overridden. It would be another hint that the logic is incorrect. **General Tips:** 1) For better help sooner, [edit] to add 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). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) hot links to an image .. – Andrew Thompson Apr 19 '20 at 04:31
  • 1
    .. embedded in [this question](https://stackoverflow.com/q/10861852/418556). 3) Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) and use it consistently. Also use meaningful & descriptive names for classes, not something like `frame` but more like `BackgroundImageFrame`. 4) `throws IOException` No it doesn't. `new ImageIcon("a.png");` fails silently, without throwing an error or exception. – Andrew Thompson Apr 19 '20 at 04:31

0 Answers0