我目前正在尝试向JTextField添加一个事件,具体取决于两个复选框,但它似乎无法正常工作。
txKids是我想要根据这两个复选框的状态修改的JTextField,cbChildrenY和cbChildrenN。
这是我对这些组件的代码;
private JCheckBox getCbChildrenY() {
if (cbChildrenY == null) {
cbChildrenY = new JCheckBox("Children (Y)");
cbChildrenY.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
showMansions();
}
});
cbChildrenY.setSelected(true);
}
return cbChildrenY;
}
private JCheckBox getCbChildrenN() {
if (cbChildrenN == null) {
cbChildrenN = new JCheckBox("Children (N)");
cbChildrenN.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
showMansions();
}
});
cbChildrenN.setSelected(true);
}
return cbChildrenN;
}
private JTextField getTxKids() {
if (txKids == null) {
txKids = new JTextField();
txKids.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ((getCbChildrenN().isSelected() == true) && (getCbChildrenY().isSelected() == false)){
getTxKids().setEnabled(false);
getTxKids().setEditable(false);
}
}
});
txKids.setColumns(10);
txKids.setBounds(203, 350, 78, 20);
}
return txKids;
}
希望你能提前帮助我。
答案 0 :(得分:1)
单击复选框时应该处理该操作。请参阅下面的代码。
private JCheckBox getCbChildrenY() {
if (cbChildrenY == null) {
cbChildrenY = new JCheckBox("Children (Y)");
cbChildrenY.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
showMansions();
handleTxKids();
}
});
cbChildrenY.setSelected(true);
}
return cbChildrenY;
}
private JCheckBox getCbChildrenN() {
if (cbChildrenN == null) {
cbChildrenN = new JCheckBox("Children (N)");
cbChildrenN.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
showMansions();
handleTxKids();
}
});
cbChildrenN.setSelected(true);
}
return cbChildrenN;
}
private JTextField getTxKids() {
if (txKids == null) {
txKids = new JTextField();
txKids.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something.
});
txKids.setColumns(10);
txKids.setBounds(203, 350, 78, 20);
}
return txKids;
}
private void handleTxKids() {
if ((getCbChildrenN().isSelected() == true) && (getCbChildrenY().isSelected() == false)){
getTxKids().setEnabled(false);
} else {
getTxKids().setEnabled(true);
}
}