Hien Tran
Hien Tran

Reputation: 1493

Image does not appear in JPanel using BufferedImage

I have a GUI with a created JPanel and a "Start" button. All I need is when I click "Start", an image will be loaded and appear on that JPanel. But my problem is when I click "Start", nothing happens. Can anyone help me fix this problem? Here is my code:

private BufferedImage image;
public class ImagePanel extends JPanel {
    public ImagePanel() {
        try {
            image = ImageIO.read(new File("C:\\Users\\HienTran\\Desktop\\Miranda-Kerr-16-240x320.jpg"));
        } catch (IOException ex) {
        // handle exception...
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
    stopBtn.setEnabled(true);
    startBtn.setEnabled(false);
    imageArea.add(new ImagePanel());    // imageArea is the JPanel in the GUI
}

When I replace 2 lines of imageArea by creating a new JFrame as below, that JFrame shows up with the image I added.

private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
    stopBtn.setEnabled(true);
    startBtn.setEnabled(false);
    JFrame test = new JFrame("Window"); 
    test.add(new ImagePanel()); 
    test.setSize(image.getWidth(), image.getHeight() + 30); 
    test.setVisible(true);
}

Upvotes: 2

Views: 2106

Answers (2)

camickr
camickr

Reputation: 324197

When you add components to a visible GUI the basic code is:

panel.add(...);
panel.revalidate();
panel.repaint();

However, that probably won't help because by default a JPanel uses a FlowLayout and a FlowLayout respects the size of the component. Your ImagePanel will have a size of (0, 0) since you did not override the getPreferredSize() method.

There is no need to create a custom panel to paint your image. Just use a JLabel with an Icon then you let the label worry about the size. Don't reinvent the wheel.

I suggest you read the Swing tutorial for the basics. Maybe the section on How to Use Labels would be a good place to start. The tutorial will also show you a better way to design your class wo that you follow Swing guidelines.

Upvotes: 5

user529543
user529543

Reputation:

First fix a bit:

    try {
        image = ImageIO.read(new File("C:\\Users\\HienTran\\Desktop\\Miranda-Kerr-16-240x320.jpg"));
    } catch (IOException ex) {
        ex.printStacktrace(); // see if there is an exception, like not finding or something
    }

than: If you add a panel, than need a layout refresh and a gui refresh:

imageArea.add(new ImagePanel()); 
imageArea.revalidate(); // refresh layout
imageArea.repaint(); // shedule painting

Upvotes: 2

Related Questions