⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 movebox.java

📁 Java程序设计技巧与开发实例附书源代码。
💻 JAVA
字号:

import java.awt.*;
import java.awt.event.*;

public class MoveBox
    extends Frame
    implements ActionListener
{
   private final int WIDTH = 30, HEIGHT = 20, INC = 4;
   private Button left = new Button("Left");
   private Button right = new Button("Right");
   private Button up = new Button("Up");
   private Button down = new Button("Down");
   private int x = 50, y = 50;
   public MoveBox()
   {
      super("Moving Box");
      setup();
      left.addActionListener(this);
      right.addActionListener(this);
      up.addActionListener(this);
      down.addActionListener(this);
      setSize(400, 400);
      show();
   }

   private void setup()
   {
      Panel buttons = new Panel();
      buttons.setLayout(new FlowLayout());
      buttons.add(up);
      buttons.add(down);
      buttons.add(left);
      buttons.add(right);
      setLayout(new BorderLayout());
      add("South", buttons);
   }

   public void paint(Graphics g)
   {
      g.fillRect(x, y, WIDTH, HEIGHT);
   }

   public void moveUp()
   {
      y -= INC;
   }

   public void moveDown()
   {
      y += INC;
   }

   public void moveLeft()
   {
      x -= INC;
   }

   public void moveRight()
   {
      x += INC;
   }

   public void actionPerformed(ActionEvent e)
   {
      if (e.getSource() == up)
      {
         moveUp();
      }
      else if (e.getSource() == down)
      {
         moveDown();
      }
      else if (e.getSource() == left)
      {
         moveLeft();
      }
      else if (e.getSource() == right)
      {
         moveRight();
      }
      repaint();
   }

   public static void main(String args[])
   {
      MoveBox mb = new MoveBox();
   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -