Repaint()不起作用

时间:2015-01-10 11:12:01

标签: java swing jpanel

当我尝试调用它时,以某种方式重绘不起作用。它没有给出错误,看起来它只是忽略了整个函数。

这是我的代码:

public class Neerslag extends JComponent {
JPanel painting = new JPanel();
private int j = 0;

  Neerslag() {
    setPreferredSize(new Dimension(370, 200));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.setColor(Color.GRAY);

    g.fillOval(j, 20, 100, 20);
    g.fillOval(j + 10, 30, 100, 20);
    System.out.println("test2");

  }

  public void move(int j) {
    System.out.println("test");
    if (j < 50) {
        j++;
    } else {
        j = -j;
    }
    /*try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        System.err.println("sleep exception");
    }*/
    this.repaint();
  }

  public JPanel showPaint() {
    painting.add(new Neerslag());
    return painting;
  }

  public void Clear() {
    painting.repaint();
    System.out.println("hello");
  }
}

public class NeerslagFrame extends JFrame implements MouseListener {
NeerslagPanel panel1 = new NeerslagPanel();;
private int i=0;
Neerslag neerslag = new Neerslag();

public static void main(String[] args) {
    NeerslagFrame textFieldFrame = new NeerslagFrame();
    textFieldFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textFieldFrame.setSize(500, 350);
    textFieldFrame.setVisible(true);

}

public NeerslagFrame(){
    super ("Neerslag");
    //panel1 = 
    this.addMouseListener(this);
    this.add(panel1.addSideBar(), BorderLayout.EAST);
    this.add(panel1.addSouthBar(), BorderLayout.SOUTH);
    this.add(neerslag.showPaint());
}
public void Clear(){
    //Neerslag paint = new Neerslag();
    this.add(new Neerslag());
}

@Override
public void mouseClicked(MouseEvent arg0) {
    neerslag.move(i);
    i++;
    neerslag.repaint();
    neerslag.revalidate();
    //this.add(neerslag.showPaint());
}
@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}


}

我错过了什么?它确实显示了最初的两个椭圆,但是一旦我改变了“j”值,就不会重新绘制它们。 提前谢谢!

1 个答案:

答案 0 :(得分:1)

repaint并不是您想要的,您所看到的&#34;&#34;想要的是revalidaterepaint

像...一样的东西。

@Override
public void mouseClicked(MouseEvent arg0) {
    neerslag.move(i);
    i++;
    neerslag.revalidate();
    neerslag.repaint();
    this.add(neerslag.showPaint());
}

例如。

现在,对于它的价值,你的设计似乎是倒退的,也就是说,而不是让Neerslag容器有一些其他容器似乎然后向它添加自己的实例,而不是{{1}应该只关心自己,而不是别的。

您应该移出Neerslag面板并单独管理,因为painting根本不应该关心它 - 恕我直言