2013-05-01 143 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開頭。