简体   繁体   中英

How to Properly Use repaint(); in Java

This is my first time using swing graphics so bear with me. My current goal is to have a texture change when I press one of the arrow keys (to change the direction of the image that I am using). In doing this, I have created a paint method and I want to call it using repaint(); when I press an arrow key. I was also thinking of having a parameter to paint so that it change what it is painting depending on that.

Here is the code that I have currently:

 //startGame.java
//Version 1.0
//09/06/2016

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;


public class Main extends JFrame
{


public static void main(String[] args)
{
    final JFrame frame = new JFrame("Display Mode");
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setUndecorated(true);


    frame.pack();
    frame.setVisible(true);

    frame.addKeyListener(new KeyInput());

}
private static class KeyInput implements KeyListener
{
    public void keyPressed(KeyEvent ke)
    {
        if(ke.getKeyCode() == KeyEvent.VK_ESCAPE)
        {
            System.exit(0);
        }
        if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
        {
            //repaint();


        }
        /*if(ke.getKeyCOde() == KeyEvent.VK_LEFT)
        {



        } */
    }
    public void keyTyped(KeyEvent ke)
    {}
    public void keyReleased(KeyEvent ke)
    {}
}

@Override
public void paint(Graphics g)
{
    super.paint(g);
    ImageIcon player = new ImageIcon("RealPlayersV2.png");
    image = player.getImage();

    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(image, 187, 245, this);


}

}

In my private static class Keylistener, etc. I want to call repaint(); so that my paint method will be called. Unfortunately, repaint(); cannot be called from a static method like my keylistener method. Is there any elegant solution to using repaint(); on a keypress? Thanks!

Your Main class extends JFrame so it is one and you should use it and not create a new JFrame like you did in your main method.
Then you should move the frame initialisation to the constructor which will allow you to make KeyListener NOT static. And when its not static you are allowed to call the repaint method.

public class Main extends JFrame{
    public static void main(String[] args){
        new Main();
    }
    public Main(){
        super("Display Mode");
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setUndecorated(true);
        pack();
        setVisible(true);
        addKeyListener(new KeyInput());
   }
   private class KeyInput implements KeyListener{
         [...] repaint(); [...]
   }
   @Override
   public void paint(Graphics g){...}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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