1 回答

TA貢獻1798條經驗 獲得超7個贊
即使 JTextField 是可編輯的,您通過按 del 鍵得到的聲音也會出現,并且是對按下的鍵的操作系統相關的響應。解決這個問題的方法是防止 del 鍵注冊它已被按下,而做到這一點的方法是使用鍵綁定使 del 鍵在 GUI 中沒有響應——給出一個不執行任何操作的響應當文本字段具有焦點時按下 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);
});
}
}
側面建議:
避免將 KeyListeners 與文本組件一起使用,因為這會導致不希望的和不標準的行為。請改用 DocumentListeners 和 DocumentFilters。
避免設置文本組件的邊界,因為這也會導致不希望的和非標準的行為,尤其是對于放置在 JScrollPanes 中時不顯示滾動條的 JTextAreas。而是設置文本組件的屬性
添加回答
舉報