gpt4 book ai didi

java - 文本字段事件、规则等

转载 作者:行者123 更新时间:2023-12-01 18:19:43 27 4
gpt4 key购买 nike

我对 JTextField 有一些疑问。

  1. 哪个事件取代了 NetBeans 中 JTextFieldTextChanged 事件?
  2. 当文本字段中的值发生更改时,我希望将其总和添加到 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 的文档中。

如果您需要将输入限制为数字或使用任何其他类型的限制,请通过 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 中的数字,同样对原始代码进行了最小的更改。要查看哪种解决方案效果最好,哪种解决方案扩展性最好,请尝试更改当前的解决方案以处理类似的问题:

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();
}
});
}
}

关于java - 文本字段事件、规则等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27977529/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com