2013-05-01 138 views
-2

即时消息真的很新,我第一次创建按钮。我认为我有基本的想法,但它不起作用。任何你可以添加到我的代码的任何部分是非常有用的。帮帮我!这里是我的代码:在java中的按钮,创建和使用动作监听器

import java.applet.Applet; 
import java.awt.*; 
import java.awt.event.*; 

public class MovingBox extends Applet 
{ 
    Thread thread; 
    Dimension dim; 
    Image img; 
    Graphics g; 
    Color red = null; 
    Color blue = null; 
    Font fnt16P = null; 


    public void init() 
    { 
    resize(800,500);  


    Button b_Up = new Button("Up"); 
    b_Up.setSize(100, 25); 
    b_Up.setLocation(450,450+ 90); 
    b_Up.setBackground(red); 
    b_Up.setForeground(blue); 
    b_Up.setFont(fnt16P); 
    b_Up.setVisible(true); 
    b_Up.addActionListener((ActionListener) this); 
    add(b_Up); 


    } 

    public void paint(Graphics gfx) 
    { 
    g.setColor(Color.green); 
    g.fillRect(0,0,800,500); 
    } 
    public void actionPerformed(ActionEvent event) 
    { 
    int value, total;; 
    Object cause = event.getSource(); 

    if (cause == b_Up) 
    (
    ) 

    } 

} 
+0

什么不在你当前的代码中工作?你还需要在你的'if(cause == b_Up)'之后交换'()'为'{}'。 – 2013-05-01 18:30:33

+0

你得到什么错误? – Mavrick 2013-05-01 18:35:25

回答

2

此代码不能编译3个原因:

变量b_UpactionPerformed可见。使它成为一个类的成员变量这个工作,并宣布它作为

b_Up = new Button("Up"); 

你不能有注册thisActionListener

b_Up.addActionListener(this); 

除非类是该类型的,因此类需要声明作为

public class MovingBox extends Applet implements ActionListener { 

使用大括号,而不是括号定义的if声明正文:

if (cause == b_Up) { 
    ... 
} 

考虑使用以下:

  • 使用匿名ActionListener的组件。更好的实现方法
  • private类的成员变量 - 明确使用这些
  • 的Java命名约定建议驼峰而非匈牙利命名法
  • 考虑使用更现代化的轻量级Swing libary过重量级AWT,
2

唐不定义图形对象。使用传递给该方法的Graphics对象。

Graphics g; 
... 
public void paint(Graphics gfx) 
    { 
    g.setColor(Color.green); 
    g.fillRect(0,0,800,500); 
    } 

不要手动设置大小/位置。使用布局管理器并让布局管理器完成其工作。

Button b_Up = new Button("Up"); 
b_Up.setSize(100, 25); 
b_Up.setLocation(450,450+ 90); 

我建议你花时间学习如何使用Swing而不是学习AWT。基础知识以Swing tutorial开头。