重绘的JPanel不JApplet的工作(Repaint JPanel doesn't wo

2019-09-16 12:29发布

我有主的JPanel(在JApplet的),它containts孩子的JPanel和按钮。 我想点击该按钮使孩子的JPanel移除,另一个孩子的JPanel添加到主JPanel的,但问题是,只有当我reclick按钮或调整JApplet的大小的第二个孩子的JPanel然后apprear。

我的按钮的监听器:

button.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            panel.remove(custompanel);
            panel.add(new CustomPanel("/hinhtu2.jpg"), BorderLayout.CENTER);
            panel.repaint();
            panel.revalidate();

        }
        });

我的整个代码:

 import java.awt.BorderLayout;
 import java.awt.Color;
 import java.awt.Graphics;
 import java.awt.Image;
 import java.awt.Toolkit;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.io.File;
 import java.io.IOException;

 import javax.imageio.ImageIO;
 import javax.swing.BorderFactory;
 import javax.swing.ImageIcon;
 import javax.swing.JApplet;
 import javax.swing.JButton;
 import javax.swing.JLabel;
 import javax.swing.JPanel;

 public class applet extends JApplet {
   public void init() {

    try {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createGUI();
            }
        });
    } catch (Exception e) {
        //System.err.println("createGUI didn't successfully complete");
        e.printStackTrace();
    }
}

 private void createGUI() {
    final JPanel panel = new JPanel(new BorderLayout());
    JButton button = new JButton("CLICK ME");
    panel.add(button, BorderLayout.SOUTH);
    final CustomPanel custompanel = new CustomPanel("/hinhtu.jpg");
    panel.add(custompanel, BorderLayout.CENTER);

    button.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            panel.remove(custompanel);
            panel.add(new CustomPanel("/hinhtu2.jpg"), BorderLayout.CENTER);
            panel.repaint();
            panel.revalidate();

        }

        });

    add(panel);
    }

public class CustomPanel extends JPanel{
    String resource;
    public CustomPanel(String resource){
        super();
        this.resource = resource;



    }
    public void paintComponent(Graphics g) {



        Image x = Toolkit.getDefaultToolkit().getImage(getClass().getResource(resource));
        g.drawImage(x, 0, 0, null); 

    }   



}

}

我的屏幕记录: http://www.screenr.com/prx8

Answer 1:

你应该调用revalidate再这里之前重绘:

        panel.remove(custompanel);
        panel.add(new CustomPanel("/hinhtu2.jpg"), BorderLayout.CENTER);
        panel.repaint();
        panel.revalidate();

重新验证调用更新容器层次结构以及可能需要重绘后。 容器大小调整既不会(重新验证并重新绘制),这就是为什么在面板出现你调整后的小程序。

此外,我注意到,在上你的代码1个坏事:

public void paintComponent(Graphics g) {
    Image x = Toolkit.getDefaultToolkit().getImage(getClass().getResource(resource));
    g.drawImage(x, 0, 0, null); 
}   

一次你的自定义组件进行重新绘制您加载图像。 更好的移动图像加载到构造器并加载它只有一次。



文章来源: Repaint JPanel doesn't work in JApplet