简体   繁体   English

java中的Coding Graphics和KeyListener

[英]Coding Graphics and KeyListener in java

I was wondering how to properly use the Graphics library and also the Keylistener in JAVA. 我想知道如何正确使用图形库以及JAVA中的Keylistener。 Underneath is my code, i believe i have done something wrong because the Window is blank with no Oval. 下面是我的代码,我相信我做错了,因为Window是空白的,没有Oval。 Please help me out! 请帮帮我!

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Game extends JFrame implements KeyListener{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    int x=100,y=100;

    boolean u,d,r,l;

    public <addKeyListener> void run(){
        setBackground(Color.gray);
        setSize(800,800);
        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addKeyListener(this);
    }
    public static void main(String[] args) {
        Game game = new Game();
        game.run(); 
        }

    public void paint(Graphics g){
        g.setColor(Color.black);
        g.fillOval(x,y,40,40);
    repaint();
    }
    {


    if(u =true){
    y-=200;

    } 
    if(d = true){
    y+=2;
    }
    if(r = true){
        x-=2;
        }
    if(l = true){
        x+=2;}
    }








    @Override
    public void keyPressed(KeyEvent e) {
    char code = e.getKeyChar();
        if(code == KeyEvent.VK_W){
            u = true;}
            if(code == KeyEvent.VK_A){
                l = true;}
                if(code == KeyEvent.VK_S){
                    d = true;}
                    if(code == KeyEvent.VK_D){
                        r = true;}

    }



    @Override
    public void keyReleased(KeyEvent e) {
        char code = e.getKeyChar();
        if(code == KeyEvent.VK_W){
            u = false;}
            if(code == KeyEvent.VK_A){
                l = false;}
                if(code == KeyEvent.VK_S){
                    d = false;}
                    if(code == KeyEvent.VK_D){
                        r = false;}

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

}
  1. You're drawing directly in the JFrame, something that is dangerous to do (as you're finding out). 你直接在JFrame中绘图,这是一件很危险的事情(正如你所发现的那样)。
  2. You're not calling the super's paint(...) method from within your paint override preventing the JFrame doing the painting that it itself needs to be doing. 你不是在你的绘画覆盖中调用super的paint(...)方法,而是阻止JFrame执行它自己需要做的绘制。
  3. You're calling repaint() from within a painting method -- never do this. 你在绘画方法中调用repaint() - 永远不要这样做。
  4. You've not read the painting in Swing tutorial yet. 你还没有在Swing教程中阅读这幅画。

Instead: 代替:

  1. Draw in a JPanel's paintComponent method. 在JPanel的paintComponent方法中绘制。
  2. Call the super's paintComponent inside your override. 在覆盖中调用super的paintComponent。
  3. Use Key Bindings not KeyListeners (Google for the tutorial as it will explain how to use these). 使用Key Bindings而非KeyListeners(Google将在本教程中介绍如何使用这些)。

Check the Swing Info link for links to tutorials and resources. 查看Swing Info链接以获取教程和资源的链接。

For example 例如

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleAnimationEg extends JPanel {
   private static final int OVAL_WIDTH = 20;
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private int x = 0;
   private int y = 0;

   public SimpleAnimationEg() {
      addKeyBindings();
   }

   private void addKeyBindings() {
      InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
      ActionMap actionMap = getActionMap();

      KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
      inputMap.put(keyStroke, keyStroke.toString());
      actionMap.put(keyStroke.toString(), new MyAction(0, -1));

      keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
      inputMap.put(keyStroke, keyStroke.toString());
      actionMap.put(keyStroke.toString(), new MyAction(0, 1));

      keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
      inputMap.put(keyStroke, keyStroke.toString());
      actionMap.put(keyStroke.toString(), new MyAction(-1, 0));

      keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
      inputMap.put(keyStroke, keyStroke.toString());
      actionMap.put(keyStroke.toString(), new MyAction(1, 0));
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setColor(Color.RED);
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.fillOval(x, y, OVAL_WIDTH, OVAL_WIDTH);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class MyAction extends AbstractAction {
      private int xDirection;
      private int yDirection;

      public MyAction(int xDirection, int yDirection) {
         this.xDirection = xDirection;
         this.yDirection = yDirection;
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         x += xDirection;
         y += yDirection;
         repaint();
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("SimpleAnimationEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new SimpleAnimationEg());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM