2014-05-08 83 views
0

我想寫這個屏幕鍵盤,當用戶在鍵盤上按下時會發生反應。 我的問題是與keyListener,我想寫它在JPanel類,但我不斷收到這個編譯錯誤,somethig有關在行中的「實現」一詞後面缺少「{」:公共類MyKeyListener實現KeyListener()KeyListener擴展JPanel類

有人能幫助我瞭解我做錯了什麼嗎? 這是代碼:

package Q2; 
import javax.swing.*; 

import java.awt.BorderLayout; 
import java.awt.Font; 
import java.awt.GridLayout; 
import java.awt.Insets; 
import java.awt.TextField; 
import java.awt.event.KeyListener; 
import java.awt.event.KeyEvent; 
import java.util.EventListener; 

public class MainPanel extends JPanel{ 

    private JButton[][] button; 
    private JPanel[] panel;              //Array of panels for each buttons line 
    private JPanel parent; 
    private static final String[][] key = { 
     {"`","1","2","3","4","5","6","7","8","9","0","-","+","Backspace"}, 
     {"Tab","Q","W","E","R","T","Y","U","I","O","P","[","]"}, 
     {"Caps","A","S","D","F","G","H","J","K","L",";","'","\\","Enter"}, 
     {"Shif","Z","X","C","V","B","N","M",",",".","?","/"}, 
     {"               ",",","<","v",">"}}; 

    //Constructor for main Panel 
    public MainPanel(){ 
     super(); 
     setLayout(new BorderLayout()); 
     TextField textField = new TextField(20); 
     Font font1 = new Font("david", Font.BOLD, 22); 

     textField.setFont(font1); 
     add(textField,BorderLayout.CENTER); 

     //initialize the parent panel and array of 5 panels and the buttons array 
     parent = new JPanel(); 
     parent.setLayout(new GridLayout(0,1)); 
     panel = new JPanel[5]; 
     button = new JButton[20][20]; 

     for (int row = 0; row<key.length; row++){ 
      panel[row] = new JPanel(); 
      for (int column = 0; column<key[row].length; column++){ 
       button[row][column] = new JButton(key[row][column]); 
       button[row][column].setFont(new Font("Ariel",Font.PLAIN, 22)); 
       button[row][column].setMargin(new Insets(10, 20, 10, 20)); 
       button[row][column].putClientProperty("row", row); 
       button[row][column].putClientProperty("column", column); 
       button[row][column].putClientProperty("key", key[row][column]); 
       panel[row].add(button[row][column]); 
      } 
      parent.add(panel[row]); 
     } 
     add(parent,BorderLayout.SOUTH); 
    } 

    public class MyKeyListener implements KeyListener(){ 


    @Override 
    public void keyPressed(KeyEvent e) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void keyReleased(KeyEvent e) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void keyTyped(KeyEvent e) { 
     // TODO Auto-generated method stub 

    } 
    } 
} 

回答

1

的問題就在這裏:

public class MyKeyListener implements KeyListener(){ 

應該

public class MyKeyListener implements KeyListener { 

沒有括號。

+0

是的你是對的!但爲什麼呢! –

+0

括號告訴編譯器(和IDE)你試圖引用一個方法。接口不是一種方法,因此需要在不帶()的情況下調用。 – Gliptal