11 Replies - 26889 Views - Last Post: 05 April 2011 - 07:00 AM Rate Topic: -----

#1 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

I need to create an on-screen keyboard GUI using Java

Posted 31 March 2011 - 06:40 PM

The on-screen keyboard allows users to touch-type [type without looking at their keyboard].

I am having trouble implementing the setBackground (changes the color of the corresponding JButton when a key is pressed) and getBackground (changes the corresponding JButton back to it's original color ) methods correctly in my program.
Also, the JTextArea in the GUI will display the text typed by the user, but whenever i use JTextArea coding in my program then run it, the GUI window is blank. The only way I could get around this problem was to use a JTextField instead.
This is what I've done so far:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;


// VirtualKeyboard.java
public class VirtualKeyboard extends JFrame implements KeyListener
{
    private JButton 
            A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,
            Tab,Caps,Shift,Backspace;
    private JTextField textField;
    private String keyText;
    private JLabel label1;
    private JLabel label2;
    private Object[] keys;
    int keycode;

    public VirtualKeyboard()
    {
        super("Typing Application");
        setLayout( new FlowLayout() );
        label1 = new JLabel("Type some text using your keyboard.  The keys you press will be "
                + "highlighed and the text will be displayed");
        add(label1);
        label2 = new JLabel("Note: clicking the buttons with your mouse will not perform any action");
        add(label2);

        textField = new JTextField(60);
        textField.setEditable(true);
        add( textField , BorderLayout.NORTH);

        TextFieldHandler handler = new TextFieldHandler();
    
       
        Backspace = new JButton( "Backspace" );
        add(Backspace);
        Tab = new JButton( "Tab" );
        add(Tab);
        Q = new JButton( "Q" );
        add(Q);
        W = new JButton( "W" );
        add(W);
        E = new JButton( "E" );
        add(E);
        R = new JButton( "R" );
        add(R);
        T = new JButton( "T" );
        add(T);
        Y = new JButton( "Y" );
        add(Y);
        U = new JButton( "U" );
        add(U);
        I = new JButton( "I" );
        add(I);
        O = new JButton( "O" );
        add(O);
        P = new JButton( "P" );
        add(P);

        Caps = new JButton ( "Caps ");
        add(Caps);
        A = new JButton( "A" );
        add(A);
        S = new JButton( "S" );
        add(S);
        D = new JButton( "D" );
        add(D);
        F = new JButton( "F" );
        add(F);
        G = new JButton( "G" );
        add(G);
        H = new JButton( "H" );
        add(H);
        J = new JButton( "J" );
        add(J);
        K = new JButton( "K" );
        add(K);
        L = new JButton( "L" );
        add(L);

        Shift = new JButton ( "Shift" );
        add(Shift);
        Z = new JButton( "Z" );
        add(Z);
        X = new JButton( "X" );
        add(X);
        C = new JButton( "C" );
        add(C);
        V = new JButton( "V" );
        add(V);
        B = new JButton( "B" );
        add(B)/>;
        N = new JButton( "N" );
        add(N);
        M = new JButton( "M" );
        add(M);
    }

      // overridden keyPressed method handles press of any key
    @Override
    public void keyPressed( KeyEvent event )
    {
        keycode = event.getKeyCode();
        keyText = String.format( "%s",KeyEvent.getKeyText( event.getKeyCode() ) );
        setBackground(Color.PINK);





    }

    // overridden keyReleased method handles press of any key
    @Override
    public void keyReleased( KeyEvent event )
    {
        keycode = event.getKeyCode();
        keyText = String.format( "%s",KeyEvent.getKeyText( event.getKeyCode() ) );
        getBackground();
    }

    @Override
    public void keyTyped( KeyEvent event )
    {
        keyText = String.format( "%s", event.getKeyChar() );

    }


   private class TextFieldHandler implements ActionListener
   {
      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = ""; // declare string to display

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == textField )
            string = String.format( "%s", event.getActionCommand() );
       }
    }

}

// VirtualKeyboardTest.java 
import javax.swing.JFrame;

public class VirtualKeyboardTest
{
    public static void main(String[] args)
    {
        VirtualKeyboard typingTutor = new VirtualKeyboard();    // creates TypingTutor
        typingTutor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        typingTutor.setSize(700, 500);      // set dimensions of window
        typingTutor.setVisible(true);
        JFrame frame = new JFrame();



    }   // end main
}   // end class TypingTutorTest



Is This A Good Question/Topic? 0
  • +

Replies To: I need to create an on-screen keyboard GUI using Java

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: I need to create an on-screen keyboard GUI using Java

Posted 31 March 2011 - 07:20 PM

I would use a complete different approach a lot shorter as far as I am concerned and without KeyListener

class Keyboard extends JFrame {

   // all key but BSP
   String qwerty = "QWERTYUIOPASDFGHJKLZXCVBNM ";
   JTextField field;

   Keyboard() {
      super("Keyboard");
      .... set layout

      // create TextField
      field = new JTextField(80);

      // create buttons
      for(int i = 0; i < qwerty.length(); i++) {
          String label = "" + qwerty.charAt(i);
          add(new MyButton(label));
      }
      add(new BSPButton());

      ....

      class MyButton extends JButton implements ActionListener {

         // constructor
         MyButton(String name) {
            super(name);
            addActionListener(this);
         }
         // button was hit
         public void actionPerformed(ActionEvent e) {
           field.append(getText());    // append to field my label
         }
       }

       class BSPButton extends JButton implements ActionListener {

          BSPButton() {
            super("BSP");
            addActionListener(this);
          }
          public void actionPerformed(ActionEvent e) {
            String text = field.getText();
            if(text.length() == 0) 
               return;
            field.setText(text.subString(text.length() - 1));
          }
        }


Was This Post Helpful? 1
  • +
  • -

#3 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: I need to create an on-screen keyboard GUI using Java

Posted 31 March 2011 - 07:31 PM

Is BSP short for Backspace?


View Postpbl, on 31 March 2011 - 07:20 PM, said:

I would use a complete different approach a lot shorter as far as I am concerned and without KeyListener

class Keyboard extends JFrame {

   // all key but BSP
   String qwerty = "QWERTYUIOPASDFGHJKLZXCVBNM ";
   JTextField field;

   Keyboard() {
      super("Keyboard");
      .... set layout

      // create TextField
      field = new JTextField(80);

      // create buttons
      for(int i = 0; i < qwerty.length(); i++) {
          String label = "" + qwerty.charAt(i);
          add(new MyButton(label));
      }
      add(new BSPButton());

      ....

      class MyButton extends JButton implements ActionListener {

         // constructor
         MyButton(String name) {
            super(name);
            addActionListener(this);
         }
         // button was hit
         public void actionPerformed(ActionEvent e) {
           field.append(getText());    // append to field my label
         }
       }

       class BSPButton extends JButton implements ActionListener {

          BSPButton() {
            super("BSP");
            addActionListener(this);
          }
          public void actionPerformed(ActionEvent e) {
            String text = field.getText();
            if(text.length() == 0) 
               return;
            field.setText(text.subString(text.length() - 1));
          }
        }


Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: I need to create an on-screen keyboard GUI using Java

Posted 31 March 2011 - 07:39 PM

          public void actionPerformed(ActionEvent e) {
            // get length of the text in the TextField
            String text = field.getText();
            // if the text length is 0 exit
            if(text.length() == 0) 
               return;
            // reset the JTextField to its old text minus the last character
            field.setText(text.subString(text.length() - 1));
          }
        }


I think that can be qualified as a backspace :)

TAB will be more complicated to implement but you can write an inner class for it

Shift depends if you want to implement shift or shift lock, almost the same
Was This Post Helpful? 0
  • +
  • -

#5 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10461
  • View blog
  • Posts: 38,758
  • Joined: 27-December 08

Re: I need to create an on-screen keyboard GUI using Java

Posted 31 March 2011 - 09:02 PM

Even if you don't use pbl's design, you should still be using an array for these at the very least. It will simplify your life a ton.
private JButton A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,  



An example on using arrays.
JButton[] buttons = new JButton[26];
for(int i = 0; i < buttons.length; i++){
     buttons[i] = new JButton(((char)(i + 'A')) + "");
     buttons[i].addActionListener(someActionListener);
     panel.add(buttons[i]);
}


Was This Post Helpful? 0
  • +
  • -

#6 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: I need to create an on-screen keyboard GUI using Java

Posted 01 April 2011 - 01:27 AM

I have tried this program using arrays as well. Here's another version of my program:

// imports used
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.event.ListSelectionListener;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

// TypingTutor.java
/******************************************************************************
PURPOSE:        To implement and create a Java GUI that allows a user to touch-type
                using an on-screen keyboard.

INPUT:          Keys entered by the user.

PRECONDITIONS:  JButtons will be used to represent the on screen keys.
                The setBackground method will be used to change the color of the on-screen
                key typed by the user.
                The getBackground method will be used to change the color of the on-screen
                key back to its original color upon release of the typed key.
                A JTextArea will be used to display what the user has typed.

OUTPUT:         The text typed by the user will be displayed in the JTextArea part of the GUI.


POSTCONDITIONS: none

ALGORITHM:      begin
                    Declare JButtons for all keyboard key
                    Declare textarea as private
                    Declare a single element array with pink as the color that will be used
                        to change the color of the key typed
                    Title the GUI "Typing Application"
                    Color the typed text black
                    Implement constructors and "add" functions for all keys
                end

ERRORS:         none
*******************************************************************************/
public class TypingTutor extends JFrame implements KeyListener
{


    // JButton declarations for keys
    // design
    //1. create an array of MAX JButtons. Let's call it keys.
    //2. Instantiate and initalize every keys element
   //         keys[TheKeyCodeOfA] = new JButtons("A")
   //         keys[TheKeyCodeOfB] = new JButtons("B")
    //        ....
    //3. code the keypressed and keyreleased event
    //   in the event handler, you use the event.getKeyCode to get the
    //    index of the arrray
    //    int keycode = event.getKeyCode();
    //     keys[keycode].setBackground(Color.PINK);
    private JButton[] keys = new JButton[403];
       
    private JLabel label1;
    private JLabel label2;
    private JTextField textField;
    private JTextArea textArea;
    private String keyText;
    

    public TypingTutor()
        {
            super("Typing Application");
            label1 = new JLabel("Type some text using your keyboard.  The keys you press will be "
                + "highlighed and the text will be displayed");
            add(label1);
            label2 = new JLabel("Note: clicking the buttons with your mouse will not perform any action");
            add(label2);
            
            textArea = new JTextArea(5, 20);
            textArea.setEditable(true);

            TextFieldHandler handler = new TextFieldHandler();
        }   // end five-argument constructor


        
       



    // overridden keyPressed method handles press of any key
    @Override
    public void keyPressed( KeyEvent event )
    {
        int keycode = event.getKeyCode();
        keyText = String.format( "%s",KeyEvent.getKeyText( event.getKeyCode() ) );
        keys[keycode].setBackground(Color.PINK);
       
        keys[KeyEvent.VK_B] = new JButton("B");
        add(keys[KeyEvent.VK_B]);
        keys[KeyEvent.VK_C] = new JButton("C");
        keys[KeyEvent.VK_D] = new JButton("D");
        keys[KeyEvent.VK_E] = new JButton("E");
        keys[KeyEvent.VK_F] = new JButton("F");
        keys[KeyEvent.VK_G] = new JButton("G");
        keys[KeyEvent.VK_H] = new JButton("H");
        keys[KeyEvent.VK_I] = new JButton("I");
        keys[KeyEvent.VK_J] = new JButton("J");
        keys[KeyEvent.VK_K] = new JButton("K");
        keys[KeyEvent.VK_L] = new JButton("L");
        keys[KeyEvent.VK_M] = new JButton("M");
        keys[KeyEvent.VK_N] = new JButton("N");
        keys[KeyEvent.VK_O] = new JButton("O");
        keys[KeyEvent.VK_P] = new JButton("P");
        keys[KeyEvent.VK_Q] = new JButton("Q");
        keys[KeyEvent.VK_R] = new JButton("R");
        keys[KeyEvent.VK_S] = new JButton("S");
        keys[KeyEvent.VK_T] = new JButton("T");
        keys[KeyEvent.VK_U] = new JButton("U");
        keys[KeyEvent.VK_V] = new JButton("V");
        keys[KeyEvent.VK_W] = new JButton("W");
        keys[KeyEvent.VK_X] = new JButton("X");
        keys[KeyEvent.VK_Y] = new JButton("Y");
        keys[KeyEvent.VK_Z] = new JButton("Z");
        keys[KeyEvent.VK_1] = new JButton("1");
        keys[KeyEvent.VK_2] = new JButton("2");
        keys[KeyEvent.VK_3] = new JButton("3");
        keys[KeyEvent.VK_4] = new JButton("4");
        keys[KeyEvent.VK_5] = new JButton("5");
        keys[KeyEvent.VK_6] = new JButton("6");
        keys[KeyEvent.VK_7] = new JButton("7");
        keys[KeyEvent.VK_8] = new JButton("8");
        keys[KeyEvent.VK_9] = new JButton("9");
        keys[KeyEvent.VK_0] = new JButton("0");
        setBackground(Color.PINK);

 

    }

   private class TextAreaHandler implements ActionListener
   {
      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = ""; // declare string to display

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == textField )
            string = String.format( "%s",
               event.getActionCommand() );
       }
    }
    // overridden keyReleased method handles press of any key
    @Override
    public void keyReleased( KeyEvent event )
    {
        int keyCode = event.getKeyCode();
        keyText = String.format( "%s"+KeyEvent.getKeyText(keyCode) );
        getBackground();

    }

    @Override
    public void keyTyped( KeyEvent event )
    {
        keyText = String.format( "%s", event.getKeyChar() );

    }

    private class TextFieldHandler implements ActionListener
    {
      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = ""; // declare string to display

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == textField )
            string = String.format( "%s", event.getActionCommand() );
       }
    }
}

// TypingTutorTest.java
import java.awt.event.KeyEvent;
import javax.swing.JFrame;

/******************************************************************************
PURPOSE:        To test the data values for all parameters in the TypingTutor class
                by using constructors.

INPUT:          none.

PRECONDITIONS:  JButtons for on screen keys have been implemented.
                The setBackground and getBackground methods have been implemented properly

OUTPUT:         none


POSTCONDITIONS: none

ALGORITHM:      begin
                    declare a new TypingTutor constructor
                    set dimensions for typingTutor window and make it visible
                        using setVisible(true)

                end

ERRORS:         none
*******************************************************************************/
public class TypingTutorTest
{
    public static void main(String[] args)
    {
        TypingTutor typingTutor = new TypingTutor()
        {

            public void keyTyped(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            public void keyPressed(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            public void keyReleased(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        };    // creates TypingTutor
        typingTutor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        typingTutor.setSize(600, 500);      // set dimensions of window
        typingTutor.setVisible(true);
    }   // end main
}   // end class TypingTutorTest



You'll notice in the keyPressed event, there is code to add a JButton for the "B" key to my GUI. However, I can't get any JButtons on my GUI when I run this program. I have no clue why no JButtons are being shown. I am using the NetBeans IDE for this btw.



View Postmacosxnerd101, on 31 March 2011 - 09:02 PM, said:

Even if you don't use pbl's design, you should still be using an array for these at the very least. It will simplify your life a ton.
private JButton A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,  



An example on using arrays.
JButton[] buttons = new JButton[26];
for(int i = 0; i < buttons.length; i++){
     buttons[i] = new JButton(((char)(i + 'A')) + "");
     buttons[i].addActionListener(someActionListener);
     panel.add(buttons[i]);
}


Was This Post Helpful? 0
  • +
  • -

#7 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: I need to create an on-screen keyboard GUI using Java

Posted 01 April 2011 - 01:17 PM

How should I implement the getBackground (so that the correct JButton changes color when the corresponding key is pressed) and setBackground (so that the correct JButton changes to its original color when the corresponding key is released) methods in my program? That's the part of this program that is causing me the most problems. A soft copy of this program is due by 11:59pm on Tuesday, April 5th.


View Postpbl, on 31 March 2011 - 07:20 PM, said:

I would use a complete different approach a lot shorter as far as I am concerned and without KeyListener

class Keyboard extends JFrame {

   // all key but BSP
   String qwerty = "QWERTYUIOPASDFGHJKLZXCVBNM ";
   JTextField field;

   Keyboard() {
      super("Keyboard");
      .... set layout

      // create TextField
      field = new JTextField(80);

      // create buttons
      for(int i = 0; i < qwerty.length(); i++) {
          String label = "" + qwerty.charAt(i);
          add(new MyButton(label));
      }
      add(new BSPButton());

      ....

      class MyButton extends JButton implements ActionListener {

         // constructor
         MyButton(String name) {
            super(name);
            addActionListener(this);
         }
         // button was hit
         public void actionPerformed(ActionEvent e) {
           field.append(getText());    // append to field my label
         }
       }

       class BSPButton extends JButton implements ActionListener {

          BSPButton() {
            super("BSP");
            addActionListener(this);
          }
          public void actionPerformed(ActionEvent e) {
            String text = field.getText();
            if(text.length() == 0) 
               return;
            field.setText(text.subString(text.length() - 1));
          }
        }


Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10461
  • View blog
  • Posts: 38,758
  • Joined: 27-December 08

Re: I need to create an on-screen keyboard GUI using Java

Posted 01 April 2011 - 01:32 PM

First, not good practice to add JComponents dynamically on events like keyPress(). Second, remember that by default, JFrame uses BorderLayout. So using the add() method without specifying a BorderLayout constraint will result in only one element being displayed in the JFrame at full size. That is, unless you change the layout of the JFrame.

Personally, I prefer to create a separate JPanel to add my JComponents to. Then add that JPanel to the JFrame. Or you can use the JFrame's content pane, accessible through the getContentPane() method.

You're missing the concept of arrays if you are initializing them one by one. Seriously, use a loop.

As for the background of the JButtons, use the JButton getBackground() method in the constructor, and store the Color in an instance variable. Then it's pretty straight-forward to alternate between that instance variable and another Color for the JButtons.
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: I need to create an on-screen keyboard GUI using Java

Posted 01 April 2011 - 01:51 PM

View Postgutchman84, on 01 April 2011 - 03:17 PM, said:

How should I implement the getBackground (so that the correct JButton changes color when the corresponding key is pressed) and setBackground (so that the correct JButton changes to its original color when the corresponding key is released) methods in my program?


In my RPN Calculator tutorial
http://www.dreaminco...rpn-calculator/

check my Btn class.

It uses a Swing Timer to change the color of the buttons and to produce a fade out effect (actually very cute :)) when the user passes over a button with the Mouse but could easily adapted to work when the user click on the button, or the corresponding key, rather than pass over with the mouse
Was This Post Helpful? 0
  • +
  • -

#10 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: I need to create an on-screen keyboard GUI using Java

Posted 01 April 2011 - 08:48 PM

Well I copied and pasted this code into a Keyboard.java file, and the following lines of code are picked up as errors:

add(new MyButton(label));
field.append(getText()); // append to field my label
field.setText(text.subString(text.length() - 1));

do I need to create methods for these lines in order to fix these errors?

View Postpbl, on 31 March 2011 - 07:20 PM, said:

I would use a complete different approach a lot shorter as far as I am concerned and without KeyListener

class Keyboard extends JFrame {

   // all key but BSP
   String qwerty = "QWERTYUIOPASDFGHJKLZXCVBNM ";
   JTextField field;

   Keyboard() {
      super("Keyboard");
      .... set layout

      // create TextField
      field = new JTextField(80);

      // create buttons
      for(int i = 0; i < qwerty.length(); i++) {
          String label = "" + qwerty.charAt(i);
          add(new MyButton(label));
      }
      add(new BSPButton());

      ....

      class MyButton extends JButton implements ActionListener {

         // constructor
         MyButton(String name) {
            super(name);
            addActionListener(this);
         }
         // button was hit
         public void actionPerformed(ActionEvent e) {
           field.append(getText());    // append to field my label
         }
       }

       class BSPButton extends JButton implements ActionListener {

          BSPButton() {
            super("BSP");
            addActionListener(this);
          }
          public void actionPerformed(ActionEvent e) {
            String text = field.getText();
            if(text.length() == 0) 
               return;
            field.setText(text.subString(text.length() - 1));
          }
        }


Was This Post Helpful? 0
  • +
  • -

#11 gutchman84  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-March 11

Re: I need to create an on-screen keyboard GUI using Java

Posted 04 April 2011 - 03:26 PM

Well check this out: here's my program using arrays and loops. My big problem is implementing setBackground (changes color of pressed key on the GUI) and getBackground (changes the corresponding key on the GUI back to it's original color when it is released) methods. Also, when I try to run the project, I get the following message in the Output window:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
at TypingTutor.<init>(TypingTutor.java:115)
at TypingTutorTest$1.<init>(TypingTutorTest.java:33)
at TypingTutorTest.main(TypingTutorTest.java:32)

I don't think my arrays are out of bounds. Why won't the GUI start? Here's my code so far:

// imports used
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

// TypingTutor.java
public abstract class TypingTutor extends JFrame implements KeyListener
{


    // JButton declarations for keys
    // design
    //1. create an array of MAX JButtons. Let's call it keys.
    //2. Instantiate and initalize every keys element
   //         keys[TheKeyCodeOfA] = new JButtons("A")
   //         keys[TheKeyCodeOfB] = new JButtons("B")
    //        ....
    //3. code the keypressed and keyreleased event
    //   in the event handler, you use the event.getKeyCode to get the
    //    index of the arrray
    //    int keycode = event.getKeyCode();
    //     keys[keycode].setBackground(Color.PINK);
    
    String firstRow[] = {"~","1","2","3","4","5","6","7","8","9","0","-","+","Back\nSpace"};
    String secondRow[] = {"Tab","Q","W","E","R","T","Y","U","I","O","P","[","]","|"};
    String thirdRow[] = {"Caps\nLock","A","S","D","F","G","H","J","K","L",";","'","Enter"};
    String fourthRow[] = {"Shift","Z","X","C","V","B","N","M",",",".","?","Space"};
    JButton first[] = new JButton[14];
    JButton second[] = new JButton[14];
    JButton third[] = new JButton[14];
    JButton fourth[] = new JButton[14];
    Panel keys = new Panel();
    Panel text = new Panel();
    TextArea textArea = new TextArea();
    String strText = "";
    private JLabel label1;
    private JLabel label2;
    private JTextField textField;
    

    public TypingTutor()
        {
            super("Typing Application");
            label1 = new JLabel("Type some text using your keyboard.  The keys you press will be "
                + "highlighed and the text will be displayed");
            add(label1);
            label2 = new JLabel("Note: clicking the buttons with your mouse will not perform any action");
            add(label2);
            
            textField = new JTextField(80);
            textField.setEditable(true);

            TextFieldHandler handler = new TextFieldHandler();

            this.setLayout(new BorderLayout(1,1));
		keys.setLayout(new GridLayout(4,14));
		text.setLayout(new BorderLayout(1,1));
		text.add(textArea);

                for(int i=0; i<14; i++)
		{
			first[i] = new JButton(firstRow[i]);
			first[i].setBackground(Color.white);
			keys.add(first[i]);
			first[i].addKeyListener(this);
		}
		for(int i=0; i<14; i++)
		{
			second[i] = new JButton(secondRow[i]);
			second[i].setBackground(Color.white);
			keys.add(second[i]);
			second[i].addKeyListener(this);
		}
		for(int i=0; i<14; i++)
		{
			third[i] = new JButton(thirdRow[i]);
			third[i].setBackground(Color.white);
			keys.add(third[i]);
			third[i].addKeyListener(this);
		}
		for(int i=0; i<14; i++)
		{
			fourth[i] = new JButton(fourthRow[i]);
			fourth[i].setBackground(Color.white);
			keys.add(fourth[i]);
			fourth[i].addKeyListener(this);
		}
		add(text, BorderLayout.NORTH);
		add(keys,BorderLayout.CENTER);
        }   // end five-argument constructor


        
       





   private class TextAreaHandler implements ActionListener
   {
      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = ""; // declare string to display

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == textField )
            string = String.format( "%s",
               event.getActionCommand() );
       }
    }
    // overridden keyReleased method handles press of any key
    @Override
    public void keyReleased( KeyEvent event )
    {
        int keyCode = event.getKeyCode();
        strText = String.format( "%s"+KeyEvent.getKeyText(keyCode) );
        getBackground();

    }

    @Override
    public void keyTyped( KeyEvent event )
    {
        int keyCode = event.getKeyCode();
        strText = String.format( "%s", event.getKeyCode() );

    }

    private class TextFieldHandler implements ActionListener
    {
      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = ""; // declare string to display

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == textField )
            string = String.format( "%s", event.getActionCommand() );
       }
    }
}


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

// TypingTutorTest.java
public class TypingTutorTest
{
    public static void main(String[] args)
    {
        TypingTutor typingTutor = new TypingTutor()
        {

            public void keyTyped(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            public void keyPressed(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            public void keyReleased(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        };    // creates TypingTutor
        typingTutor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        typingTutor.setSize(600, 500);      // set dimensions of window
        typingTutor.setVisible(true);
    }   // end main
}   // end class TypingTutorTest






View Postmacosxnerd101, on 01 April 2011 - 01:32 PM, said:

First, not good practice to add JComponents dynamically on events like keyPress(). Second, remember that by default, JFrame uses BorderLayout. So using the add() method without specifying a BorderLayout constraint will result in only one element being displayed in the JFrame at full size. That is, unless you change the layout of the JFrame.

Personally, I prefer to create a separate JPanel to add my JComponents to. Then add that JPanel to the JFrame. Or you can use the JFrame's content pane, accessible through the getContentPane() method.

You're missing the concept of arrays if you are initializing them one by one. Seriously, use a loop.

As for the background of the JButtons, use the JButton getBackground() method in the constructor, and store the Color in an instance variable. Then it's pretty straight-forward to alternate between that instance variable and another Color for the JButtons.

Was This Post Helpful? 0
  • +
  • -

#12 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10461
  • View blog
  • Posts: 38,758
  • Joined: 27-December 08

Re: I need to create an on-screen keyboard GUI using Java

Posted 05 April 2011 - 07:00 AM

The thirdRow array has 13 elements, and the fourthRow array only has 12. When you try to go to index 13 and 12 respective, you will get an ArrayIndexOutOfBoundsException.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1