Как добавить нажатие клавиши внутри метода keyPressed (KeyEvent e), чтобы изменить цвет шара? простая демонстрация KeyListener

1

У меня ограниченный опыт Java, особенно когда речь идет о графике. До сих пор у меня была очень хорошая помощь по этой проблеме. Это стартовый код (ниже), который отлично работает, когда я тестировал его в Eclipse. Я использую его из класса, чтобы научить ученика средней школы. В соответствии с приведенными ниже инструкциями в комментариях кто-нибудь знает, что простой способ расширить уже простую программу, чтобы изменить цвет шара после нажатия кнопки C? Я подумываю добавить следующий код к методу keyPressed (KeyEvent e):

else if(keyCode == KeyEvent.VK_C)    
{     
   //Not sure what code to add here 
   //g.setColor(Color.green);   ----> this line says "g can not be resolved". 
}

Любые советы или идеи, чтобы поддерживать простую программу, были бы очень оценены. Спасибо. ,

import java.awt.*;
import java.awt.event.*;                            // #1
import javax.swing.*;   

/******************************************************************************
 * 
 * KeyListenerDemo.java
 * Demonstrates getting keyboard input using the KeyListener interface.
 * 
 * Program 18: Extend this program by adding a few more keystroke commands:
 *      z     (VK_Z)    - Cause the ball to jump to a random new location.
 *      s     (VK_S)    - Make the ball smaller - multiply its diameter 1/2.
 *      b     (VK_B)    - Make the ball bigger - multiply its diameter by 2.
 *      c     (VK_C)    - Change the color (in any way you'd like).
 *
 *  In addition, modify the program to ensure the following:
 *  - The ball goes all the way to the edge of the screen but stays
 *          completely on the screen. 
 *  - If a doubled diameter doesn't fit, make it as large as possible.
 *  - Be sure the ball never completely disappears.
 * 
 *****************************************************************************/
public class KeyListenerDemo extends JFrame
                        implements KeyListener      // #2
{
// Class Scope Finals
private static final int SCREEN_WIDTH = 1000;
private static final int SCREEN_HEIGHT = 800;
private static final int START_RADIUS = 25;
private static final int START_X = 100;
private static final int START_Y = 100;
private static final int STEP_SIZE = 10;

// Class Scope Variables
private static int x = START_X;             // x at center of the ball
private static int y = START_Y;             // y at center of the ball
private static int radius = START_RADIUS;   // radius of the ball

// Methods
/**
 * Create the window and register this as a KeyListener
 * 
 * @param args
 */
public static void main (String[] args)
{
    // Set up the JFrame window.
    KeyListenerDemo gp = new KeyListenerDemo();
    gp.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    gp.setVisible(true);

    gp.addKeyListener(gp);                          // #3
    // If this class had a constructor and you moved this line into
    //   that constructor it could not refer to gp since that variable
    //   is local to this method.  Instead you would write::
    // addKeyListener(this);
}

/**
 * Called when a key is first pressed
 * Required for any KeyListener
 * 
 * @param e     Contains info about the key pressed
 */
public void keyPressed(KeyEvent e)                  // #4A
{
    int keyCode = e.getKeyCode();
    if (keyCode == KeyEvent.VK_LEFT)
    {
        x = x - STEP_SIZE;
    }
    else if (keyCode == KeyEvent.VK_RIGHT)
    {
        x = x + STEP_SIZE;
    }
    else if (keyCode == KeyEvent.VK_UP)
    {
        y = y - STEP_SIZE;
    }
    else if (keyCode == KeyEvent.VK_DOWN)
    {
        y = y + STEP_SIZE;
    }
    repaint();
}

/**
 * Called when typing of a key is completed
 * Required for any KeyListener
 * 
 * @param e     Contains info about the key typed
 */
public void keyTyped(KeyEvent e)                    // #4B
{
}

/**
 * Called when a key is released
 * Required for any KeyListener
 * 
 * @param e     Contains info about the key released
 */
public void keyReleased(KeyEvent e)                 // #4C
{
}

/**
 * paint - draw the figure
 * 
 * @param g     Graphics object to draw in
 */


   public void paint(Graphics g)
    {
        g.setColor(Color.white);
        g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

        g.setColor(Color.blue);
        g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }
}
  • 1
    Вы должны вернуться и принять ответы на все ваши вопросы. Люди с большей вероятностью ответят на ваши вопросы, если вы дадите им баллы за ответы на них.
  • 0
    Это имеет смысл. Я новичок в этом сайте. Как я принимаю ответы конкретно? Еще раз спасибо
Теги:
keylistener

2 ответа

1
Лучший ответ
private Color currentColor;

...

public void paint(Graphics g)
{
    g.setColor(Color.white);
    g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

    g.setColor(currrentColor);
    g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
}

...

public void keyPressed(KeyEvent e)                  
{
    int keyCode = e.getKeyCode();
    if (keyCode == KeyEvent.VK_LEFT)
    {
        x = x - STEP_SIZE;
    }
    else if (keyCode == KeyEvent.VK_RIGHT)
    {
        x = x + STEP_SIZE;
    }
    else if (keyCode == KeyEvent.VK_UP)
    {
        y = y - STEP_SIZE;
    }
    else if (keyCode == KeyEvent.VK_DOWN)
    {
        y = y + STEP_SIZE;
    }else currentColor = Color.BLUE;
    repaint();
}

Вероятно, вы должны сделать что-то подобное.

  • 0
    Спасибо. Я дам ему попробовать.
  • 0
    Спасибо! Простое решение и хорошо работает сейчас. Я ценю это.
0

Вы не имеете графическую переменную 'g' в событии нажатия клавиши, чтобы получить компиляционную ошибку без разрешения. Необходимо сохранить цвет для рисования в переменной и использовать его в методе рисования.

Имейте переменную экземпляра класса, которая является цветом. Первоначально это будет

colorBall = Color.white

затем нажмите C, если его белый цвет станет зеленым, и наоборот.

В краске просто используйте переменную цвета

  g.setColor(colorBall );
  • 0
    Спасибо за всю помощь. Я понимаю, как эта переменная экземпляра будет работать сейчас.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню