Re: Display jpg in JPanel problem
On 6/27/2010 2:08 AM, jimmy wrote:
Thanks all for your help again. I didn't include the complete code for
my GUI as it was built using NetBeans and contains lots of other
buttons and panels, which were not relevant to the problem. I was
unaware of the SSCCE method of describing a problem, and I find it a
very good method. I did write an SSCCE example showing my problem, but
I fear that, as pointed out by Knute Johnson, the problems with my
code run deeper than the problem I described. I haven't fully grasped
how to work with images, therefore I am going to buy a book on Java
today (Head First Java seems to receive high praise) and spend some
time getting to grips with the basics.
Thanks Daniel Pitts for the JLabel suggestion, however I need to be
able to manipulate the images, which I believe is beyond the scope of
JLabel.
In the meantime I need to create a GUI for image analysis, so I have
started one in MATLAB (which I am much more familiar with than Java).
My intention is to create the final version in Java however.
Cheers,
Jimmy
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class test extends JPanel {
private BufferedImage image;
public void setImage(BufferedImage bi) {
image = bi;
if (image != null) {
setPreferredSize(new Dimension(
bi.getWidth(),bi.getHeight()));
revalidate();
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null)
g.drawImage(image,0,0,null);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final test t = new test();
JScrollPane sp = new JScrollPane(t);
f.add(sp,BorderLayout.CENTER);
JButton b = new JButton("Load Image");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(f) ==
JFileChooser.APPROVE_OPTION) {
try {
File file = chooser.getSelectedFile();
if (file.exists())
t.setImage(ImageIO.read(file));
} catch (IOException ioe) {
JOptionPane.showMessageDialog(f,ioe);
}
}
}
});
f.add(b,BorderLayout.SOUTH);
f.setSize(400,300);
f.setVisible(true);
}
});
}
}
--
Knute Johnson
email s/nospam/knute2010/