【发布时间】:2014-02-10 04:48:36
【问题描述】:
我遇到了这个问题。我想从 JPanel 中删除所有现有组件,并在单击按钮后添加另一个新组件。现在,如果我点击一个按钮,它会在左上角添加相同的按钮,但不再有任何可点击的按钮了。
public class MainPanel extends JPanel implements ActionListener{
private Image backgroundImage;
private Image startScreen;
private boolean gameStarted = false;
private SingleplayerButton button1;
private MultiplayerButton button2;
public MainPanel() {
String imgUrl = "graphics/";
try {
startScreen = ImageIO.read(new File(imgUrl+"start.png"));
} catch (IOException e) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, e);
}
backgroundImage = startScreen;
this.setLayout(null);
button1 = new SingleplayerButton(this);
button1.addActionListener(this);
this.add(button1);
button2 = new MultiplayerButton(this);
button2.addActionListener(this);
this.add(button2);
}
@Override
protected void paintComponent(Graphics g) {
if(gameStarted == false) {
g.drawImage(backgroundImage, 0, 0, null);
} else {
this.removeAll();
this.setBackground(Color.WHITE);
this.revalidate();
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
gameStarted = true;
this.repaint();
// something more
} else if(e.getSource() == button2) {
gameStarted = true;
this.repaint();
// something more
}
}
【问题讨论】:
-
您能发布一个实际的 SSCCE 吗?这段代码甚至无法编译。
-
也许内容没有消失是因为你没有调用 super.paintComponent(g);在paintComponent 方法的顶部。如果您不需要图形,我同意下面的答案,请不要在 paintComponent 方法中删除、重新验证和重新绘制。在侦听器中执行此操作
-
@FelipeO.Thomé,paintComponent() 方法不负责绘制面板的子项。 paint() 方法绘制孩子。请参阅A Closer Look at the Painting Mechanism 了解更多信息。
-
@camickr 我们不需要调用 super paintComponent 来擦除面板上绘制的任何内容吗?
-
问题出在背景上...它不会消失 :-/ 所以我决定为下一个屏幕创建另一个背景图像并交换背景图像...现在可以了。为什么 setBackground(Color.WHITE);没有功能? :-/
标签: java swing components repaint