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

标签 java jframe 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();
    }

  }

最佳答案

您尚未添加 checkHandler 作为 checkJB 的操作监听器。尝试:

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

关于java - 缺少一些东西来完成我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22950569/

相关文章:

java - 从 JTable 拖放到 JLayeredPane

java - 为什么 getMetadata() 不适用于 javafx 中的 m4a 文件?

java - 如何使用 Netbeans 和 Maven 将 Web 片段打包到 jar 中

java - 为什么这个 JPanel 实例的大小不正确?

algorithm - 添加最少数量的字符以构成回文

java - HashSet 没有意识到两个对象是相同的

java - 使用PaintComponent在Panel之外绘图

java - 更改 GridLayout 元素的颜色

java - 我怎样才能让我的程序检查一个单词是否是回文,无论用户输入的大小写如何

c++ - 基于堆栈的回文检查器