【问题标题】:How would I make this textfield only have one correct code as an input?我如何让这个文本字段只有一个正确的代码作为输入?
【发布时间】:2014-09-09 04:28:47
【问题描述】:

我想知道如何让我的程序只接受 (1101101) 作为 JTextField txtCode 上唯一正确的输入。目前,我可以在文本字段中输入任何代码,它会显示相同的输出。

代码如下:

import java.awt.FlowLayout;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class GUI extends JFrame {

JLabel coffeeProgram;
JButton button;
JTextField txtCode;
JTextField price;
JTextField description;
JLabel outputPrice;

public GUI() {
     setLayout(new FlowLayout());
    coffeeProgram = new JLabel("Enter Code Here:");
    add(coffeeProgram);
    txtCode = new JTextField(15);
    add(txtCode);  
    button = new JButton("Submit Code");
    add(button);

       outputPrice = new JLabel(" Price:  ");
       add(outputPrice);

      JTextField price;

      CoffeeReturn objCoffee = new CoffeeReturn();

      double myPrice = objCoffee.CoffeeCode(txtCode.getText());

      price = new JTextField(15);
      add(price);

      price.setText("Price is"+myPrice);

 }
}

如果这段代码看起来有点缺乏经验,我很抱歉。我今年 15 岁,两天前开始尝试学习 Java。 这是我的程序的截图:http://gyazo.com/afe2abf5fcffa3822bd41eaea8581597

【问题讨论】:

    标签: java text input field output


    【解决方案1】:

    看看http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

    它解释了如何使用一种格式来只允许特定字符。

    【讨论】:

    • 谢谢!我会检查一下。
    【解决方案2】:

    我想您需要更改数据类型才能成功。

    参考:Why can't we use '==' to compare two float or double numbers

    您可以使用 Integer 或 String 值以您想要的方式进行比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多