class ImageComponent extends JComponent
implements MouseListener, MouseMotionListener {
private final BufferedImage img;
private Point p1, p2;
public ImageComponent(File file) throws IOException {
img = ImageIO.read(file);
setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
addMouseListener(this);
addMouseMotionListener(this);
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
if (p1 != null && p2 != null)
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
@Override public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
}
@Override public void mouseDragged(MouseEvent e) {
mouseReleased(e);
}
@Override public void mouseReleased(MouseEvent e) {
p2 = e.getPoint();
repaint();
}
@Override public void mouseMoved(MouseEvent e) {}
@Override public void mouseClicked(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
public static void main(String[] args) throws Exception {
JFileChooser chooser=new JFileChooser();
chooser.setCurrentDirectory(new File(" "));
chooser.showOpenDialog(new JFrame());
File file=chooser.getSelectedFile();
final ImageComponent image = new ImageComponent(file);
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(image));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
Here in this code, it takes a file using JFileChooser
directly.
Now i want to add a button on which when i click, it should generates an ActionEvent
and should open a JFileChooser
from which i can choose a file and then it should show me that image on frame. How can i do that?
I Have created something like that
JButton open_button=new JButton("Add File");
open_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.showOpenDialog(new JFrame());
File file = chooser.getSelectedFile();
ImageComponent image=new ImageComponent(file);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "IOException Occured");
}
}
But it isn't working..