缺少一些东西来完成我的程序

时间:2014-04-09 00:15:04

标签: java jframe palindrome

我正在研究我的palindrome程序并将其实现到JFrame中。我坚持如何在CalculateButtonHandler范围内的resultTF中显示结果。任何帮助将不胜感激。

继承我的代码:

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

public class Exercise5 extends JFrame
{
   private static final int Width = 400;
    private static final int Height = 200;

    private JLabel wordJL,resultJL;
    private JTextField wordTF,resultTF;

    private JButton checkJB,exitJB;

    private CalculateButtonHandler checkHandler;
    private ExitButtonHandler exitB;

    public Exercise5()
    {
        setTitle ("Palindrome");
        wordJL = new JLabel ("Enter a word: ", SwingConstants.RIGHT);
        resultJL = new JLabel ("Result: ", SwingConstants.RIGHT);

        wordTF = new JTextField(10);

        resultTF = new JTextField(10);

        checkJB = new JButton ("Calculate");
        checkHandler = new CalculateButtonHandler();

        exitJB = new JButton ("Exit");
        exitB = new ExitButtonHandler();
        exitJB.addActionListener (exitB);

        Container pane = getContentPane();
        pane.setLayout (new GridLayout (3,2));

        pane.add(wordJL);
        pane.add(wordTF);
        pane.add(checkJB);
        pane.add(exitJB);
        pane.add(resultJL);
        pane.add(resultTF);

        setSize(Width, Height);
        setVisible (true);
        setDefaultCloseOperation (EXIT_ON_CLOSE);
    }

    private class CalculateButtonHandler implements ActionListener
       {
      public void actionPerformed (ActionEvent e)
      {
         if(e.getSource().equals(checkJB)) {
             String pal1, pal2="";
             pal1 = wordTF.getText();
             int length = pal1.length();

             for ( int i = length - 1 ; i >= 0 ; i-- ) {
                pal2 = pal2 + pal1.charAt(i);
            }

            if (pal1.equals(pal2))
                resultTF.setText("True");
                else
                    resultTF.setText("False");


        }
      }
    }

    private class ExitButtonHandler implements ActionListener
    {
     public void actionPerformed (ActionEvent e)
     {
         System.exit(0);
        }
    }

    public static void main (String[] args){
       Exercise5 rectObject = new Exercise5();
    }

  }

1 个答案:

答案 0 :(得分:1)

您尚未将checkHandler添加为checkJB的动作监听器..尝试:

checkJB = new JButton ("Calculate");
checkHandler = new CalculateButtonHandler();
checkJB.addActionListener(checkHandler); //THIS LINE!