gpt4 book ai didi

java - 如何对图像执行 'undraw' 操作?

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

我正在尝试用Java制作一个简单的游戏,我需要做的就是在屏幕上绘制一个im,然后等待5秒然后“取消绘制”。

代码(此类在屏幕上绘制图像):

 package com.mainwindow.draw;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class MainWindow extends JPanel{

Image Menu;
String LogoSource = "Logo.png";

public MainWindow() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(LogoSource));
Menu = ii.getImage();
Timer timer = new Timer(5, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();

}
});
timer.start();

}

public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null);


}
}

代码#2(这会创建 JFrame)

package com.mainwindow.draw;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Frame extends JFrame {

public Frame() {
add(new MainWindow());
setTitle("Game Inviroment Graphics Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 480);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);


}
public static void main(String[] args) {
new Frame();
}
}

最佳答案

使用某种标志来确定是否应该绘制图像,并根据需要简单地更改其状态...

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (draw) {
g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null);
}
}

然后在需要时更改标志的状态...

Timer timer = new Timer(5, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
draw = false;
repaint();
}
});

注意:不建议重写paintpaint位于绘制更改的顶部,很容易破坏绘制过程的工作方式,导致无休止问题。相反,通常建议使用 paintComponent 代替。请参阅Performing Custom Painting了解更多详情

另请注意:javax.swing.Timer 预计延迟以毫秒为单位...5 有点快...

关于java - 如何对图像执行 'undraw' 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22398145/

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