我有主 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);
}
每次自定义组件重绘时,您都会加载图像。最好将图像加载移至构造函数中并仅加载一次。
关于java - 重绘 JPanel 在 JApplet 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10119069/