重绘 JPanel 在 JApplet 中不起作用



我有主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

您应该在此处重新绘制之前调用重新验证:

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

每次自定义组件重绘时,您都会加载图像。最好将图像加载移动到构造函数中并只加载一次。

最新更新