0

I am trying to write a code to create a GUI using java where after pressing a button on the keyboard, the associated button in the GUI changes it's colour. Could you please check the code as the color change isn't happening. Thank you

package controller;

import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

import java.util.Enumeration;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;


public class GUI extends JPanel implements ActionListener, KeyListener {


    boolean running = true;

    int frontKey = KeyEvent.VK_W;

    int backKey = KeyEvent.VK_S;

    int leftKey = KeyEvent.VK_A;

    int rightKey = KeyEvent.VK_D;


    static boolean backKeyPressed = false;
    static boolean frontKeyPressed = false;
    static boolean leftKeyPressed = false;
    static boolean rightKeyPressed = false;

    int listenKey = 0; 
    public JButton bFront, bBack, bLeft, bRight;

    StyledDocument instructionsText;
    public JTextPane instructions;

    public GUI() {

        setLayout(new GridBagLayout());
        this.setPreferredSize(new Dimension(400,400));
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = 0;

        c.gridwidth = 4;

        StyledDocument instructionsText = new DefaultStyledDocument();
        Style defaultStyle = instructionsText.getStyle(StyleContext.DEFAULT_STYLE);
        StyleConstants.setAlignment(defaultStyle, StyleConstants.ALIGN_CENTER);

        try {
            instructionsText.insertString(0, "Control the Robot using the keyboard.\n Change the key bindings by clicking the buttons below.", null);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }

        instructions = new JTextPane(instructionsText);
        instructions.setFocusable(false);

        add(instructions,c);


        bFront = new JButton("Forward key: " + KeyEvent.getKeyText(frontKey));
        bFront.setActionCommand("forward");
        bFront.addActionListener(this);
        bFront.setFocusable(false);


        c.gridwidth = 1;
        c.gridx = 1;
        c.gridy = 1;
        add(bFront,c);


        bBack = new JButton("Backward key: " + KeyEvent.getKeyText(backKey));
        bBack.setActionCommand("backward");
        bBack.addActionListener(this);
        bBack.setFocusable(false);

        c.gridx = 1;
        c.gridy = 4;
        add(bBack,c);

        bLeft = new JButton("Left key: " + KeyEvent.getKeyText(leftKey));
        bLeft.setActionCommand("left");
        bLeft.addActionListener(this);
        bLeft.setFocusable(false);

        c.gridx = 0;
        c.gridy = 3;
        add(bLeft,c);


        bRight = new JButton("Right key: "+ KeyEvent.getKeyText(rightKey));
        bRight.setActionCommand("right");
        bRight.addActionListener(this);
        bRight.setFocusable(false);

        c.gridx = 3;
        c.gridy = 3;
        add(bRight,c);

        setFocusable(true);
        addKeyListener(this);

    }

     public static void main(String arg[]) {
         // TODO Auto-generated method stub

         //Create and show the GUI
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() {
             createAndShowGUI();             
            }
        });  
    }

     private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Telepresence Robot Controller");


        frame.setLocationRelativeTo(null);
        //Tell the program to exit when the GUI is closed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

        final GUI gui = new GUI(); //create the GUI
        gui.setOpaque(true); //Set it to visible
        frame.setContentPane(gui); //attach it to the Jframe

        //Display the window.
        frame.pack();
        frame.setVisible(true);
     }


    @Override
    public void actionPerformed(ActionEvent e) {

        if(e.getActionCommand().equals("forward")) {
            listenKey = 1;
        } else if(e.getActionCommand().equals("backward")) {
            listenKey = 2;
        } else if(e.getActionCommand().equals("left")) {
            listenKey = 3;
        } else if(e.getActionCommand().equals("right")) {
            listenKey = 4;
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub

        if(listenKey == 0) 
            if(e.getKeyCode() == frontKey) {
                bFront.setBackground(Color.yellow);
                frontKeyPressed = true;
            } else if(e.getKeyCode() == backKey) {
                bBack.setBackground(Color.yellow);
                backKeyPressed = true;
            } else if(e.getKeyCode() == leftKey) {
                bLeft.setBackground(Color.yellow);
                leftKeyPressed = true;
            } else if(e.getKeyCode() == rightKey) {
                bRight.setBackground(Color.yellow);
                rightKeyPressed = true;
            } 
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        switch(listenKey) {

            case 1:
                frontKey = e.getKeyCode();
                bFront.setText("Forward key: " + KeyEvent.getKeyText(frontKey));
                listenKey = 0;
                break;

            case 2:

                backKey = e.getKeyCode();
                bBack.setText("Backward key: " + KeyEvent.getKeyText(backKey));
                listenKey = 0;
                break;

            case 3:
                leftKey = e.getKeyCode();
                bLeft.setText("Left key: " + KeyEvent.getKeyText(leftKey));
                listenKey = 0;
                break;

            case 4:
                rightKey = e.getKeyCode();
                bRight.setText("Right key: " + KeyEvent.getKeyText(rightKey));
                listenKey = 0;
                break;

            default:
                if(e.getKeyCode() == frontKey) {
                    bFront.setBackground(Color.yellow);
                    frontKeyPressed = false;
                } else if(e.getKeyCode() == backKey) {
                    bBack.setBackground(null);
                    backKeyPressed = false;
                } else if(e.getKeyCode() == leftKey) {
                    bLeft.setBackground(null);
                    leftKeyPressed = false;
                } else if(e.getKeyCode() == rightKey) {
                    bRight.setBackground(null);
                    rightKeyPressed = false;
                } 
                break;

        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }




}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
karan nayak
  • 23
  • 1
  • 4
  • By the way, JavaFX is the replacement of Swing. – ihsan Oct 27 '14 at 16:27
  • A component needs focus for KeyListeners to work. Are you sure that your listened-to component has focus? I don't see that your application has requested it via `requestFocusInWindow()`. Myself, I much prefer to use Key Bindings over KeyListeners. – Hovercraft Full Of Eels Oct 27 '14 at 16:31
  • 1
    Use KeyBindings instead of a `KeyListener`. See [this tutorial](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) and [this answer](http://stackoverflow.com/a/15290065/1076463) – Robin Oct 27 '14 at 16:31
  • @HovercraftFullOfEels this isn't strictly true. You could use the KeyboardFocusManager, rather than KeyBindings or KeyListeners. I think this would be what I'd do – ControlAltDel Oct 27 '14 at 16:34
  • Ok, can you please explain what you want your code to do that it is not doing now? – DreadHeadedDeveloper Oct 27 '14 at 17:23
  • @DreadHeadedDeveloper I want my button background color to change when i press the corresponding button the keyboard. Right now that isn't happening. Please help – karan nayak Oct 28 '14 at 13:53
  • @Hovercraft Full Of Eels Could you please edit my code? I am complete newbie at this and would really appreciate the help. – karan nayak Oct 28 '14 at 13:58
  • @karannayak Just tested your code, when I press A, S, or D, it turns yellow if I push the respective button down, and then turns back to normal after I release the button. However, for W, it changes yellow upon pushing and stays yellow after release. What do you want it to do? – DreadHeadedDeveloper Oct 28 '14 at 14:08
  • @DreadHeadedDeveloper you tested it using what? eclipse right? or something else? Because on my laptop when i run it in eclipse i am not being able to get the color change – karan nayak Oct 28 '14 at 14:22
  • @karannayak I use JGrasp, much easier IMO. But yes, it is working for me – DreadHeadedDeveloper Oct 28 '14 at 14:23
  • @karannayak Perhaps you could try changing which button causes the color change? Like, instead of WASD, try j or something to see if it is something else that's causing the problem. – DreadHeadedDeveloper Oct 28 '14 at 14:57

0 Answers0