方法FourOfAKind应该测试4个JTextField,并检查它们是否彼此相等。每个JTextField除外一个数字。当我按5555 ex时,当我按下ButtonListener时,布尔方法FourOfAKind不会响应,即使它返回false,也不会响应。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 */
public class MyPanel extends JPanel
{
    private JLabel inputLabel, outputLabel;
    private JButton button;
    private JTextField digit1, digit2, digit3, digit4;

    public MyPanel()
    {
        inputLabel = new JLabel ("Enter four one digit numbers between zero and 9");
        button = new JButton ("Result");
        outputLabel = new JLabel ("---");

        digit1 = new JTextField(1);
        digit1.addActionListener (new ButtonListener());

        digit2 = new JTextField(1);
        digit2.addActionListener (new ButtonListener());

        digit3 = new JTextField(1);
        digit3.addActionListener (new ButtonListener());

        digit4 = new JTextField(1);
        digit4.addActionListener (new ButtonListener());

        add(inputLabel);
        add(digit1);
        add(digit2);
        add(digit3);
        add(digit4);
        add(button);
        add(outputLabel);

        setPreferredSize(new Dimension(300,100));
        setBackground(Color.yellow);
    }

    private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent even)
        {
            int num1, num2, num3, num4;

            String text = digit1.getText();
            num1 = Integer.parseInt(text);

            String text2 = digit2.getText();
            num2 = Integer.parseInt(text2);

            String text3 = digit3.getText();
            num3 = Integer.parseInt(text3);

            String text4 = digit4.getText();
            num4 = Integer.parseInt(text4);

            if (fourOfAKind(num1, num2, num3, num4))
            outputLabel.setText ("four of a kind");
        }
    }

    public boolean fourOfAKind(int a, int b, int c, int d)
    {
        return (a == b && b == c && c == d);
    }
}

最佳答案

仅将ButtonListener添加到按钮中,以便在您按下按钮并触发事件时将其激活。

您可以删除'digitN.addActionListener(new ButtonListener());`,而是使用:

button.addActionListener(new ButtonListener());


这样,您正在指示Java监听被按下的按钮,而不是文本字段(在按下Enter键时将触发它)

关于java - 将多个JTextFields传递给 boolean 方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29869724/

10-11 21:59