1 回答

TA貢獻(xiàn)1798條經(jīng)驗 獲得超7個贊
即使 JTextField 是可編輯的,您通過按 del 鍵得到的聲音也會出現(xiàn),并且是對按下的鍵的操作系統(tǒng)相關(guān)的響應(yīng)。解決這個問題的方法是防止 del 鍵注冊它已被按下,而做到這一點(diǎn)的方法是使用鍵綁定使 del 鍵在 GUI 中沒有響應(yīng)——給出一個不執(zhí)行任何操作的響應(yīng)當(dāng)文本字段具有焦點(diǎn)時按下 del 鍵。例如:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JFrame {
public Example() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// setBounds(0, 0,250,200);
// setLayout(null);
JPanel panel = new JPanel();
int gap = 40;
panel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
JTextField jTextField1 = new JTextField(20);
jTextField1.setEditable(false);
panel.add(jTextField1);
// get input and action maps to do key binding
InputMap inputMap = jTextField1.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = jTextField1.getActionMap();
// the key stroke that we want to change bindings on: delete key
KeyStroke delKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
// tell the input map to map the key stroke to a String of our choosing
inputMap.put(delKeyStroke, delKeyStroke.toString());
// map this same key String to an action that does **nothing**
actionMap.put(delKeyStroke.toString(), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// do nothing
}
});
add(panel);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> {
Example example = new Example();
example.pack();
example.setLocationRelativeTo(null);
example.setVisible(true);
});
}
}
側(cè)面建議:
避免將 KeyListeners 與文本組件一起使用,因為這會導(dǎo)致不希望的和不標(biāo)準(zhǔn)的行為。請改用 DocumentListeners 和 DocumentFilters。
避免設(shè)置文本組件的邊界,因為這也會導(dǎo)致不希望的和非標(biāo)準(zhǔn)的行為,尤其是對于放置在 JScrollPanes 中時不顯示滾動條的 JTextAreas。而是設(shè)置文本組件的屬性
添加回答
舉報