[英]Enable/disable a Java swing button in relation with a combo box
当用户在组合框中更改所选项目时,如何更新按钮的状态(启用/禁用)?
该按钮具有对组合框的引用,但是组合框对按钮一无所知。
组合框不需要了解按钮。 您需要向组合框事件添加一个侦听器,如下所示:
public class ComboBoxDemo ... implements ActionListener {
. . .
petList.addActionListener(this) {
. . .
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
yourButton.setEnabled(true/false);
}
. . .
}
如果该按钮具有对组合框的引用,则该按钮可以在该组合框中注册一个动作侦听器,您可以在其中更改按钮的状态。
final JButton button = new JButton();
final JComboBox comboBox = new JComboBox();
comboBox.addActionListener( new ActionListener() {
@Override
public void actionPerformed( final ActionEvent event ) {
// Your logic to determine when to enable/disable:
final boolean enabled = comboBox.getSelectedIndex() == 0;
button.setEnabled( enabled );
}
} );
JButton
可以简单地在JComboBox
上添加其自己的ActionListener
,然后在ActionListener
根据组合框的选定项更改JButton
的状态。
我以前编写过代码,其中启用或禁用按钮取决于填充文本字段并一起选择组合框的一个项目。 在这里可能会有所帮助。
jComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jComboBoxActionPerformed(e);
}
});
...
jTextField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
public void removeUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
public void changedUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
});
jTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextFieldActionPerformed(e);
}
});
...
private void jComboBoxActionPerformed(ActionEvent e){
if(jComboBox.getSelectedIndex() == -1)
jButton.setEnabled(false);
else if(!jTextField.getText().equals(""))
jButton.setEnabled(true);
}
private void jTextFieldDocumentListener(DocumentEvent e){
if(jTextField.getText().equals("") || jComboBox.getSelectedIndex() == -1){
jButton.setEnabled(false);
}
else{
jButton.setEnabled(true);
}
}
private void jTextFieldActionPerformed(ActionEvent e){
if(jTextField.getText().equals("")){
jButton.setEnabled(false);
}
if(!(jTextField.getText().equals(""))){
jButton.setEnabled(true);
}
}
如果选择了组合框并填充了文本字段,则将启用该按钮。 否则将无法启用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.