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

📄 example6_6.java

📁 书中的例题
💻 JAVA
字号:
1.  /* 移动方块 */
2.  import java.awt.*;
3.  import java.awt.event.*;
4.  import javax.swing.*;
5.  public class Example6_6 extends JFrame implements ActionListener
6.  {  private JButton left = new JButton("向左移");
7.     private JButton right = new JButton("向右移");
8.     private JButton up = new JButton("向上移");
9.     private JButton down = new JButton("向下移");
10.    public MoveCanvas drawing = new MoveCanvas();
11.  
12.    private class WindowCloser extends WindowAdapter
13.     {  public void windowClosing(WindowEvent we)
14.	         {System.exit(0);}	    
15.     }
16.
17.    public Example6_6()
18.	    {  super("移动方块");
19.        setSize(400,400);
20.	       show();
21.	       Panel p = new Panel();
22.	       p.setLayout(new FlowLayout());
23.	       setLayout(new BorderLayout());
24.	       add(p,BorderLayout.SOUTH);
25.	       add(drawing,BorderLayout.CENTER); 
26.        p.add(up);    p.add(down);
27.	       p.add(left);  p.add(right);
28.        validate();
29.	       left.addActionListener(this); 
30.	       right.addActionListener(this);
31.        up.addActionListener(this); 
32.	       down.addActionListener(this);
33.	       addWindowListener(new WindowCloser());
34.     }
35.  
36.	   public void actionPerformed(ActionEvent e)
37.	    {  if(e.getSource()==up)
38.		     drawing.moveUp();
39.	       else if(e.getSource()==down)
40.		     drawing.moveDown();
41.        else if(e.getSource()==left)
42.		     drawing.moveLeft();
43.        else if(e.getSource()==right)
44.		     drawing.moveRight();
45.	    }
46.	   public static void main(String args[])
47.	    {
48.	      JFrame.setDefaultLookAndFeelDecorated(true);
49.	      new Example6_6();
50.	    }
51.  }
52.
53.  //创建一个绘制可移动的方块的画布类
54.  class MoveCanvas extends Canvas
55.  {  
56.	   private final int WIDTH =30, HEIGHT = 30,INC = 10;
57.    private int i,j;
58.
59.    public void paint(Graphics g)
60.	   {  
61.	     g.drawRect(0,0,getSize().width-1,getSize().height-1); 
62.	     g.setColor(Color.black);
63.	     g.fillRect( i+2,j+2,WIDTH+2,HEIGHT+2); 
64.	     g.setColor(Color.red);
65.	     g.fillRect( i,j,WIDTH,HEIGHT);
66.    }
67.
68.    public void moveUp()
69.	    {  if(j>0)
70.	         j-=INC; 
71.        else
72.		     j=getSize().height-INC;
73.	       repaint();
74.   }
75.   public void moveDown()
76.	   {  if(j < getSize().height - INC)
77.	        j+=INC;
78.       else 
79.	  	    j = 0;
80.	      repaint();
81.    }
82.   public void moveLeft()
83.	   {  if( i > 0)
84.	         i-=INC;
85.       else 
86.		     i = getSize().width - INC;
87.	      repaint();
88.    }
89.   public void moveRight()
90.	   {  if(i < getSize().width - INC)
91.	         i+=INC;
92.       else 
93.	         i = 0;
94.		  repaint();
95.    }
96. }

⌨️ 快捷键说明

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