0

I want to display an image on a application and when I want to open another one, I want that the new one overwrite the old.

I've looking everywhere to find a solution like use invalidate(), repaint(), etc.. but still not working and I can't figured out why the windows doesn't refresh, can someone help me?

Here the code :

public void actionPerformed(ActionEvent e) 
{
    System.out.println(e.getActionCommand());
    if (e.getActionCommand().contains("Open"))
    {
        filename_ = new String();
        filename_ = JOptionPane.showInputDialog("File to open ?");
        ImagePanel test = new ImagePanel(new File(filename_));

        test.setPreferredSize(new Dimension(test.getWidth(), test.getHeight()));
        test.setMinimumSize(new Dimension(test.getWidth(), test.getHeight()));
        test.repaint();
        JScrollPane tmp = new JScrollPane();
        tmp.getViewport().add(test);

        tmp.getViewport().repaint();
        mainPanel_.add(tmp, BorderLayout.NORTH);
        mainPanel_.repaint();
        curim_ = test;
        test.memento_ = new Memento(test);
        test.caretaker_.add(test.memento_);
        curim_ = test;


        curmodindex_ = curim_.caretaker_.getIndex();
        this.setContentPane(mainPanel_);
        System.out.println(curmodindex_);
        if (curmodindex_ != 0)
        {
            button1.setEnabled(true);
            button2.setEnabled(true);
        }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Lenjyco
  • 41
  • 1
  • 1
  • 7

1 Answers1

2

Don't create new components. Just update the data of existing components. Maybe something like:

scrollPane.setViewportView( imagePanel );

Or even easier just use a JLabel to display your image. Then when the image changes you can use:

label.setIcon( new ImageIcon(...) );

Without a proper SSCCE its hard to guess what you are doing wrong. For example I see:

tmp.getViewport().add(test);
...
test.memento_ = new Memento(test);

Without knowing what your code does it looks like you are trying to add the same component to two different components which is not allowed.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • In fact, I have a ImagePanel class which extends JPanel, my image are in this JPanel, then I put my JPanel in a ScrollPanel to get scroll bars, then i put my ScollPanel in a MainPanel that is in my JFrame. – Lenjyco May 10 '13 at 16:28
  • 1
    I understand what you are doing. There is no need to create the custom panel for your image. You can just use a JLabel. – camickr May 10 '13 at 18:06