gpt4 book ai didi

java - 如何在线程中放置两个不同的任务

转载 作者:行者123 更新时间:2023-11-30 09:22:27 25 4
gpt4 key购买 nike

我有以下代码。在这段代码中,我有一个从左向右移动的图像和一个有事件的按钮。但我想把这两个任务都放在线程中。以便它可以正常工作。此代码的问题是按钮事件在到达最右边的点之前不起作用。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyImage extends JFrame implements ActionListener
{
static int xPixel = 20;
Image myImage, offScreenImage;
Graphics offScreenGraphics;
JPanel p = new JPanel();
Button btn = new Button("bun");
JFrame f = new JFrame();


public MyImage()
{
myImage = Toolkit.getDefaultToolkit().getImage("mywineshoplogo.jpg");
setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(p);
p.add(btn);
moveImage();
btn.addActionListener(this);
}

public void update(Graphics g)
{
paint(g);
}

public void paint(Graphics g)
{
int width = getWidth();
int height = getHeight();
if (offScreenImage == null)
{
offScreenImage = createImage(width, height);
offScreenGraphics = offScreenImage.getGraphics();
}
// clear the off screen image
offScreenGraphics.clearRect(0, 0, width + 1, height + 1);
// draw your image off screen
offScreenGraphics.drawImage(myImage, xPixel, 10, this);
// draw your image off screen
// show the off screen image
g.drawImage(offScreenImage, 0, 0, this);
// show the off screen image
}

void moveImage() //left to right move
{
Thread hilo = new Thread() {

public void run() {
try {

for (int i = 0; i < 530; i++)
{

xPixel += 1;
repaint();
// then sleep for a bit for your animation
try
{
Thread.sleep(4);
} /* this will pause for 50 milliseconds */

catch (InterruptedException e)
{
System.err.println("sleep exception");
}
}
} //try
catch (Exception ex) {
// do something...
}
}
};
hilo.start();
}

/* void moveimg() // right to left move
{
for (int i = 529; i > 0; i--)
{
if (i == 1)
{
moveImage();
}
xPixel -= 1;
repaint();
// then sleep for a bit for your animation
try
{
Thread.sleep(40);
} // this will pause for 50 milliseconds

catch (InterruptedException e)
{
System.err.println("sleep exception");
}
}
} */

public void actionPerformed(ActionEvent ae)
{
try
{
if (ae.getSource() == btn)
{
p.setBackground(Color.RED);
}
}
catch (Exception e)
{
System.out.println("error");
}
}

public static void main(String args[])
{
MyImage me = new MyImage();
}
}

最佳答案

每当您要在您的 GUI 代码中编写 Thread.sleep 时,请停下来并引入一个在 Swing 的 Timer 上安排的任务。这正是您的代码所需要的:将每个更新安排为 Timer 上的单独计划任务。 Timer 非常简单易用,参见示例 this official Oracle tutorial .

关于java - 如何在线程中放置两个不同的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16480969/

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