0

I'm new to Java, and trying to figure out one last thing for my program.

This is the program that I have coded and with the layout it is perfectly fine no problem at all.

enter image description here

Now my program suppose highlight the buttons whenever to press it on the keyboard (NOT BY PRESSING THE BUTTON ON THE SCREEN)

I'm not sure what I have to use since the action that it needs to take is when they type it in the JTextArea. I'm trying to use KeyEvent with KeyPressed but not sure if that is the right thing to do since it doesn't really work.

I can't post my code at the moment here since this is an assignment and I don't want some of my classmate to google and use it if they found it here. (LOL)

As required here is my codes :)

import javax.swing.*; // import all javax.swing
import java.awt.*; // import all java.awt
import java.awt.event.*;

public class Sample extends JFrame implements KeyListener { // start of the
                                                            // class

    private JTextArea field = new JTextArea(10,15); // create an instance of
                                                        // JTextField
    private JPanel mainPanel = new JPanel(); // create an instance of JPanel
    private JPanel TopFieldPan = new JPanel();
    private JPanel MainBtnsPan = new JPanel();
    private JPanel FifthRowPan = new JPanel();

    JPanel fifthBtn = new JPanel();

    private static JButton Space = new JButton("");

    public Sample() { // start of the weather constructor

        Space.setPreferredSize(new Dimension(280, 45));
        fifthBtn.add(Space);


        TopFieldPan.add(field);

        FifthRowPan.setLayout(new BoxLayout(FifthRowPan, BoxLayout.X_AXIS));
        FifthRowPan.add(fifthBtn);
        MainBtnsPan.setLayout(new GridLayout(5, 5, 0, 0));

        MainBtnsPan.add(FifthRowPan);

        mainPanel.add(TopFieldPan);
        mainPanel.add(MainBtnsPan);

        this.add(mainPanel);

        Space.setSelected(true);
        field.addKeyListener(this); // important !!!

        setTitle("Typing Tutor"); // set the title to the frame
        setSize(300, 300); // set the fixed size
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setLocationRelativeTo(null); 
        setVisible(true); // make it visible

    } // ends of the constructor

    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
            Space.setBackground(Color.green);

        }


    }

    public void keyReleased(KeyEvent evt) {
        Space.setBackground(null);
    }

    public void keyTyped(KeyEvent evt) {
        // TODO Auto-generated method stub

        if(evt.getKeyChar() == 'a' || evt.getKeyChar() ==  'A')
        {
            Space.setBackground(Color.green);
        }
        else if(evt.getKeyChar() == 'b' || evt.getKeyChar() == 'B')
        {
            Space.setBackground(Color.red);
        }       
    }

    public static void main(String[] args) { // start of the main method

        new Sample();

    } // ends of main method

} // ends of class

I tried to simplified the code as much as I could and here is the final one.

So I'm trying to make it when I press a or A it should highlight that space JButton.

Ali
  • 9,997
  • 20
  • 70
  • 105
  • 3
    Without some code, I don't know how we can help you much (LOL), other than perhaps to suggest that you look into perhaps a DocumentFilter, DocumentListener or perhaps (though I hate to use them) a KeyListener. Good luck. – Hovercraft Full Of Eels Mar 25 '13 at 23:38
  • @HovercraftFullOfEels Ouch! Well it will be very messy, but all my codes that I have is only for the layout. Would that be useful? – Ali Mar 25 '13 at 23:38
  • No, the layout isn't your problem, but the code that drives the logic. You'd best start experimenting. – Hovercraft Full Of Eels Mar 25 '13 at 23:39
  • @HovercraftFullOfEels updated my question with the codes, and of course the part where I was trying to experiment on. :) – Ali Mar 25 '13 at 23:41
  • 1
    I suggest that you simplify your code a bit. Start by writing a short program with *one* button that highlites when you press a key (say the spacebar). This will help clarify your question as well as make it easier for us to focus on an answer that will help you. – Code-Apprentice Mar 25 '13 at 23:51
  • @Code-Guru and should I post it again or just update? – Ali Mar 25 '13 at 23:52
  • @Ali Go ahead and keep editing your current question until you feel that you are asking the right question. – Code-Apprentice Mar 25 '13 at 23:53
  • And tell us, what "is not really working". – Markus Kreth Mar 26 '13 at 00:03
  • @Code-Guru I have update it with only one button now as you have asked – Ali Mar 26 '13 at 00:05
  • @MarkusKreth question updated :) – Ali Mar 26 '13 at 00:06
  • 1
    Next step: please describe what your short program does and how it differs from what you want it to do. – Code-Apprentice Mar 26 '13 at 00:17

2 Answers2

2

Create a map of your buttons and the keys they map to, like this:

Map<String, JButton> buttonMap = new HashMap<String, Button>();

Then, when you are adding the buttons, add them to the map, like this:

buttonMap.put(FirstRow[i].toLowerCase(), btn);

Then, add something like this into your KeyTyped:

public void keyTyped(KeyEvent evt) {
    String keyPressed = new String(""+evt.getKeyChar()).toLowerCase();
    JButton tmp = buttonMap.get(keyPressed);
    if(null != tmp){
        tmp.doClick();
    }
}

I did this quickly to your code for row 1 and 2. You'll have to play around with it to get it to work for the special keys, but it should get you where you're trying to go.

I pasted it here, to keep the answer small. http://pastebin.com/t1v8d6Hi

Kylar
  • 8,876
  • 8
  • 41
  • 75
  • 1
    Of course, once you have the correct button, you can do anything you want to it - change the background color, highlight it, etc. I just used the 'doClick()' because it's simple. – Kylar Mar 26 '13 at 00:12
  • one last thing if you don't mind. For example, the caplop I know it is `KeyEvent.VK_CAPS_LOCK` but how can I put that in the `buttomMap.put("".toLowerCase(), btn);` – Ali Mar 26 '13 at 00:19
  • 1
    You could just make something up: map.put("CAPS_LOCK", btn), then look for that specifically: if(ke.getKeyCode() == KeyEvent.VK_CAPS_LOCK) { map.get("CAPS_LOCK"). – Kylar Mar 26 '13 at 00:21
1

You're code looks okay for a first pass, you seem to have a basic mechanism in place that works with the KeyListener. You probably need to think about how to stop mouse clicks on the buttons, JButton.setEnabled(false) works but changes how the button is drawn so you may need to override the paint method. You probably only need to hook the keylistener up to one component, the window will get all events, the text area when it has focus. The main task you have is to work out how to map the key pressed events to the buttons, maybe use a hashmap or something to store the JButtons with the key being the character code?

Daniel Walton
  • 218
  • 1
  • 4
  • 17
  • Well I'm not sure if I understand you right, but just to make sure again. If they type something on the keyboard. Let say if they press the space bar. My JButton should change the color and when they release it then just change the color back. Is that the same? – Ali Mar 26 '13 at 00:04