Sunday, 25 August 2013

Image does not appear in JPanel using BufferedImage

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);
}

No comments:

Post a Comment