Hi, I need some help on this how can i use the arrow keys(up,down,left and right) in the keyboard so that the filloval will move, I have no idea on this.can you help me on this please.

Thank you in advance.

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


public class TestPoint extends JFrame 
{

  int x = 10;
  int y=100;    
   public TestPoint()
   {
         setTitle("sdfds");
         setSize(400,400);
         setVisible(true);
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         addKeyListener(this);
   }


    public void paint(Graphics g)
    {


        super.paint(g);

        this.setBackground(Color.white);
        g.setColor(Color.RED);
        g.fillOval(x,y,10,10);

    }



    public static void main(String[]c)
    {

        TestPoint t = new TestPoint();
        t.setBackground(Color.white);


    }


}

implement a keyListener.
in the methods, print the value of the char linked to the KeyEvent, that way you know which charvalues to filter on.

Hi stultuske,

I tried to get the keycode but it doesnt work. can you tell me what is wrong in my code.

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



public class TestPoint extends JFrame implements KeyListener
{

  int x = 10;
  int y=100;    
   public TestPoint()
   {

         setTitle("My Ball");
         setSize(400,400);
         setVisible(true);
         setDefaultCloseOperation(EXIT_ON_CLOSE);




   }


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

        this.setBackground(Color.white);
        g.setColor(Color.RED);
        g.fillOval(x,y,10,10);

    }



    public void keyPressed(KeyEvent e){
        System.out.print(e.getKeyCode());
    }
     public void keyReleased(KeyEvent e){

    }
     public void keyTyped(KeyEvent e){

    }

    public static void main(String[]c)
    { 
        TestPoint t = new TestPoint();
        t.setBackground(Color.white);

    }


}

you didn't add your listener to a component.

Okay thanks, it will print now..the keycode of the arrow up is 38,okay i will try now to move the ball,i will write back to you.

hi stultuske, is this correct ?

  public void keyPressed(KeyEvent e){

       if(e.getKeyCode()==38){
           y++;
           repaint();
       }

    }

Hi stultuske, i want to draw an arc,but i could not use paint if i pressed the arrow up

how to do that?just like pacman

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

        this.setBackground(Color.white);
        g.setColor(Color.RED);

        g.fillArc(x,y,40,40,30,200);

    }

      public void keyPressed(KeyEvent e){

   if(e.getKeyCode()==38){
       y-=5; 

     Graphics ng = new Graphics();
     ng.fillArc(x,y,40,40,30,300);
      repaint();


   }
  if(e.getKeyCode()==40){
      y+=5;
      repaint();
   }
   if(e.getKeyCode()==37){
     x-=5;
     repaint();
   }
   if(e.getKeyCode()==39){
    x+=5;  
    repaint();
   }




}

Drawing is normally done in the paint method using the Graphics that you are given. You cannot create a Graphics using new Graphics() because that is forbidden. It is possible to draw outside of the paint method, but those are advanced techniques that you probably don't need because they are never needed for most purposes.

This would be easier if you were trying to represent some meaningful object rather than a TestPoint. In that case, all you would have to do would be to modify the object in your keyPressed method, and then call repaint and allow your paint method to draw the object again with your changes included. There would be no reason to draw in the keyPressed method. You don't need to draw there when your paint method does all the necessary drawing already because you called repaint().

If paint doesn't do all the necessary drawing then it can only be because you are trying to do something quite unusual.

Here's a readability tip: use constants defined in the KeyEvent class.

Example:

if (e.getKeyCode() == KeyEvent.VK_UP) {
    // ...
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    // ...
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    // ...
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    // ...
}

@mvmalderen,Okay now how do i draw and arc, i want to draw a pacman when i pressedd the arrow up the mouth of pacman is in up position,and if i pressed arrow down,the mouth of pacman is in down position.

how to achieve this.Thank you in advance.

are you familiar with using a runnable interface so you can continuously repaint the object?

on a side note... it might be my laziness talking but if it were me I'd just use several images of pacman pertaining to a direction instead of writing code to draw the shapes. Then I'd call and paint a selected image depending on which key is triggered

Along with your x and y coordinaltes you could have a boolean for mouth up. In your key event handler set the boolean correctly when the user presses up or down. In your paint method use that boolean in an if test to draw the arc up or down

  • all discusion about KeyListner is wrong, caused a few another side effects from usage of wrong Listener

  • there no reason call for repaint(), why repeating, supply methods implemented in API, all those notifiers are implemented and correctly

  • not, never to use KeyListener for Swing JComponents, this Listener is designated for AWT Components,

  • have to use hight possible abstraction for Swing JComponents, use KeyBindings instead of Keylistener

  • output from KeyBindings will be Swing Action, rather then ActionListener directly

  • KeyBindins are scallable, shareable, settable (same for Swing Action) for Focus in the window, then there isn't required to hunting for Focus or programatically to set setFocusable,

  • simple example

Hi mKorbel,

not, never to use KeyListener for Swing JComponents, this Listener is designated for AWT Components,

I am confuse between the awt components and swing components...how do i know that it is awt components?
or can you please show me the awt components that use paint method().

  • don't to use prehistoric AWT Components, their edge ended in last centaury, use only Swing, there no reason for that, there no performance issue in compare with AWT Components, simple forgot about that

  • usage AWT Components is for OpenGL/CL, 3D, CAM/CAD in Java (required native peers)

AWT classes are in the java.awt package, swing classes are in javax.swing
Swing classes have names that begin with a J (eg JLabel is swing, Label is AWT)
Like mKorbel said, the swing versions replace the AWT versions more than 10 yeras ago. You should not use the old AWT versions unless you have some very special advanced technical reason.

or for sentimental reasons .... :)

@jamescherill,@mKorbel,@stultuske, Thank you for the reply...back to my problem,i am confuse in using the keybindings...i read the keybindings tutorial but i could not get or don't know how to use.

Hoping for your positive repsonse.

mKorbel is going to disagree with me but...
In my opinion, key bindings are the right solution for real-life development, but they are not easy for a beginner. KeyListener is much easier to understand. The more you use key listener the more you will run into its problems and limitations until you are ready to tackle key bindings to solve all those problems. For now, I think you will be OK using key listeners.

@JamesCherrill :-)

@jemz

  • aaach now I see we forgot here ...

  • most important issue is that you tried to draw to the Top Level Container,

  • most important issue is that you tried react to KeyEvents (Mouse partially), this events aren't implemented in the API, simple aren't accessible for Top Level Container by default, without ton of (useless) code

  • JFrame isn't proper container for Custom painting

  • put there JComponent / JPanel and to override paintComponent instead of paint

  • override gerPreferredSize for container, otherwise JComponent / JPanel returns zero Dimension, Graphics / Graphics2D by default never returns any size

  • example by one of my pattern

.

//http://stackoverflow.com/a/10131478/714968
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RacingCars extends JFrame {

    private CarPanel car1;
    private CarPanel car2;

    public RacingCars() {//Constructor
        setLayout(new GridLayout(2, 1));
        car1 = new CarPanel('w', Color.RED);
        car2 = new CarPanel('k', Color.blue);
        car1.setBackground(Color.black);
        this.add(car1, BorderLayout.NORTH);
        this.add(car2, BorderLayout.SOUTH);
        this.addKeyListener(new MyKeyListener());
    }

    class MyKeyListener extends KeyAdapter {

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyChar() == 'w') {
                car1.moveCar();
            }
            if (e.getKeyChar() == 'k') {
                car2.moveCar();
            }
        }
    }

    public static void main(String[] args) {
        //Create the frame on the event dispatching thread
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                RacingCars rc = new RacingCars();
                rc.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                rc.pack();
                rc.setVisible(true);
            }
        });
    }
}

class CarPanel extends JPanel {

    private char forwardKey = 'w';
    private boolean reachedTarget = false;
    private Color color = Color.blue;
    private int x = 10;
    private int y = 10;
    private int panelWidth;
    private int panelHeight;

    public CarPanel() {//default Constructor
    }

    //overloaded Constructor
    public CarPanel(char key, Color color) {
        this.forwardKey = key;
        this.color = color;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GREEN);
        //g.fillOval(0, 0, 25, 25);
        panelWidth = getWidth();
        panelHeight = getHeight();
        g.setColor(color); //draw a Car        
        int t_x[] = {x + 10, x + 20, x + 30, x + 40};//polygon points
        int t_y[] = {y + 10, y, y, y + 10};
        //g.fillPolygon(t_x, t_y, t_x.length);
       // g.fillRect(x, y + 10, 50, 10);
        g.fillArc(x + 10, y + 20, 10, 10, 0, 360);
        //g.fillArc(x + 30, y + 20, 10, 10, 0, 360);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(750, 100);
    }

    public void moveCar() {
        if (this.x < panelWidth) {
            this.x += 10;
            repaint();
        }
    }
}
  • to try replace (from JPanel) paint and move painting to the Top Level Container, then to search on the net about redirect KeyEvent from AWTEventListener to custom painting, crazy job, don't do that, this is possible only with KeyBindings,

It takes time for me to understand how to use keybindings finally i got it now. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.