我对JTextField
有一些疑问。
哪个事件已将NetBeans中的TextChanged
事件替换为JTextField
事件?
当textField中的Value更改时,我希望完成其总和并将其添加到Total
Fee中。同样,我正在使用此代码,但无法正常工作。
码:
private void TutionFeesKeyTyped(java.awt.event.KeyEvent evt) {
TotalFee.setText(""+Integer.parseInt(TutionFees.getText())+
Integer.parseInt(LibraryFees.getText())+Integer.parseInt(UDFees.getText())+
Integer.parseInt(USFees.getText())+Integer.parseInt(OtherFees.getText())+
Integer.parseInt(SecurityFees.getText())) ;
// TODO add your handling code here:
}
基本上我正在使用:
Integer.parseInt()
将文本转换为数字数据,以便我可以添加它们..
我正在使用
KeyTyped
事件,但是它不允许在文本字段中输入任何内容。 最佳答案
切勿使用KeyListener进行此类操作,因为它会弄乱JTextField的基本功能。要在输入JTextField的内容时侦听其变化,请考虑将DocumentListener添加到JTextField的Document中。
而且,如果您需要将输入限制为数字或使用任何其他类型的限制,请通过DocumentFilter设置文档的过滤器(请记住首先将其转换为PlainDocument),或者使用JFormattedTextField或使用(我最喜欢的)JSpinner。
例如。,
Document doc = myTextField.getDocument();
doc.addDocumentListener(new DocumentListener() {
void insertUpdate(DocumentEvent e) {
// ... code to check document change here
}
void removeUpdate(DocumentEvent e){
// ... code to check document change here
}
void changedUpdate(DocumentEvent e){
// ... code to check document change here
}
});
例如,一起使用DocumentListener和DocumentFilter,第一个添加数字,第二个确保只输入数字。
现在编辑以处理15个JTextField:
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
@SuppressWarnings("serial")
public class DocListenerEg extends JPanel {
private static final int FIELD_COUNT = 15;
private static final int COLS = 6;
private List<JTextField> fieldList = new ArrayList<>();
private JTextField sumField = new JTextField(COLS);
public DocListenerEg() {
sumField.setFocusable(false);
DocListener docListener = new DocListener();
DocFilter docFilter = new DocFilter();
for (int i = 0; i < FIELD_COUNT; i++) {
JTextField textField = new JTextField(COLS);
Document doc = textField.getDocument();
doc.addDocumentListener(docListener);
((PlainDocument) doc).setDocumentFilter(docFilter);
add(textField);
fieldList.add(textField);
String labelText = i < (FIELD_COUNT - 1) ? "+" : "=";
add(new JLabel(labelText));
}
add(sumField);
}
private class DocFilter extends DocumentFilter {
private boolean checkIfIntegerOrEmpty(String text) {
if (text.isEmpty()) {
return true;
} else {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
}
}
return false;
}
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
String preText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(preText);
sb.insert(offset, string);
if (checkIfIntegerOrEmpty(sb.toString())) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
String preText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(preText);
int end = offset + length;
sb.replace(offset, end, "");
if (checkIfIntegerOrEmpty(sb.toString())) {
super.remove(fb, offset, length);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
String preText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(preText);
int end = offset + length;
sb.replace(offset, end, text);
if (checkIfIntegerOrEmpty(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
}
}
private class DocListener implements DocumentListener {
private void textChanged() {
int sum = 0;
for (JTextField jTextField : fieldList) {
String text = jTextField.getText().trim();
if (!text.isEmpty()) {
sum += Integer.parseInt(text);
}
}
sumField.setText(String.valueOf(sum));
}
@Override
public void insertUpdate(DocumentEvent e) {
textChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
textChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
textChanged();
}
}
private static void createAndShowGui() {
DocListenerEg mainPanel = new DocListenerEg();
JFrame frame = new JFrame("DocListenerEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
编辑:您发表评论,
阅读完整的代码,内容丰富,但是如果我想为30个以上的文本字段实现,则太大了。我已经解决了问题,现在粘贴了解决方案。
好的,因此下面的此新代码将100个JTextFields中的数字相加,并且对原始代码的更改最少。若要查看哪种解决方案最有效,查看哪种解决方案最有效,请尝试更改当前解决方案以处理类似问题:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
@SuppressWarnings("serial")
public class DocListenerEg extends JPanel {
private static final int COLS = 6;
private static final int GAP = 5;
private static final int SIDE = 10;
private List<JTextField> fieldList = new ArrayList<>();
private JTextField sumField = new JTextField(COLS);
public DocListenerEg() {
sumField.setFocusable(false);
JPanel additionFieldPanel = new JPanel(new GridLayout(SIDE, SIDE, GAP, GAP));
additionFieldPanel.setBorder(BorderFactory.createTitledBorder("Numbers To Add"));
DocListener docListener = new DocListener();
DocFilter docFilter = new DocFilter();
for (int i = 0; i < SIDE * SIDE; i++) {
JTextField textField = new JTextField(COLS);
Document doc = textField.getDocument();
doc.addDocumentListener(docListener);
((PlainDocument) doc).setDocumentFilter(docFilter);
fieldList.add(textField);
additionFieldPanel.add(textField);
}
JPanel sumPanel = new JPanel();
sumPanel.add(new JLabel("Sum Of All Numbers:"));
sumPanel.add(sumField);
setLayout(new BorderLayout());
add(additionFieldPanel, BorderLayout.CENTER);
add(sumPanel, BorderLayout.PAGE_END);
}
private class DocFilter extends DocumentFilter {
private boolean checkIfIntegerOrEmpty(String text) {
if (text.isEmpty()) {
return true;
} else {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
}
}
return false;
}
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
String preText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(preText);
sb.insert(offset, string);
if (checkIfIntegerOrEmpty(sb.toString())) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
String preText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(preText);
int end = offset + length;
sb.replace(offset, end, "");
if (checkIfIntegerOrEmpty(sb.toString())) {
super.remove(fb, offset, length);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
String preText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(preText);
int end = offset + length;
sb.replace(offset, end, text);
if (checkIfIntegerOrEmpty(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
}
}
private class DocListener implements DocumentListener {
private void textChanged() {
int sum = 0;
for (JTextField jTextField : fieldList) {
String text = jTextField.getText().trim();
if (!text.isEmpty()) {
System.out.println(text);
sum += Integer.parseInt(text);
}
}
sumField.setText(String.valueOf(sum));
}
@Override
public void insertUpdate(DocumentEvent e) {
textChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
textChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
textChanged();
}
}
private static void createAndShowGui() {
DocListenerEg mainPanel = new DocListenerEg();
JFrame frame = new JFrame("DocListenerEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}