简单Java程序中的NullPointerException

时间:2014-08-28 18:29:01

标签: java nullpointerexception

我正在创建一个简单的Java程序,它将计算使用箭头键成功环绕2x2表的次数(在Excel电子表格中使用旧的无意识习惯)。到目前为止,我已经构建了基本结构,但是我遇到了空指针异常。

程序的当前状态实现了KeyListener,用于在按下键时更改JTextField的背景颜色。但是,我在KeyPressed()方法中不断收到NullPointerException。

有问题的JTextField在主类中声明并在构造函数中初始化。我无法弄清楚为什么这些对象不能被主类的方法KeyPressed()修改而没有NullPointerException。任何帮助将不胜感激。

package arrows;


import javax.swing.*;

package arrows;


import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

/**
 *
 * @author christian.a.murphy
 */
public class Arrows implements KeyListener {

   JPanel windowContent;
   JPanel buttonsPanel;

   JTextField one;
   JTextField two;
   JTextField three;
   JTextField four;



   Arrows() {

          windowContent= new JPanel();
          buttonsPanel = new JPanel();
          JTextField one = new JTextField();
          JTextField two = new JTextField();
          JTextField three = new JTextField();
          JTextField four= new JTextField();

         BorderLayout bl = new BorderLayout(); 
         windowContent.setLayout(bl);

         GridLayout gl = new GridLayout(2,2); 
         buttonsPanel.setLayout(gl);

         buttonsPanel.add(one); 
         buttonsPanel.add(two); 
         buttonsPanel.add(three); 
         buttonsPanel.add(four); 

//         one.setEditable(true);
//         two.setEditable(false);
//         three.setEditable(false);
//         four.setEditable(false);

        windowContent.add("South",buttonsPanel) ;

       JFrame frame = new JFrame("Arrows");
       frame.setContentPane(windowContent);
       frame.setSize(400,400);
       buttonsPanel.setSize(300,300);
       frame.setVisible(true);

       windowContent.addKeyListener(this);
       one.addKeyListener(this);
       two.addKeyListener(this);
       three.addKeyListener(this);
       four.addKeyListener(this);

//       frame.pack();

//       one.setBackground(Color.yellow);
   }

     /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {

    }

    /** Handle the key-pressed event from the text field. */
    public void keyPressed(KeyEvent e) {

        int characterkd = e.getKeyCode();
        System.out.println("Key Pressed is " + characterkd) ;
        one.setText("d");
    }


    /** Handle the key-released event from the text field. */
    public void keyReleased(KeyEvent e) {

    }

    public void changeColor() {
       one.setText("d");
    }

    public static void main(String[] args) {
          new Arrows();
    }



}

0 个答案:

没有答案