检查JTextfield不为空

时间:2014-11-02 13:41:37

标签: java swing

我的程序在按下按钮时从多个文本字段创建一个对象。但是,JTextField名为' nameField'这不应该是空的。如果是'nameField'是空的然后我想打印一条错误消息,告诉用户文本框是空的。这段代码在我的actionPerformed函数的第一部分。

import javax.swing.*;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FuelStationInterface extends JFrame implements ActionListener {

    private JLabel totalPriceLabel = new JLabel("Amount to pay = 0.00 GBP", SwingConstants.CENTER);
    private JLabel totalItemsLabel = new JLabel("Items = 0", SwingConstants.CENTER);
    private JPanel topPanel = new JPanel();

    private Container contentPane;

    private double totalPrice = 0;
    private int totalItems = 0;

    private boolean breakSwitch = true;
    private PurchaseVolume volumeNumber = null;
    private PurchaseNumber unitNumber = null;
    private int number = 0;
    private int price = 0;

    private String outputText = "";
    private JTextArea outputArea = new JTextArea(outputText);
    private JTextArea errorReportField = new JTextArea("");

    private JPanel inputPanel = new JPanel();

    private JLabel nameLabel = new JLabel("Item Name");
    private JLabel numberLabel = new JLabel("Number of units (or Volume in L)");
    private JLabel priceLabel = new JLabel("Price per unit (or L) in pence");

    private JTextField nameField = new JTextField(10);
    private JTextField numberField = new JTextField(10);
    private JTextField priceField = new JTextField(10);

    private JButton addVolumeButton = new JButton("Add by Volume");
    private JButton addNumberButton = new JButton("Add by number of units");

    public FuelStationInterface() {
        super("Fuel station shop");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        outputArea.setEditable(false);
        outputArea.setRows(30);
        JScrollPane scrollPanel = new JScrollPane(outputArea);
        scrollPanel.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        errorReportField.setEditable(false);
        errorReportField.setRows(3);

        addVolumeButton.addActionListener(this);
        addNumberButton.addActionListener(this);

        inputPanel.setLayout(new FlowLayout());
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);
        inputPanel.add(numberLabel);
        inputPanel.add(numberField);
        inputPanel.add(priceLabel);
        inputPanel.add(priceField);
        inputPanel.add(addVolumeButton);
        inputPanel.add(addNumberButton);

        topPanel.setLayout(new GridLayout(0, 2));
        topPanel.add(totalPriceLabel);
        topPanel.add(totalItemsLabel);

        contentPane = getContentPane();
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
        contentPane.add(topPanel);
        contentPane.add(scrollPanel);
        contentPane.add(errorReportField);
        contentPane.add(inputPanel);

        pack();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        while (breakSwitch = true) {
            if (nameField.getText().isEmpty()) {
                errorReportField.setText("name error");
                break;
            }
            try {
                price = Integer.parseInt(priceField.getText());
            } catch (NumberFormatException exception) {
                errorReportField.setText("price error");
                priceField.setText("");
                break;
            }
            try {
                number = Integer.parseInt(numberField.getText());
            } catch (NumberFormatException exception) {
                errorReportField.setText("number error");
                numberField.setText("");
                break;
            }
            if (e.getSource() == addVolumeButton) {
                volumeNumber = new PurchaseVolume(nameField.getText(), number, price);
                outputArea.append(volumeNumber.toString() + "\n");
                nameField.setText("");
                priceField.setText("");
                numberField.setText("");
                totalPrice += volumeNumber.getPrice() * volumeNumber.getVolume();
                totalItems += 1;
                totalPriceLabel.setText("Amount to pay = " + Double.toString(totalPrice) + " GBP");
                totalItemsLabel.setText("Items = " + Integer.toString(totalItems));
            }
            if (e.getSource() == addNumberButton) {
                unitNumber = new PurchaseNumber(nameField.getText(), number, price);
                outputArea.append(unitNumber.toString() + "\n");
                nameField.setText("");
                priceField.setText("");
                numberField.setText("");
                totalPrice += unitNumber.getPrice() * unitNumber.getNumber();
                totalItems += unitNumber.getNumber();
                totalPriceLabel.setText("Amount to pay = " + Double.toString(totalPrice) + " GBP");
                totalItemsLabel.setText("Items = " + Integer.toString(totalItems));
            }
            errorReportField.setText("");
        }
    }

}

按下按钮后,即使nameField文本字段输入了有效字符串,也会出现空字符串错误,为什么会这样?

1 个答案:

答案 0 :(得分:2)

您的问题是while循环的内容:

while (breakSwitch = true) {
    if (nameField.getText().isEmpty()) {
        errorReportField.setText("name error");
        break;
    }
    // stuff omitted
    if (e.getSource() == addVolumeButton) {
        // stuff omitted
        nameField.setText("");
        // stuff omitted
    }
    if (e.getSource() == addNumberButton) {
        // stuff omitted
        nameField.setText("");
        // stuff omitted
    }
    errorReportField.setText("");
}

首先:你已经创建了一个带有赋值而不是布尔比较的循环。 现在问题是:如果e.getSource()addVolumeButtonaddNumberButton,那么您将删除nameField的内容。在循环的下一次迭代中,您将测试nameField.getText().isEmpty()是否返回true now 。您现在将获得错误并退出循环。

如何解决问题?我建议考虑那个循环,因为我相对肯定,没有必要在那里循环。

没有循环的actionPerformed方法版本可能如下所示:

@Override
public void actionPerformed(ActionEvent e) {
    if (nameField.getText().isEmpty()) {
        errorReportField.setText("name error");
        return; // error occured; exit the method early
    }
    try {
        price = Integer.parseInt(priceField.getText());
    } catch (NumberFormatException exception) {
        errorReportField.setText("price error");
        priceField.setText("");
        return; // error occured; exit the method early
    }
    try {
        number = Integer.parseInt(numberField.getText());
    } catch (NumberFormatException exception) {
        errorReportField.setText("number error");
        numberField.setText("");
        return; // error occured; exit the method early
    }
    if (e.getSource() == addVolumeButton) {
        // omitted
    }
    if (e.getSource() == addNumberButton) {
        // omitted
    }
    errorReportField.setText("");
}

如果发生错误,此版本使用代码字return;退出当前方法。