文本字段事件、规则等
Text field events, rules etc
我有一些关于 JTextField
的问题。
- NetBeans 中
JTextField
的 TextChanged
事件替换了哪个事件?
- 当 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 内容时侦听它的变化,请考虑向 JTextField 的文档添加一个 DocumentListener。
如果您需要将输入限制为数字或使用任何其他类型的限制,请通过 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();
}
});
}
}
编辑:您在评论中声明,
Read whole code, much informative , however way too big if i want to implement for more then 30 textfields .. I have solved the problem , now pasting the solution.
好的,所以下面的新代码添加了来自 100 JTextFields 的数字,同样对原始代码进行了最小的更改。要查看哪种解决方案最有效,要查看哪种解决方案 scales 最好,请尝试更改您当前的解决方案以处理类似的问题:
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();
}
});
}
}
if (TutionFees.getText().equals(""))
tf=0;
else
tf=Integer.parseInt(TutionFees.getText());
if (LibraryFees.getText().equals(""))
lf=0;
else
lf=Integer.parseInt(LibraryFees.getText());
if (OtherFees.getText().equals(""))
of=0;
else
of=Integer.parseInt(OtherFees.getText());
if (UDFees.getText().equals(""))
df=0;
else
df=Integer.parseInt(UDFees.getText());
if (USFees.getText().equals(""))
sf=0;
else
sf=Integer.parseInt(USFees.getText());
if(SecurityFees.getText().equals(""))
sd=0;
else
sd=Integer.parseInt(SecurityFees.getText());
total=tf+lf+of+df+sf+sd;
TotalFee.setText(""+total);
我有一些关于 JTextField
的问题。
- NetBeans 中
JTextField
的TextChanged
事件替换了哪个事件? - 当 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 内容时侦听它的变化,请考虑向 JTextField 的文档添加一个 DocumentListener。
如果您需要将输入限制为数字或使用任何其他类型的限制,请通过 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();
}
});
}
}
编辑:您在评论中声明,
Read whole code, much informative , however way too big if i want to implement for more then 30 textfields .. I have solved the problem , now pasting the solution.
好的,所以下面的新代码添加了来自 100 JTextFields 的数字,同样对原始代码进行了最小的更改。要查看哪种解决方案最有效,要查看哪种解决方案 scales 最好,请尝试更改您当前的解决方案以处理类似的问题:
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();
}
});
}
}
if (TutionFees.getText().equals(""))
tf=0;
else
tf=Integer.parseInt(TutionFees.getText());
if (LibraryFees.getText().equals(""))
lf=0;
else
lf=Integer.parseInt(LibraryFees.getText());
if (OtherFees.getText().equals(""))
of=0;
else
of=Integer.parseInt(OtherFees.getText());
if (UDFees.getText().equals(""))
df=0;
else
df=Integer.parseInt(UDFees.getText());
if (USFees.getText().equals(""))
sf=0;
else
sf=Integer.parseInt(USFees.getText());
if(SecurityFees.getText().equals(""))
sd=0;
else
sd=Integer.parseInt(SecurityFees.getText());
total=tf+lf+of+df+sf+sd;
TotalFee.setText(""+total);