首页 > 解决方案 > java - 如何在java中仅使用一种方法检测按键?

问题描述

我正在尝试绘制 6 种颜色、10 种形状、一个 jpeg 图像和 3 个在 java 中按下一个键时会发生变化的东西。

但是,我正在尝试用一种方法对所有这些进行编程。除了检测按键之外,我已经完成了其他所有操作。我看过很多例子,但它们都使用不同的方法或类来共同检测按键。但是我该如何检测按键并同时通过一种方法更改 JPanel 中的图片/图像。

我试图编写一些代码,但它不起作用(JPanel/屏幕上没有显示任何内容)这是我的代码到目前为止:

public void paint(Graphics g){

      g.setColor(Color.WHITE);
      g.fillRect(0, 0, 1000, 1000);

      BufferedImage photo = null;
      try 
      {
       File file = new File("holiday.jfif");
       photo = ImageIO.read(file);
      } 
      catch (IOException e)
      {
       g.drawString("Problem reading the file", 100, 100);
      }
      g.drawImage(photo,0,0,800,800,null);

      g.setColor(Color.BLACK);
      g.fillRect(120,300,100,100 );
      g.setColor(Color.GREEN);
      g.fillOval(270,130,50,100 );
      g.setColor(Color.BLUE );
      g.fillRect(350,200,100,150 );
      g.setColor(Color.PINK);
      g.fillOval(460, 270, 50, 50);

      g.setColor(Color.GRAY);
      g.fillArc(500, 300, 110, 100, 5, 150);
      g.setColor(Color.YELLOW);
      g.fillRect(500,450,100,100);
      g.setColor(Color.YELLOW);
      g.fillOval(550,500,100,100);
      int[] xpoints = {50,150,20,180};
      int[] ypoints = {500,500,550,550};
      g.setColor(Color.BLACK);
      g.drawPolygon(xpoints,ypoints,4);
      int[] xpoint = {250,220,380,350};
      int[] ypoint = {500,550,550,500};
      g.drawPolygon(xpoint,ypoint,4);
      int[] x = {600,500,700};
      int[] y = {20,100,100};
      g.drawPolygon(x,y,3);
      g.setColor(Color.ORANGE);
      g.fillRect(10,50,220,30);
      g.fillRect(115,80,20,100);

      Scanner input = new Scanner(System.in);
      String press;
      boolean stop = false;  
      while(!stop)
      {
       //Scanner input = new Scanner(System.in);
       press = input.next();

       if (press != null)
       {
        g.clearRect(115,80,20,100);
        g.clearRect(500,450,100,100);
        stop = true;
       }
     }


   }

标签: javaswinggraphicsjpanelkeypress

解决方案


推荐阅读