//这是我的代码
String str = "";
private void jTextField1KeyPressed (java.awt.event.KeyEvent evt) {
char ch=evt.getKeyChar();
if(Character.isDigit(ch)
str += ch;
jLabel2.setText(str);
}
}
答案 0 :(得分:1)
DocumentListener
代替KeyListener
,它可以检测用户何时将文字粘贴到字段中和/或以编程方式更改Document
后,从字段中获取文本并设置标签文本。当信息已在字段/ String
中可用时,尝试更新另一个Document
几乎没有任何好处。如果你“真的”必须使用StringBuilder
代替它,它会更有效并且是可变的例如
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel mirrorLabel;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JTextField field = new JTextField(10);
field.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
@Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
@Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e.getDocument());
}
protected void updateLabel(Document document) {
try {
mirrorLabel.setText(document.getText(0, document.getLength()));
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
add(field, gbc);
mirrorLabel = new JLabel(" ");
add(mirrorLabel, gbc);
}
}
}