我有包含子 JPanel 和按钮的主 JPanel(在 JApplet 中)。我想单击按钮使子 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