gpt4 book ai didi

java - 如何绘制另一个对象而不是 repaint() JPanel

转载 作者:行者123 更新时间:2023-12-01 20:13:12 24 4
gpt4 key购买 nike

我有一个 JFrame,其中使用 3 个线程打印 3 个对象:
线程-1) 打印圆圈
线程 2) 打印方 block
线程 3) 打印三角形
问题是我需要一遍又一遍地打印新对象,而不仅仅是重新绘制它们。但是我每个线程的 run() 函数无法触及该类的重写方法 PaintComponent(Graphics g) 的 Graphics g 变量。我只能在 run() 函数中使用 repaint() 。
这就是我所拥有的:(使用repaint()方法) https://prnt.sc/gnxz6iM
这就是我想要的(没有 PaintImmediatly() 方法的那些方形边框):https://prnt.sc/gny1qx

package tarefa03;

import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.Random;
import javax.swing.OverlayLayout;


public class FigurePlacer extends JPanel implements Runnable{
final int width = 700;
final int height = 700;
int x_pos = 0;
int y_pos = 0;
int x_width = 50;
int y_height = 50;
String figure;

public FigurePlacer(String str){
figure = str;
randomCoord();
setOpaque(false);
setBounds(0, 0, width, height);
Thread th = new Thread (this);
th.start();
}

private void randomCoord(){
Random random = new Random();
x_pos = random.nextInt(width);
y_pos = random.nextInt(height);
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
switch (figure){
case "circle":
g2.setColor(Color.BLUE);
g2.fillOval(x_pos, y_pos, x_width, y_height);
break;

case "square":
g2.setColor(Color.GREEN);
g2.fillRect(x_pos, y_pos, x_width, y_height);
break;

case "triangle":
g2.setColor(Color.ORANGE);
int xpoints[] = {x_pos, x_pos+25, x_pos+50};
int ypoints[] = {y_pos, y_pos+50, y_pos};
g2.fillPolygon(xpoints,ypoints,3);
}
}

@Override
public void run(){
while (true){
randomCoord();
this.paintImmediately(x_pos, y_pos, x_width, y_height);
try{
Thread.sleep (200);
}
catch (InterruptedException ex){}
}
}

}

最佳答案

您的渲染没有表明它的绘图例程不是不透明的。

当在某些东西上绘制时,setOpaque(...) 方法会提示渲染线程是否可以直接设置背景像素,或者必须检查透明度并与现有像素混合像素值。

请注意,您还必须在颜色中设置透明度。缺少这样的东西意味着您的混合支持可能已打开,但您绘制了不透明的颜色。

此外,Swing 不是多线程安全的。它使用私有(private)线程进行光栅化和 UI 更新。任何“多线程”解决方案都需要将所有 UI 更新分派(dispatch)到该绘图线程。否则,您将无法获得所需的结果(因为渲染线程已集成到核心操作系统绘图例程中,并且是专门为支持 AWT、Swing 和其他技术而编写的。

这意味着即使是像呈现 GUI 框架这样的小事情也需要"dispatch"。如果您有需要在主 Java 线程和绘图线程之间进行协调的任务,请参阅 SwingWorker;如果协调不是那么细粒度,请参阅 SwingUtilites.invokeAndWait(...)/SwingUtilites.invokeLater(...)。

是的,您可以尝试从主线程执行操作(就像您所做的那样)。有时它几乎可以工作,但通常它不会正常工作,并且随着时间的推移不会继续正常工作。

关于java - 如何绘制另一个对象而不是 repaint() JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346971/

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