import java.awt.*; import javax.swing.*; import java.awt.event.*; public class BackSpaceSample extends JPanel { private String word; public BackSpaceSample() { setBackground(Color.BLACK); addKeyListener(new KeyListener()); setFocusable(true); setLayout(null); word = ""; } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.WHITE); g2d.setFont(new Font("Arial", Font.BOLD, 24)); g2d.drawString(word, 100, 100); repaint(); } private class KeyListener extends KeyAdapter { public void keyTyped(KeyEvent e) { String alphabet = "abcdefghijklmnopqrstuvwxyz"; Character charac = e.getKeyChar(); for (int x = 0; x < alphabet.length(); x++) { if (charac.toString().equalsIgnoreCase("" + alphabet.charAt(x))) { word = word + e.getKeyChar(); } } } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { System.out.println("Backspace is being pressed"); // iterating action that will re-assign the string itself // but without the last character for (int x = 0; x < word.length() -1; x++) { word = word + word.charAt(x); System.out.println("What the hell?? : " + x); } } } } public static void main(String[] args) { JFrame f = new JFrame(); f.add(new BackSpaceSample()); f.setSize(400, 200); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }
im trying to perform a backspace action in a paint method, i was trying to put the logic of it in the keyPressed event, where there is a loop that will iterate according to the length of the word (minus 1) and re-assgin the characters in the string instance but without the last character, but the loop is looping forever, my first assumption was that MAYBE I DONT HAVE A keyRelease event, so what i did is incuded a keyReleased event and put the same statements, still it loops forever, my second assumption was that MAYBE i should just put the statement in the released event, still the loop is going forever, i even put a statement that will check the value of 'x' of the for-loop counter, and i saw that it just keeps on iterating, i dont know what is going on. need help again please....