Refreshing picture in drawingPanel extends JPanel

浪尽此生 提交于 2019-12-02 07:23:55

First thing don't start class name with small name. Rename drawingPanel to DrawingPanel.

I have tried making a simple demo based on your description and it works fine. The image in panel is changing perfectly.

public class Demo {

    public Demo() {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        // Grab the image.
        Image img = new ImageIcon("1.png").getImage();
        // Create an instance of DrawingPanel
        final DrawingPanel iconPanel = new DrawingPanel(img);

        frame.add(iconPanel, BorderLayout.CENTER);

        JButton button = new JButton("Change image..");
        frame.add(button, BorderLayout.NORTH);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                iconPanel.setImg(new ImageIcon("2.png").getImage());
                iconPanel.repaint();
            }
        });

        frame.setVisible(true);
    }

    public static void main(String[] args){
        new Demo();
    }
}

class DrawingPanel extends JPanel {
    Image img;

    DrawingPanel(Image img) {
        this.img = img;
    }

    public void setImg(Image img) {
        this.img = img;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Use the image width & height to find the starting point
        int imgX = getSize().width / 2 - img.getWidth(this);
        int imgY = getSize().height / 2 - img.getHeight(this);

        // Draw image centered in the middle of the panel
        g.drawImage(img, imgX, imgY, this);
    } // paintComponent

}

The changes I have made is add a setter method of img in DrawingPanel class. So instead of creating new DrawingPanel you just have to call setImg() with new Image and then call reapint to paint the new image.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!