不幸的是,我無法為 JTextField 或 JTextField(都嘗試過)打開 .setEnable()。它保持灰色,因此用戶無法鍵入。請幫幫我。
詳細資訊:taTwo 可以是 JTextField 或 JTextArea,但我嘗試的任何一個都無法啟用。它應該為 A 禁用,但應該為 B 啟用,因此如果用戶選擇 A,他/她不能在 taTwo 欄位中輸入值,但如果用戶選擇 B,他/她可以在 taTwo 中寫入。
方法如下:
public void btnAddtreeAction() {
this.btnAddtree.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel dialogPanel = new JPanel();
dialogPanel.setPreferredSize(new Dimension(60,60));
String[] choices = {"A", "B"};
JComboBox<String> cb = new JComboBox<String>(choices);
JTextArea taOne = new JTextArea(1,30);
JTextField taTwo = new JTextField();
taTwo.setEnabled(false);
Object[] myObject = {"Options:", cb,
"Input first:", taOne,
"Input second:", taTwo};
JOptionPane.showConfirmDialog(frame, myObject, "Form", JOptionPane.OK_CANCEL_OPTION);
if (cb.getSelectedItem().toString().equals("A")) {
//something will happen here
} else if (cb.getSelectedItem().toString().equals("B")) {
taTwo.setEnabled(true);
//something will happen here
}
}
});
}
uj5u.com熱心網友回復:
在您的actionPerformed方法中,您正在創建一個沒有添加到 GUI 中的新的。 JTextField我假設您taTwo在未發布的代碼中有另一個名為 somehere 的變數。您沒有在方法內更改該變數actionPerformed。嘗試洗掉這行代碼:
JTextField taTwo = new JTextField();
uj5u.com熱心網友回復:
如果我正確理解您的問題,您需要將您的啟用/禁用代碼移動到另一個ActionListener并將其添加到您的組合框中。像這樣的東西:
public void btnAddtreeAction() {
this.btnAddtree.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel dialogPanel = new JPanel();
dialogPanel.setPreferredSize(new Dimension(60,60));
String[] choices = {"A", "B"};
JComboBox<String> cb = new JComboBox<String>(choices);
JTextArea taOne = new JTextArea(1,30);
JTextField taTwo = new JTextField();
taTwo.setEnabled(false);
cb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (cb.getSelectedItem().toString().equals("A")) {
taTwo.setEnabled(false);
//something will happen here
} else if (cb.getSelectedItem().toString().equals("B")) {
taTwo.setEnabled(true);
//something will happen here
}
}
});
Object[] myObject = {"Options:", cb,
"Input first:", taOne,
"Input second:", taTwo};
JOptionPane.showConfirmDialog(frame, myObject, "Form", JOptionPane.OK_CANCEL_OPTION);
}
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/477991.html
