I am trying to stop a JTextPane from receiving specific letters to insert into its text, so I can insert different letters instead without having to delete the original ones first (and having them annoyingly blink into existence for a moment anyways). My solution so far would be having the press of the key associated with any such letter set the JTextPane uneditable, then have the release set it editable again. I was going to follow this up with changing the text so my chosen alternative letter would show up – but when I tried my code without said followup to see if it would work at all, I noticed that the JTextPane stays uneditable (or maybe disappears) if I press one of the keys in question first thing before typing anything else. (This also happens if I already typed some other text but then deleted it again) Any ideas what could have gone wrong?
This is my code:
import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.SpringLayout;
import javax.swing.JTextPane;
import java.awt.Font;
import javax.swing.Action;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.KeyStroke;
class Mainclass
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
Container pane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
JTextPane line = new JTextPane();
Font font = new Font("Palatino", Font.PLAIN, 36);
line.setFont(font);
Action freeze = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
line.setEditable(false);
}
};
Action unfreeze = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
line.setEditable(true);
}
};
line.getActionMap().put("freeze", freeze);
line.getActionMap().put("unfreeze", unfreeze);
line.getInputMap().put(KeyStroke.getKeyStroke("I"), "freeze");
line.getInputMap().put(KeyStroke.getKeyStroke("J"), "freeze");
line.getInputMap().put(KeyStroke.getKeyStroke("released I"), "unfreeze");
line.getInputMap().put(KeyStroke.getKeyStroke("released J"), "unfreeze");
pane.setLayout(layout);
pane.add(line);
frame.setSize(1000, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
line.getPreferredSize();
frame.setVisible(true);
}
}
PS: I found out that the problem does not occur if I force the JTextPane to always take up some space (stretching it out across the JFrame's contentPane using my Springlayout), but I would still like to know what caused the problem in the first place.