gpt4 book ai didi

java - 线程和图形

转载 作者:行者123 更新时间:2023-12-02 04:38:19 26 4
gpt4 key购买 nike

我正在制作一个带有棋盘的小程序(如棋盘,大小为 m x n),每个字段都必须位于不同的线程中,并且它必须每秒改变颜色,直到我将其关闭。我该怎么做呢?我不能只将 g.setColorg.fillRect 放入 run 方法中。有没有办法通过使用paintComponent方法来绘制整个事物并每秒改变颜色,所有这些都在每个字段的单独线程中进行?

小程序:

import javax.swing.JApplet;

public class MyApplet extends JApplet {

public void init() {
add(new Board( Integer.parseInt(getParameter("m")),
Integer.parseInt(getParameter("n")),
Integer.parseInt(getParameter("k")),
Integer.parseInt(getParameter("p"))
));
}
}

董事会:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
import java.net.*;
import java.util.Random;

class NowyWatek extends Board implements Runnable{
public NowyWatek(){
super(0, 0, 0, 0);
}
public void run(){
Random random=new Random();
int r1=random.nextInt(255)+0;
int r2=random.nextInt(255)+0;
int r3=random.nextInt(255)+0;
g.setColor(r1, r2, r3);
}

}

public class Board extends JPanel {
int m,n,k,p;
public Board (int m, int n, int k, int p) {
super();
this.m = m;
this.n = n;
this.k = k;
this.p = p;
}

public void paintComponent(Graphics g)
{
int a=0, b=0;
for(int i=0; i<m*n;i++)
{
NowyWatek nowywatek=new NowyWatek();
Thread thread=new Thread(nowywatek);
thread.start();
g.fillRect(a,b,29,29);
a+=30;
if(i%n==n-1)
{
a=0;
b+=30;
}
}
}
}

最佳答案

it has to change color every second until I turn it off. How am I suppose to do this with this?

  1. 创建 swing Timer更新颜色并调用组件上的repaint
  2. 保留对您在 (1) 中更改的 Color 对象的引用
  3. 将 Color 对象从 (2) 传递到 paintComponent 中的 g.setColor

例如:

Color color = Color.WHITE;
Random random = new Random();
....
Timer timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
int r1=random.nextInt(255);
int r2=random.nextInt(255);
int r3=random.nextInt(255);
color = new Color(r1, r2, r3);
repaint();
}
});
timer.start();
...
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(color);
...
}

关于java - 线程和图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30488741/

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