2012-03-06 41 views
-1

我需要幫助製作一個有2個按鈕的程序。當按鈕被點擊時,出現一條消息「我被點擊了n次!」。每個按鈕應該有一個單獨的點擊數。按鈕計數器Java

import java.awt.event.ActionListener; 
    import javax.swing.JButton; 
    import javax.swing.JFrame; 

    public class ButtonViewer 
    { 
     private static final int FRAME_WIDTH = 400; 
     private static final int FRAME_HEIGHT = 360; 


public static void main(String[] args) 
{ 
    int counter1 = 0; 
    int counter2 = 0; 

    JFrame frame = new JFrame(); 
    JButton button = new JButton("Click me!"); 
    frame.add(button); 

    JFrame frame2 = new JFrame(); 
    JButton button2 = new JButton("Click me too!"); 
    frame2.add(button2); 

    ActionListener listener = new ClickListener(); 
    button.addActionListener(listener); 
    button2.addActionListener(listener); 

    counter1++; 
    counter2++; 

    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 

    frame2.setSize(FRAME_WIDTH, FRAME_HEIGHT); 
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame2.setVisible(true); 
} 
} 
+4

這看起來像家庭作業... – 2012-03-06 19:08:37

+1

我們不會爲你做功課,但我們會幫助你。嘗試一下,告訴我們你卡在哪裏。如果你已經做出了明確的努力,我們會把你推向正確的方向。 – switz 2012-03-06 19:09:25

+1

你有沒有試過解決這個問題? – 2012-03-06 19:09:55

回答

0

一個簡單的解決方案是實現內聯的ActionListener。只需要:

button2.addActionListener(new ActionListener(){ 
... 
}); 

在那裏實現actionperfomed方法時,您可以輕鬆地更改button2的文本。

0

您沒有對動作偵聽器進行回調,因此當您單擊該按鈕時,偵聽知道正在發生的事情,但沒有任何指示該怎麼做。就像@KingWilliam提到的,這看起來像功課,所以尋找行動聽衆回電應該足以讓你的齒輪移動。

0

監聽器是一個接口,所以在實現類中,需要確保實現了actionPerformed()方法。你只需要檢測'click'事件的資源,如果它來自按鈕增加按鈕的計數器,並且與button2相同。

0

初始化count的兩個變量,比如count1,count2。對於按鈕1個寄存器匿名類作爲一個事件監聽器是這樣的:

button1.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent ae){ 
     count1++; 
     new CustomMessage(count1); 
    } 
}); 

其中CUSTOMMESSAGE應該是這樣的:

class CustomMessage extends javax.swing.JDialog{ 
    public CustomMessage(int counter){ 
    //... 
    } 
} 

確保納入「反」的消息。 同樣按鈕2。希望這對你有用! 好運。

3

要開始您將需要實際添加一個ClickListener,通過實際編寫類似下面的另一種方法:

private class listener1 implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
     counter1++; 
    } 
} 

你有這些類2在這種情況下......每一個按鈕。 當按下按鈕時,第二個偵聽器只會增加另一個計數器。