Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按下Java键后,图像将不会被处理_Java_Graphics_Paintcomponent_Keyevent - Fatal编程技术网

按下Java键后,图像将不会被处理

按下Java键后,图像将不会被处理,java,graphics,paintcomponent,keyevent,Java,Graphics,Paintcomponent,Keyevent,我在JPanel的图形背景上绘制图像。但是,当我按下S键时,图像不会从图形上下文中删除。我确信我的键盘侦听器正在工作 如果我正在处理图形上下文,那么图形上下文上的内容不应该消失吗 public class MainMenu extends JPanel implements KeyListener { private JFrame frame; private int width = 660; private int height = 500; private

我在JPanel的图形背景上绘制图像。但是,当我按下S键时,图像不会从图形上下文中删除。我确信我的键盘侦听器正在工作

如果我正在处理图形上下文,那么图形上下文上的内容不应该消失吗

public class MainMenu extends JPanel implements KeyListener {

    private JFrame frame;
    private int width = 660;
    private int height = 500;
    private Image image;
    private boolean removeImage = false;

    public MainMenu()
    {
        frame = new JFrame();
        frame.setResizable(false);
        frame.setTitle("Menu Test");
        setBackground(Color.BLACK);
        frame.setSize(width,height);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // add main menu to the frame
        frame.add(this);
        // let the frame know about keyevents from this class
        frame.addKeyListener(this);

    }

    public void setup()
    {
        frame.setVisible(true);

    }



    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        if(e.getKeyCode() == KeyEvent.VK_S)
        {

            removeImage = true;

        }

        repaint();
    }



    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        try {
            image = ImageIO.read(new File("Game/menuScreen.PNG"));

            g.drawImage(image, 0, 0, null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        if(removeImage)
        {
            g.dispose();
        }

    }
调用
Graphics#dispose
不会从
JPanel

if (removeImage) {
   g.dispose();
}
而是使用
布尔
标志指示是否应绘制图像

if (showImage) {
   g.drawImage(image, 0, 0, this);
}
将标志更新为
false
并调用
repaint
以有效地“清除”任何以前的图像

showImage = false;
repaint();

注:

  • 对于
    paintComponents
    中的
    Graphics
    对象,无需调用
    dispose
    。这仅适用于自定义
    图形
    参考
  • 不要从
    paintComponent
    加载图像-这会降低性能。在启动时从方法加载映像
  • 在开发Swing应用程序时,使用而不是
    键侦听器
    。后者使用需要焦点才能工作的
    KeyEvents
    <代码>键绑定
    使用不考虑焦点的
    击键

这就是它的工作原理。好的,我把加载映像放在构造函数中+1和绿色支票!