Dear i want to make a program i which when Pressed UP Arrow key cicle start moving up and when pressed DOWM key circle moves Downword Similarly left and right i have draw circle and also implements Key Listner and can anyone give me ideo how i do this task here is my code.

import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
class MovingBalls extends JFrame implements KeyListener
{
     public MovingBalls()
     {
         setTitle(":: Move ball With Keyboard Input ::");
         setVisible(true);
         setBounds(100,100,500,500);
         setDefaultCloseOperation(EXIT_ON_CLOSE);
     }
     public void paint(Graphics g){
         g.drawOval(40, 40, 60, 60);
         g.fillOval(40, 40, 60, 60);
         g.addKeyListener(this);
     }
     public void keyPressed(KeyEvent ke1)
     {

     }
     public void keyTyped(KeyEvent ke2){}
     public void keyReleased(KeyEvent ke3){}
     public static void main(String abc[])
    {
        MovingBalls MB = new MovingBalls();

    }
}
  • JFrame is Top-Level Container, its RootPane isn't by default focusable, then can't receive Key Events

  • you have to

    1. put there JPanel

    2. override paintComponent instead of paint

    3. 1st. code line inside paintComponent(Graphics g){ shoudl be super.paintComponent, otherwise painting cumulated

    4. use KeyBindings, in a state of extreme danger:-) you can to use KeyListener, but again JPanel is container, isn't focusable too, but in this case is possible to change its status with setFocusable(true);

    5. better is to use KeyBindings instead of KeyListener

can you please make a program for me??

can you please make a program for me??

There are lots of people here who will freely give their time to help you become the best Java programmer you can be. There's nobody here who is interested in helping you cheat or doing your homework for you.

ok thanks for giving me the Knowledge.I will try to make it my self.

OK. Here's an outline of how to do this:

Use a JPanel like mKorbel says

Have variables for the current position (x,y)
Change your paintComponent method to use the current x,y position
Have variables to show which direction to move in (and maybe how fast)
Have a small method to move the circle by updating its x and y positions then calling repaint() to cause a screen refresh (that will call your paintComponent)

Use a java.util.Timer to call your move method at regular intervals (eg 20 times per second)

Use the keyboard to change the direction/speed variables - that will affect how the move method updates x and y, and therefore where the circle is drawn.

mKorbel - I know you are a big supporter of key bindings, but can you use them to detect keypressed/keyreleased for game-like movement as long as an arrow key is held down?

@JamesCherrill

  • there is used the same setting (from native OS) as for KeyEvent, repeatly (if key is pressed then) firing quite same events,

  • advantage you can to play with focus for JComponents

  • disatvantage, Swing uses KeyBindings internally, there can be concurency, some of MODIFIER + key are missplelled (they are not important in real life), not possible to determine 3 or more key are pressed in the same time

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

    public class JScrollBarUnitIncrement {

    public JScrollBarUnitIncrement() {
        final JFrame f = new JFrame("");
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2000, 1));
        for (int i = 0; i != 2000; i++) {
            JButton btn = new JButton("Button 2");
            panel.add(btn);
        }
        final JScrollPane sPane = new JScrollPane(panel);
        sPane.setPreferredSize(new Dimension(150, 400));
        final int increment = 50;
        sPane.getVerticalScrollBar().setUnitIncrement(increment);
        KeyStroke kUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
        KeyStroke kDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
        sPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(kUp, "actionWhenKeyUp");
        sPane.getActionMap().put("actionWhenKeyUp", new AbstractAction("keyUpAction") {
            private static final long serialVersionUID = 1L;
    
            @Override
            public void actionPerformed(ActionEvent e) {
                final JScrollBar bar = sPane.getVerticalScrollBar();
                int currentValue = bar.getValue();
                bar.setValue(currentValue - increment);
            }
        });
        sPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(kDown, "actionWhenKeyDown");
        sPane.getActionMap().put("actionWhenKeyDown", new AbstractAction("keyDownAction") {
            private static final long serialVersionUID = 1L;
    
            @Override
            public void actionPerformed(ActionEvent e) {
                final JScrollBar bar = sPane.getVerticalScrollBar();
                int currentValue = bar.getValue();
                bar.setValue(currentValue + increment);
            }
        });
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(sPane);
        f.pack();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                f.setVisible(true);
            }
        });
    }
    
    public static void main(String[] args) {
        new JScrollBarUnitIncrement();
    }
    

    }

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.