需要帮助在Java中绘制图像吗
我想做的是在屏幕上显示一个图像,持续x秒,然后消失,然后在它的位置绘制另一个图像,我得到了第一个要显示的图像,但第二个图像不工作注意:我可以绘制形状,但不能绘制图像需要帮助在Java中绘制图像吗,java,image,swing,timer,paintcomponent,Java,Image,Swing,Timer,Paintcomponent,我想做的是在屏幕上显示一个图像,持续x秒,然后消失,然后在它的位置绘制另一个图像,我得到了第一个要显示的图像,但第二个图像不工作注意:我可以绘制形状,但不能绘制图像 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.Acti
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 Logo;
Image Menu;
String LogoSource = "Gimijes.png";
String menuEntity = "Menu.png";
Boolean draw = true;
static Boolean timeout = false;
public MainWindow() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(LogoSource));
Logo = ii.getImage();
ImageIcon mii = new ImageIcon(this.getClass().getResource(menuEntity));
Menu = mii.getImage();
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
draw = false;
timeout = true;
repaint();
}
});
timer.start();
};
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (draw == true) {
//draw Gimijes.png (on screen for 5 seconds)
g2.drawImage(Logo, 0, 0, null);
}
if (timeout == true) {
g2.drawImage(Menu, getWidth(), getHeight(), null);
}
}
}
如果有人知道如何让这个工作,我会非常感激 问题在于新图像的位置。如果要覆盖现有图像,请使用相同的坐标(位置[0,0])
这是添加到JFrame的
JPanel
吗?getWidth(),getHeight()从getPreferredSize为JPanel返回正确的值,在此处搜索您可能遇到线程问题,计时器线程可能会将timeout更改为true,但它看起来像EDT(正在执行paintComponent)从未被告知重新查看超时变量。@Swing计时器在EDT的上下文中执行actionPerfoemed,重新绘制请求重新绘制组件,这会将重新绘制事件放入事件队列,该事件队列将(最终)调用paintComponent。就其本质而言,这两件事一件接一件地发生,这是不可能的。如果它以任何其他顺序发生…我怀疑您有图像加载问题。尝试使用ImageIO.read而不是ImageIcon,因为这将在出现问题时引发IOExceptiong2.drawImage(..,0,0,null)代码>最好是g2.drawImage(..,0,0,this)代码>因为每个组件
都是图像观察者
。
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (draw == true) {
// draw Gimijes.png (on screen for 5 seconds)
g2.drawImage(Logo, 0, 0, null);
}
if (timeout == true) {
g2.drawImage(Menu, 0, 0, null);
}
}