简体   繁体   中英

Refreshing my JFrame

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM