【问题标题】:cannot remove components and repaint无法移除组件并重新绘制
【发布时间】: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


【解决方案1】:

在可见的 GUI 中添加/删除组件时的基本代码是:

panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();

上面的代码应该在 ActionListener 中完成,而不是在 paintComponent() 方法中。绘画方法仅供绘画。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多