2014-02-11 55 views
1

我試圖使用擺動,使一個計算器,但我還是堅持了一個問題,當我編譯它,它throughing在類AbstractButton的方法addActionListener方法不能適用錯誤給定類型。方法addActionListener方法不能適用於特定類型

我的代碼是

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Calculator extends JFrame implements ActionListener { 
    private String str = "0"; 
    JTextField l_tf = new JTextField(100); 
    JButton button[] = new JButton[31]; 
    Northwindow panelNorth = new Northwindow(); 
    Centerwindow panelCenter = new Centerwindow(); 

    Calculator(String l_s) { 
     getContentPane().setLayout(new BorderLayout()); 
     getContentPane().add("North", panelNorth); 
     getContentPane().add("Center", panelCenter); 

     setSize(300, 400); 
     setVisible(true); 
    } 

    //Northwindow 

    class Northwindow extends JPanel { 
     public Northwindow() { 
      Dimension textf = new Dimension(50, 50); 
      setLayout(new GridLayout(0, 1)); 
      setBackground(new Color(230, 230, 255)); 
      l_tf.setPreferredSize(textf); 
      add(l_tf); 
     } 
    } 


    class Centerwindow extends JPanel { 
     public Centerwindow() { 
      setLayout(new GridLayout(0, 4)); 
      String key[] = {"ON", "Del", "C", "+/-", "1/x", "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+", "Sqrt", "Sqr", "Sin", "Cos", "^", "log", "ln", "tan", "(", ")", "pie"}; 

      Dimension but = new Dimension(80, 30); 
      for (int i = 0; i < button.length; i++) { 

       button[i] = new JButton(key[i]); 
       button[i].setPreferredSize(but); 
       add(button[i]); 
       button[i].addActionListener(this); 

       //before the on button is not clicked 

       for (i = 0; i < button.length; i++) 
        button[i].setEnable(false); 
       l_tf.setEditable(false); 

      } 
     } 
    } 

    public void actionPerformed(ActionEvent e) { 
     if (e.getSource == button[0]) // ON button 
     { 
      l_tf.setBackground(color.white); 
      button[0].setLabel("OFF"); 
      for (i = 0; i < button.length; i++) 
       button[i].setEnable(true); 
      l_tf.setEditable(true); 
      l_tf.setText(str); 
     } 
     if (e.getSource == button[1]) { 
     } 
    } 

    public static void main(String... s) { 
     Calculator c = new Calculator("Calculator"); 
    } 
} 

回答

4
button[i].addActionListener(this); 

這裏面出現Centerwindow不落實ActionListener。因爲Centerwindow是一個內部類,您可以訪問封閉Calculator實例,並將其添加如果這就是你想要做什麼:

button[i].addActionListener(Calculator.this); 
+0

謝謝你,我已經嘗試這樣做,它得到的工作。 – user3078082

相關問題