1

I am trying to create a keyboard GUI with some basic functionalities. The problem that I am running into is within my draw(...){...} function, which highlights the addKeyListener() method, with the error: The method addKeyListener(KeyListener) in the type Component is not applicable for the arguments (a3_keyboard)

Im not sure what I'm doing wrong. I tried changing my code up with,

getContentPane().addKeyListener(this);
for (JButton button : first)  { button.addKeyListener(this); }
for (JButton button : second) { button.addKeyListener(this); } 
for (JButton button : third)  { button.addKeyListener(this); }
for (JButton button : fourth) { button.addKeyListener(this); }
for (JButton button : fifth)  { button.addKeyListener(this); }

But that's throwing me the same error. Full code below:

import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class a3_keyboard extends JFrame implements KeyListener {
    //input
    String input;
    //default color
    Color defaultColor = new JButton().getBackground();
    //main rows of keys
    private String rowOne[] = {
        "~", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "h"
    };
    private String rowTwo[] = {
        "Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"
    };
    private String rowThree[] = {
        "Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "'", "Enter"
    };
    private String rowFour[] = {
        "Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "?", "   ^"
    };
    private String rowFive[] = {
        "       ", "<", "v", ">"
    };
    /** Account for chars with no shift:
        ** Program toggles Shift key, meaning
        ** if a user clicks on it, all keys will be
        ** toggled to their respective shift value. The
        ** user can tap the shift key again to 
        ** change back to regular value */
    private String shiftless[] = {
        "1","2","3","4","5","6","7","8","9","0",
        "-","=","q","w","e","r","t","y","u","i","o","p",
        "[","]","\\","a","s","d","f","g","h","j","k","l",
        ";","z","x","c","v","b","n","m",",",".","/"
    };
    //Account for special chars
    private String specialChars[] = {
        "~", "-", "+", "[", "]", "\\", ";", ".", "?"
    };
    private JLabel context = new JLabel("Type some text using your keyboard. "
        + "The keys you press will be highlighed and the text will be displayed.\n "
        + "Note: Clicking the buttons with your mouse will not perform any action.")
        .setFont(new Font("Verdana",Font.BOLD,14));
    //declare rows of buttons
    private JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
    //ctor
    public a3_keyboard() {
        super("Typing Tutor");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.getContentPane().setPreferredSize(new Dimension(1000,600));
        this.setLocation(50,50);
        this.setVisible(true);
        __init__();
    }
    public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
        setLayout(new BorderLayout());
        add(top, BorderLayout.NORTH);
        add(contextBox);
        add(middle, BorderLayout.CENTER);
        add(bottom, BorderLayout.SOUTH);
    }
    private void __init__body() {
        JTextArea body = new JTextArea().setPreferredSize(new Dimension(600, 150));
    }
    public void __init__panels() {
        JPanel top = new JPanel();
        JPanel middle = new JPanel();
        JPanel bottom = new JPanel();
        JPanel contextBox = new JPanel();
        __init__layout(top, middle, bottom, contextBox);
        top.setLayout(new BorderLayout());
        bottom.setLayout(new GridLayout(5,1));
        top.add(info, BorderLayout.WEST);
        top.add(info, BorderLayout.SOUTH);
        middle.setLayout( new BorderLayout());
        middle.add(text, BorderLayout.WEST);
        middle.add(text, BorderLayout.CENTER);
    }
    private void __init__() {
        //text area
            __init__body();
        //panels for layout
            __init__panels();
        pack();
        //get length of row strings
            int length_rowOne = rowOne.length;
            int length_rowTwo = rowTwo.length;
            int length_rowThree = rowThree.length;
            int length_rowFour = rowFour.length;
            int length_rowFive = rowFive.length;
        //create array for each row of buttons
            buttons_rowOne = new JButton[length_rowOne];
            buttons_rowTwo = new JButton[length_rowTwo];
            buttons_rowThree = new JButton[length_rowThree];
            buttons_rowFour = new JButton[length_rowFour];
            buttons_rowFive = new JButton[length_rowFive];
        //create panel for each row of buttons
            JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
            JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
            JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
            JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
            JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
        //draw out the rows of buttons
            draw(
                r1, length_rowOne,
                r2, length_rowTwo,
                r3, length_rowThree,
                r4, length_rowFour,
                r5, length_rowFive
            );
    }
    //draw rows of buttons
    public void draw(JPanel r1, int s1, 
                    JPanel r2, int s2, 
                    JPanel r3, int s3, 
                    JPanel r4, int s4, 
                    JPanel r5, int s5) {
        for (int i = 0; i < s1; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowOne[i] = currentButton;
            buttons_rowOne[i].addKeyListener(this);
            r1.add(buttons_rowOne[i]);
        }
        for (int i = 0; i < s2; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowTwo[i] = currentButton;
            buttons_rowTwo[i].addKeyListener(this);
            r1.add(buttons_rowTwo[i]);
        }
        for (int i = 0; i < s3; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowThree[i] = currentButton;
            buttons_rowThree[i].addKeyListener(this);
            r1.add(buttons_rowThree[i]);
        }
        for (int i = 0; i < s4; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowFour[i] = currentButton;
            buttons_rowFour[i].addKeyListener(this);
            r1.add(buttons_rowFour[i]);
        }
        for (int i = 0; i < s5; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            //account for space bar
            if (i == 1) {
                currentButton = new JButton(rowFive[i]);
                currentButton.setPreferredSize(new Dimension(400,10));
                currentButton.setBounds(10, 10, 600, 100);
                buttons_rowFive[i] = currentButton;
            } else {
                currentButton.setPreferredSize(new Dimension(100, 50));
                buttons_rowFive[i] = currentButton;
                buttons_rowFive[i].addKeyListener(this);
            }
            r1.add(buttons_rowFive[i]);
        }
        bottom.add(r1);
        bottom.add(r2);
        bottom.add(r3);
        bottom.add(r4);
        bottom.add(r5);
    }//!draw(...)
    //called when a button is pressed
    @Override
    public void activated(KeyEvent press) {
        int index = press.getKeyCode();
        input = String.format("%s", index);
    }//!activated(...)
    //called when a button is released
    @Override
    public void deactivated(KeyEvent release) {
        int index = release.getKeyCode();
        input = String.format( "%s"+KeyEvent.getKeyText(keyCode) );
        this.setBackground(defaultColor);;
    }//!deactivated(...)
    //main method
    public static void main(Strings[] args) {
        new a3_keyboard();
    }//!main method
    //obtain the JButton’s original background colour before you change its colour
}//!main class

If Im missing something, please let me know and I'll add it to the question.


Edit:

New code:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.*;

public class a3_keyboard extends JFrame implements KeyListener {
    //input
    String input;
    //input body
    JTextArea body;
    //panels
    JPanel top, middle, bottom, contextBox = new JPanel();
    //default color
    Color defaultColor = new JButton().getBackground();
    //main rows of keys
    public String rowOne[] = {
        "~", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "+", "h"
    };
    public String rowTwo[] = {
        "Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"
    };
    public String rowThree[] = {
        "Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "'", "Enter"
    };
    public String rowFour[] = {
        "Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "?", "   ^"
    };
    public String rowFive[] = {
        "       ", "<", "v", ">"
    };
    /** Account for chars with no shift:
        ** Program toggles Shift key, meaning
        ** if a user clicks on it, all keys will be
        ** toggled to their respective shift value. The
        ** user can tap the shift key again to 
        ** change back to regular value */
    public String shiftless[] = {
        "1","2","3","4","5","6","7","8","9","0",
        "-","=","q","w","e","r","t","y","u","i","o","p",
        "[","]","\\","a","s","d","f","g","h","j","k","l",
        ";","z","x","c","v","b","n","m",",",".","/"
    };
    //Account for special chars
    public String specialChars[] = {
        "~", "-", "+", "[", "]", "\\", ";", ".", "?"
    };

    //declare rows of buttons
    public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
    //ctor
    public a3_keyboard() {
        super("Typing Tutor");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.getContentPane().setPreferredSize(new Dimension(1000,600));
        this.setLocation(50,50);
        this.setVisible(true);
        __init__();
    }
    public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
        setLayout(new BorderLayout());
        add(top, BorderLayout.NORTH);
        add(contextBox);
        add(middle, BorderLayout.CENTER);
        add(bottom, BorderLayout.SOUTH);
    }
    public void __init__body() {
        JTextArea body = new JTextArea();
        body.setPreferredSize(new Dimension(600, 150));
    }
    public void __init__panels() {
        JLabel context = new JLabel("Type some text using your keyboard. "
            + "The keys you press will be highlighed and the text will be displayed.\n "
                + "Note: Clicking the buttons with your mouse will not perform any action.");
        context.setFont(new Font("Verdana",Font.BOLD,14));
        __init__layout(top, middle, bottom, contextBox);
        top.setLayout(new BorderLayout());
        bottom.setLayout(new GridLayout(5,1));
        top.add(context, BorderLayout.WEST);
        top.add(context, BorderLayout.SOUTH);
        middle.setLayout( new BorderLayout());
        middle.add(body, BorderLayout.WEST);
        middle.add(body, BorderLayout.CENTER);
    }
    public void __init__() {
        //text area
            __init__body();
        //panels for layout
            __init__panels();
        pack();
        //get length of row strings
            int length_rowOne = rowOne.length;
            int length_rowTwo = rowTwo.length;
            int length_rowThree = rowThree.length;
            int length_rowFour = rowFour.length;
            int length_rowFive = rowFive.length;
        //create array for each row of buttons
            buttons_rowOne = new JButton[length_rowOne];
            buttons_rowTwo = new JButton[length_rowTwo];
            buttons_rowThree = new JButton[length_rowThree];
            buttons_rowFour = new JButton[length_rowFour];
            buttons_rowFive = new JButton[length_rowFive];
        //create panel for each row of buttons
            JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
            JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
            JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
            JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
            JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
        //draw out the rows of buttons
            draw(
                r1, length_rowOne,
                r2, length_rowTwo,
                r3, length_rowThree,
                r4, length_rowFour,
                r5, length_rowFive
            );

    }
    //draw rows of buttons
    public void draw(JPanel r1, int s1, 
                    JPanel r2, int s2, 
                    JPanel r3, int s3, 
                    JPanel r4, int s4, 
                    JPanel r5, int s5) {
        for (int i = 0; i < s1; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowOne[i] = currentButton;
            buttons_rowOne[i].addKeyListener(this);
            r1.add(buttons_rowOne[i]);
        }
        for (int i = 0; i < s2; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowTwo[i] = currentButton;
            buttons_rowTwo[i].addKeyListener(this);
            r1.add(buttons_rowTwo[i]);
        }
        for (int i = 0; i < s3; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowThree[i] = currentButton;
            buttons_rowThree[i].addKeyListener(this);
            r1.add(buttons_rowThree[i]);
        }
        for (int i = 0; i < s4; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            currentButton.setPreferredSize(new Dimension(100, 50));
            buttons_rowFour[i] = currentButton;
            buttons_rowFour[i].addKeyListener(this);
            r1.add(buttons_rowFour[i]);
        }
        for (int i = 0; i < s5; i++) {
            JButton currentButton = new JButton(rowOne[i]);
            //account for space bar
            if (i == 1) {
                currentButton = new JButton(rowFive[i]);
                currentButton.setPreferredSize(new Dimension(400,10));
                currentButton.setBounds(10, 10, 600, 100);
                buttons_rowFive[i] = currentButton;
                buttons_rowFive[i].addKeyListener(this);
            } else {
                currentButton.setPreferredSize(new Dimension(100, 50));
                buttons_rowFive[i] = currentButton;
                buttons_rowFive[i].addKeyListener(this);
            }
            r1.add(buttons_rowFive[i]);
        }
        bottom.add(r1);
        bottom.add(r2);
        bottom.add(r3);
        bottom.add(r4);
        bottom.add(r5);
    }//!draw(...)

    // called when a button is pressed
    @Override
    public void keyPressed(KeyEvent pressed) {
        JButton current = (JButton) pressed.getSource();
        current.setBackground(Color.GRAY);
        body.append(toString(current.getKeyChar()));
    }//!keyPressed(...)
    // called when a button is released
    @Override
    public void keyReleased(KeyEvent released) {
        JButton current = (JButton) released.getSource();
        current.setBackground(defaultColor);
    }//!keyReleased(...)
    @Override
    public void keyTyped(KeyEvent typed) {
        JButton current = (JButton) typed.getSource();
    }

    //main method
    public static void main(String[] args) {
        new a3_keyboard();
    }//!main method
    private static final long serialVersionUID = 999;
}//!main class

Edit 2:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class ButtonInPane extends JFrame implements KeyListener {
  //redacted, see below

  @Override
  public void keyPressed(KeyEvent press) {
      JButton current = (JButton) press.getSource();
      current.setBackground(Color.GRAY);
      StringBuilder sb = new StringBuilder();
      sb.append(press.getKeyChar());
      body.append(sb.toString());
  } // !keyPressed(...)
  // called when a button is released

  @Override
  public void keyReleased(KeyEvent release) {
      JButton current = (JButton) release.getSource();
      current.setBackground(defaultColor);
  } // !keyReleased(...)

  @Override
  public void keyTyped(KeyEvent typed) {
      JButton current = (JButton) typed.getSource();
  }

  // main method
  public static void main(String[] args) {
      new ButtonInPane();
  } // !main method

  private static final long serialVersionUID = 999;
} // !main class

Edit 3:

@Override
public void keyPressed(KeyEvent press) {
    Object current = press.getSource().toString();
    for (int i = 0; i < 14; i++) {
    if (current == rowOne[i]) {
        buttons_rowOne[i].setBackground(Color.GRAY);
    } else if (current == rowTwo[i]) {
        buttons_rowTwo[i].setBackground(Color.GRAY);
    } else if (current == rowThree[i]) {
        buttons_rowThree[i].setBackground(Color.GRAY);
    } else if (current == rowFour[i]) {
        buttons_rowFour[i].setBackground(Color.GRAY);
    } else if (current == rowFive[i]) {
        buttons_rowFive[i].setBackground(Color.GRAY);
    }
    }
} // !keyPressed(...)
// called when a button is released

@Override
public void keyReleased(KeyEvent release) {
    Object current = release.getSource().toString();
    for (int i = 0; i < 14; i++) {
    if (current == rowOne[i]) {
        buttons_rowOne[i].setBackground(defaultColor);
    } else if (current == rowTwo[i]) {
        buttons_rowTwo[i].setBackground(defaultColor);
    } else if (current == rowThree[i]) {
        buttons_rowThree[i].setBackground(defaultColor);
    } else if (current == rowFour[i]) {
        buttons_rowFour[i].setBackground(defaultColor);
    } else if (current == rowFive[i]) {
        buttons_rowFive[i].setBackground(defaultColor);
    }
    }
} // !keyReleased(...)

@Override
public void keyTyped(KeyEvent typed) {
    // Object current = typed.getSource().toString();
    // StringBuilder sb = new StringBuilder();
    // for (int i = 0; i < 14; i++) {
    //   if (current == rowOne[i]) {
    //     sb.append(typed.getKeyCode());
    //     body.append(sb.toString());
    //   } else if (current == rowTwo[i]) {
    //     sb.append(typed.getKeyCode());
    //     body.append(sb.toString());
    //   } else if (current == rowThree[i]) {
    //     sb.append(typed.getKeyCode());
    //     body.append(sb.toString());
    //   } else if (current == rowFour[i]) {
    //     sb.append(typed.getKeyCode());
    //     body.append(sb.toString());
    //   } else if (current == rowFive[i]) {
    //     sb.append(typed.getKeyCode());
    //     body.append(sb.toString());
    //   }
    // }      
}
Mike K
  • 7,621
  • 14
  • 60
  • 120
  • Possible duplicate of https://stackoverflow.com/questions/22741215/how-to-use-key-bindings-instead-of-key-listeners – ControlAltDel Jul 30 '18 at 15:30
  • 1
    It looks like there are many other problems in your code which prevents it to compile it before that section. For instance you can't do `private JLabel context = new JLabel("Type some text using your keyboard. "someText").setFont(new Font("Verdana",Font.BOLD,14));` because `setFont(..)` doesn't return any value, not even `JLabel` itself, so you cannot assign it to `context`. You need to split it into two steps, or initialize it in constructor/init block. Similar problem with `JTextArea body` (which I am not sure what you even create since it is not used anywhere). – Pshemo Jul 30 '18 at 15:44
  • 1
    Aside from that your class didn't implement mandatory methods of `KeyListener` like `keyTyped`, `keyPressed`, `keyReleased`. After fixing all other compilation problems you should be able to use `this` as instance of KeyListener. (you also have `String*s*[] args` instead of `String[] args`) – Pshemo Jul 30 '18 at 15:49
  • I've made a few big changes and added what you suggested. Im still running into the same `keyEventListener()` issue. Error: "The method addKeyListener(KeyListener) in the type component is not applicable for the arguments Keyboard.myKeyListener" – Mike K Jul 30 '18 at 17:26
  • 1
    Welcome to Stack Overflow. When you tackle a problem like this, it often helps to open a new file and write code that recreates the problem. Keep it as simple as possible and add only the parts of your code that are important for the current issue. In this case, you want to focus only on the parts of your program that deal with the `KeyListener`. When you create this small example, you will learn what parts are needed for what you are doing to work correctly. It also makes it easier to ask a question because you have a very specific code example that shows what you are doing. – Code-Apprentice Jul 30 '18 at 19:13
  • 1
    For more tips about creating a good code example, read [mcve]. – Code-Apprentice Jul 30 '18 at 19:13
  • 1
    Thank you for the advice, I'll keep that in mind in the future. – Mike K Jul 30 '18 at 19:15
  • Note that when you start using numbers in variable names, you should immediately consider using an array or list. In this case, `rowOne`, `rowTwo`, etc. are themselves arrays, so you can use a 2D array: `String[][] rows = ...` (or some more appropriate variable name). – Code-Apprentice Jul 30 '18 at 19:21
  • If you haven't already, study this: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html – D-Klotz Jul 30 '18 at 19:53

1 Answers1

1

This version puts the keylistener on the correct component. However you now need to redesign this given your new understanding...

Because as the code is right now, the jtext area body simply gets a repeat of the key as you press them. There are several ways you could solve this.

Some of the brute force and others more intricate but elegant. Ping me if you still want help.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class ButtonInPane extends JFrame implements KeyListener {
  // input
  String input;
  //context
  JLabel context1, context2;
  // default color
  Color defaultColor = new JButton().getBackground();
  // main rows of keys
  public String rowOne[] = {
      "~",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "0",
      "-",
      "+",
      "h"
  };
  public String rowTwo[] = {
      "Tab",
      "Q",
      "W",
      "E",
      "R",
      "T",
      "Y",
      "U",
      "I",
      "O",
      "P",
      "[",
      "]",
      "\\"
  };
  public String rowThree[] = {
      "Caps",
      "A",
      "S",
      "D",
      "F",
      "G",
      "H",
      "J",
      "K",
      "L",
      ":",
      "'",
      "Enter"
  };
  public String rowFour[] = {
      "Shift",
      "Z",
      "X",
      "C",
      "V",
      "B",
      "N",
      "M",
      ",",
      ".",
      "?",
      "   ^"
  };
  public String rowFive[] = {
      "       ",
      "<",
      "v",
      ">"
  };
  /**
   * Account for chars with no shift: Program toggles Shift key, meaning if a
   * user clicks on it, all keys will be toggled to their respective shift
   * value. The user can tap the shift key again to change back to regular
   * value
   */
  public String shiftless[] = {
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "0",
      "-",
      "=",
      "q",
      "w",
      "e",
      "r",
      "t",
      "y",
      "u",
      "i",
      "o",
      "p",
      "[",
      "]",
      "\\",
      "a",
      "s",
      "d",
      "f",
      "g",
      "h",
      "j",
      "k",
      "l",
      ";",
      "z",
      "x",
      "c",
      "v",
      "b",
      "n",
      "m",
      ",",
      ".",
      "/"
  };
  // Account for special chars
  public String specialChars[] = {
      "~",
      "-",
      "+",
      "[",
      "]",
      "\\",
      ";",
      ".",
      "?"
  };

  // declare rows of buttons
  public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
  private JTextArea body;
  private JPanel top;
  private JPanel middle;
  private JPanel bottom;
  private JPanel contextBox;

  // ctor
  public ButtonInPane() {
      super("Typing Tutor");
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setResizable(false);
      this.getContentPane().setPreferredSize(new Dimension(2000, 600));
      this.setLocation(50, 50);
      this.setVisible(true);
      __init__();
  }

  public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
      setLayout(new BorderLayout());
      add(top, BorderLayout.NORTH);
      add(contextBox);
      add(middle, BorderLayout.CENTER);
      add(bottom, BorderLayout.SOUTH);
  }

  public void __init__body() {
      body = new JTextArea();
      body.setPreferredSize(new Dimension(600, 150));
      body.addKeyListener(this);
  }

  public void __init__panels() {
      context1 = new JLabel("Type some text using your keyboard. " +
          "The keys you press will be highlighed and the text will be displayed.");
      context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
      context1.setFont(new Font("Verdana", Font.BOLD, 14));
      context2.setFont(new Font("Verdana", Font.BOLD, 14));
      top = new JPanel();
      top.setSize(new Dimension(500, 500));
      middle = new JPanel();
      bottom = new JPanel();
      contextBox = new JPanel();
      __init__layout(top, middle, bottom, contextBox);
      top.setLayout(new BorderLayout());
      bottom.setLayout(new GridLayout(5, 1));
      top.add(context2);
      top.add(context1);
      middle.setLayout(new BorderLayout());
      middle.add(body, BorderLayout.WEST);
      middle.add(body, BorderLayout.CENTER);
  }

  public void __init__() {
      // text area
      __init__body();
      // panels for layout
      __init__panels();
      pack();
      // get length of row strings
      int length_rowOne = rowOne.length;
      int length_rowTwo = rowTwo.length;
      int length_rowThree = rowThree.length;
      int length_rowFour = rowFour.length;
      int length_rowFive = rowFive.length;
      // create array for each row of buttons
      buttons_rowOne = new JButton[length_rowOne];
      buttons_rowTwo = new JButton[length_rowTwo];
      buttons_rowThree = new JButton[length_rowThree];
      buttons_rowFour = new JButton[length_rowFour];
      buttons_rowFive = new JButton[length_rowFive];
      // create panel for each row of buttons
      JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
      JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
      JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
      JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
      JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
      // draw out the rows of buttons
      draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);

  }

  // draw rows of buttons
  public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
      for (int i = 0; i < s1; i++) {
          JButton currentButton = new JButton(rowOne[i]);
          currentButton.setPreferredSize(new Dimension(100, 50));
          buttons_rowOne[i] = currentButton;
          r1.add(buttons_rowOne[i]);
      }
      for (int i = 0; i < s2; i++) {
          JButton currentButton = new JButton(rowTwo[i]);
          currentButton.setPreferredSize(new Dimension(100, 50));
          buttons_rowTwo[i] = currentButton;
          r2.add(buttons_rowTwo[i]);
      }
      for (int i = 0; i < s3; i++) {
          JButton currentButton = new JButton(rowThree[i]);
          currentButton.setPreferredSize(new Dimension(100, 50));
          buttons_rowThree[i] = currentButton;
          r3.add(buttons_rowThree[i]);
      }
      for (int i = 0; i < s4; i++) {
          JButton currentButton = new JButton(rowFour[i]);
          currentButton.setPreferredSize(new Dimension(100, 50));
          buttons_rowFour[i] = currentButton;
          r4.add(buttons_rowFour[i]);
      }
      for (int i = 0; i < s5; i++) {
          JButton currentButton = new JButton(rowFive[i]);
          // account for space bar
          if (i == 1) {
              currentButton = new JButton(rowFive[i]);
              currentButton.setPreferredSize(new Dimension(400, 10));
              currentButton.setBounds(10, 10, 600, 100);
              buttons_rowFive[i] = currentButton;
          } else {
              currentButton.setPreferredSize(new Dimension(100, 50));
              buttons_rowFive[i] = currentButton;
          }
          r5.add(buttons_rowFive[i]);
      }
      bottom.add(r1);
      bottom.add(r2);
      bottom.add(r3);
      bottom.add(r4);
      bottom.add(r5);
  } // !draw(...)
  // called when a button is pressed

  @Override
  public void keyPressed(KeyEvent press) {
      StringBuilder sb = new StringBuilder();
      sb.append(press.getKeyChar());
      body.append(sb.toString());
  } // !keyPressed(...)
  // called when a button is released

  @Override
  public void keyReleased(KeyEvent release) {
       Object current = release.getSource();
  } // !keyReleased(...)

  @Override
  public void keyTyped(KeyEvent typed) {
      Object current = typed.getSource();
  }

  // main method
  public static void main(String[] args) {
      new ButtonInPane();
  } // !main method

  private static final long serialVersionUID = 999;
} // !main class
D-Klotz
  • 1,973
  • 1
  • 15
  • 37
  • Wow! Thank you for that sense of direction. I've added some changes as well in Edit 2, and I still can't seem to get the keys to input to the text area. When I run the program, the onscreen keyboard doesn't even show up until I type something from my keyboard into the JTextArea, and then each key doesn't exhibit any behaviour once pressed. You mentioned Im not calling the event listener anywhere -- I was under the impression that defining KeyEvent methods (keyPressed, keyTyped etc) and adding `addKeyListener` was sufficient enough to get pressed keys inputted into the TextArea. – Mike K Jul 30 '18 at 19:11
  • @legoMyEgo I meant that within the eclipse debugger a breakpoint inside keyPressed and keyReleased is never reached. After work I'll spend some time on this if you are still stuck. – D-Klotz Jul 30 '18 at 19:51
  • @legoMyEgo i see the problem. Think about who you are adding your keylistener to. What component are you actually typing within? – D-Klotz Jul 30 '18 at 20:13
  • @legoMyEgo You are adding a lot of listeners to the wrong components. They will never be called. – D-Klotz Jul 30 '18 at 20:14
  • @legoMyEgo Perhaps you thought that the method call addKeyListener meant that the component you did this call on would receive all of the key events. It doesn't work that way. It took me a while to remember this as it has been a few years since I developed within Swing. – D-Klotz Jul 30 '18 at 20:40
  • @legoMyEgo Ok I've updated my answer with a version that has the listener in the correct place. You will need to redesign this. – D-Klotz Jul 30 '18 at 20:52
  • Thank you again for the help. I feel like I am on the right track. I've added into Edit 3 the relevant 3 methods. It compiles, but now no on-screen keyboard even shows up.. not even if I press something on my keyboard to trigger it to show (which was another issue on its own). If you get a moment again after work today, please let me know what I should be focusing on. I have a feeling `Object current = typed.getSource()` isn't something that can be compared to my array of rows such as rowOne or rowTwo. I tried `Object current = typed.getSource().toString();` but still no cigar – Mike K Jul 31 '18 at 15:24
  • @legoMyEgo are you using eclipse (http://www.eclipse.org/downloads/packages/release/photon/r/eclipse-java-photon-r)? I ask because if you use the debugger and break on the Object current ... you can take a look at the object and examine it. Hopefully that will let the light bulb go off :) and you see what is what. – D-Klotz Jul 31 '18 at 15:33
  • Just noticed that I do not have to implement a keypress, ie if a key on the on screen keyboard is tapped with mouse, no input should show up in the JTextArea. Which kind of simplifies things. Commenting out the whole `keyTyped(...)` method now shows up my keyboard again (although, again, I need to first tap something on my keyboard to trigger it to show up). Still though, I cant seem to have the onscreen keys grey out with every respective keyclick on the physical keyboard. – Mike K Jul 31 '18 at 15:33
  • I am using a Mac and compiling via terminal – Mike K Jul 31 '18 at 15:34
  • Thank you for your help, I'll go where I can from here :) – Mike K Jul 31 '18 at 16:07
  • @legoMyEgo so your version of the Mac can't install the eclipse package for Macs? That's to bad. The debugger and inspecting the object in flight is very educational. After work, I should be able to help if you are stumped. – D-Klotz Jul 31 '18 at 16:18
  • @legoMyEgo one way you could solve this is to have hashmap with the key being the letter "a", "b", "c" etc and the value being a reference to your corresponding button. Your key listener would see that the letter "d" was pressed and you do a hashmap.get("d") https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#get-java.lang.Object- Questions? – D-Klotz Jul 31 '18 at 18:22