gpt4 book ai didi

java - 重绘()不起作用

转载 作者:行者123 更新时间:2023-12-01 12:02:40 25 4
gpt4 key购买 nike

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

这是我的代码:

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”值,就不会重新绘制它们。预先感谢您!

最佳答案

repaint 并不是您真正想要的,您“似乎”想要的是 revalidaterepaint

类似...

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

例如。

现在,就其值(value)而言,您的设计似乎是倒退的,也就是说,不是让 Neerslag 容器出现在其他容器中,而是将其自身的实例添加到其中,而是 Neerslag 应该只关心它自己而不关心其他任何事情。

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

关于java - 重绘()不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27875571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com