0
在我的應用程序中,我需要從用戶獲得1和9之間的響應。我正在使用JTextField
來獲得輸入。然而,當按下按鈕時,用戶JTextField
變得無響應。下面是一個剝離下來的例子問題:無響應的JTextField
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
public class InputTest {
private JTextField inputBox;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new InputTest();
}
});
} // end main()
public InputTest() { // constructor
JFrame f = new JFrame("Input Test");
f.setBounds(100, 100, 450, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
JLabel label = new JLabel("Enter an integer:");
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
label.setBounds(109, 120, 109, 30);
f.add(label);
inputBox = new JTextField();
inputBox.setBounds(259, 120, 30, 30);
f.add(inputBox);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Pressed");
}
});
button.setMnemonic('B');
button.setBounds(166, 198, 78, 23);
f.add(button);
f.setVisible(true);
inputBox.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c < '!' || e.getModifiers() > 0)
return;
if (c < '1' || c > '9') {
JOptionPane.showMessageDialog(null, c
+ " is not an integer");
// inputBox.setText("error");
System.out.println("You typed a non-integer");
} else
System.out.println("You typed " + c);
inputBox.setText(null);
}
});
} // end constructor
} // end class
Java的圖形用戶界面可能需要在多個平臺上工作,在不同的屏幕分辨率和使用不同的PLAFs。因此,它們不利於組件的準確放置。爲了組織強大的GUI,請改爲[使用佈局管理器](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html)或[它們的組合](http:// stackoverflow.com/a/5630271/418556),以及[white space]的佈局填充和邊框(http://stackoverflow.com/q/17874717/418556)。 –