问题描述
我是Java的新手,正在开发一个小项目.我正在编写一个程序,其中用户必须自己注册.我的选项卡式窗格中有3个不同的选项卡.我希望能够第一个窗格上的禁用 下一个按钮,使用户无法 text 字段均已填充,否则strong>继续继续到窗格2.我一直在网上搜索,发现了各种示例,但它们都无法在运行时正常工作.
I'm new to Java and developing a small project. I'm making a program where the user has to register themselves. I have 3 different tabs on my Tabbed Pane. I want to be able to disable the next button on the first pane making it impossible for the user to continue to pane 2 unless all the text
fields on pane 1 have been filled. I have been Searching online and found various examples but none of them would work in run time.
我正在使用Netbeans.
I am using Netbeans.
private void txtFirstNameActionPerformed(java.awt.event.ActionEvent evt) {
if(txtFirstName.getText().trim().length() > 0)
btnNext1.setEnabled(true);
else
btnNext1.setEnabled(false);
}
推荐答案
为窗格上所有文本字段创建一个 List
:
Create a List
of all the text fields on your pane:
List<JTextField> list = new ArrayList<>();
将所有文本字段添加到该列表.
Add all your text fields to that list.
然后,创建一个通用的 DocumentListener
来侦听文本更改事件,并且每次发生文本更新时,请扫描所有文本字段以查看是否已全部填充:
Then, create a universal DocumentListener
that listens for text change events, and every time a text update happens, scan through all your text fields to see if they have all been filled:
DocumentListener listener = new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) { changedUpdate(e); }
@Override
public void insertUpdate(DocumentEvent e) { changedUpdate(e); }
@Override
public void changedUpdate(DocumentEvent e) {
boolean canEnable = true;
for (JTextField tf : list) {
if (tf.getText().isEmpty()) {
canEnable = false;
}
}
btnNext1.setEnabled(canEnable);
}
};
并将该 listener
添加到列表中您拥有的每个文本字段中:
And add that listener
to every text field you have in the list:
for (JTextField tf : list) {
tf.getDocument().addDocumentListener(piecesListener);
}
这篇关于禁用Java中的按钮,直到所有字段都填满的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!