我正在开发我的回文程序并将其实现到 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/