package TryOut;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TryOut1 extends JFrame {
private static final long serialVersionUID = 1L;
private String QualityAsEntered = new String();
private JTextField QualityEntry = null; // Quality
private javax.swing.JPanel jContentPane = null;
public static void main(String[] args) {
TryOut1 frame = new TryOut1();
frame.setVisible(true);
}
// constructor
public TryOut1() {
super();
initialize();
}
private void initialize() {
this.setSize(350, 250);
this.setContentPane(getJContentPane());
this.setTitle("Customer Data Entry");
}
private JPanel getJContentPane() {
jContentPane = new JPanel();
jContentPane.setLayout(new java.awt.FlowLayout());
jContentPane.add(makeLabel(" Quality *", 100, 20));// Quality
jContentPane.add(getQualityEntry(), null);//Quality
return jContentPane;
}
// build labels
private JLabel makeLabel(String labelName, int width, int height) {
JLabel label = new JLabel();
label.setText(labelName);
label.setPreferredSize(new Dimension(width, height));
return label;
}
private JTextField getQualityEntry() {
QualityEntry = new JTextField();
QualityEntry.setPreferredSize(new Dimension(200, 20));
QualityEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
QualityAsEntered = QualityEntry.getText().trim();
QualityEntry.setText(QualityAsEntered);
if (QualityAsEntered.length() != 0)
System.out.println(QualityAsEntered);
}
});
return QualityEntry;
}
}
它會要我打Quality, 我的最大問題是, 點才能把 Quality 要求只輸入數量(如 int), 不能輸入 String.
謝謝幫忙
更新1:
我嘗試過將 private String QualityAsEntered = new String(); 轉做 private Int QualityAsEntered = new int(); 但唔得... 我係java 初學者, 請指教
更新2:
To Ninja: 謝謝你的解答 那我把 private String QualityAsEntered = new String(); 轉做 private Int QualityAsEntered = new int(); 的想法是錯的嗎? 依你的想法, 我是不能限制 input 只能輸入數字, 但我可以用某方法 去check input 是否數字 .. 對嗎? 因為我是學 C++的, 請問check input 是否數字, 可否用 if loop.還有 check JTextField 是否類似 javax.swing.InputVerifier (聽說的) 謝謝你