Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Swing Code Examples

Moving label using arrow keys

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
Moving label using arrow keys import java.awt.*; import javax.swing.*; import java.awt.event.*; public class MoveLabel extends JFrame { JLabel label; public MoveLabel() { label = new JLabel(new ImageIcon("copy.gif")); label.setBounds(20,30,16,19); label.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { if(ke.getKeyCode() == KeyEvent.VK_DOWN) { label.setLocation(label.getX(),label.getY()+1); repaint(); } if(ke.getKeyCode() == KeyEvent.VK_UP) { label.setLocation(label.getX(),label.getY()-1); repaint(); } if(ke.getKeyCode() == KeyEvent.VK_LEFT) { label.setLocation(label.getX()-1,label.getY()); repaint(); } if(ke.getKeyCode() == KeyEvent.VK_RIGHT) { label.setLocation(label.getX()+1,label.getY()); repaint(); } } }); label.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if(me.getClickCount() == 1) { boolean dd = label.isOptimizedDrawingEnabled(); boolean ff = label.requestFocusInWindow(); repaint(); } } }); JPanel p = new JPanel(); p.setPreferredSize(new Dimension(2000,1000)); p.setLayout(null); p.add(label); JScrollPane js = new JScrollPane(p); getContentPane().add(js); } public static void main(String args[]) { MoveLabel frame = new MoveLabel(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.setSize(300,300); frame.setVisible(true); } }