重绘JPanel在JApplet中不起作用

时间:2012-04-12 07:13:45

标签: java swing applet jpanel

我有主要的JPanel(在JApplet中),它包含了孩子JPanel和按钮。我想点击按钮,删除子JPanel,另一个子JPanel添加到主JPanel,但问题是只有当我重新点击按钮或调整JApplet的大小时,第二个孩子JPanel才会显示。

我的按钮的听众:

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

1 个答案:

答案 0 :(得分:4)

您应该在重新绘制之前调用revalidate:

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

重新验证调用更新容器层次结构,之后可能需要重新绘制。容器调整大小同时执行(重新验证和重新绘制),这就是为什么在调整小程序大小后面板出现的原因。

此外,我注意到你的代码中有一件坏事:

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

您正在加载自定义组件重新绘制的图像每个时间。最好将图像加载移动到构造函数中并加载一次。