Simple Keyboard input?

I am a new programmer trying to create a simple keyboard input for a Jframe, if that is possible. Here is a simple jframe creation:
    public static void main(String[] args) {
        JFrame frame = new JFrame("Keyboard input");
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        // make window visible
        frame.pack();
        frame.setVisible(true);
    If I wanted to make a class that would put a ball in the frame and have the ball move up, down, left, or right according to which arrow keys were pressed and held- how would I do that?
Thanks for your help,
Sam

See classes KeyListener and KeyAdapter
And reed the Manual

Similar Messages

  • Java applet simple keyboard input

    I am new to writing java applets and I am trying to write one that calls for a number from the user, this number becomes the amount of random numbers that are generated and displayed. So what is the best way to get a number from the user with an applet?

    Thanx for the help, but in searching around more and more I decided to use the JOptionPane.

  • Simple User-Input AKA a DOS application.

    I've been doing some programming using the simple DOS commands, and reading keyboard input to read strings into variables.
    I've got an Applet at the moment with a text area (several rows high), and a text field (single line), and I've got the text area reading a string variable into it, and the text field appending it's value to the variable on the event that you hit enter..
    But the issue I'm having is that, unlike the DOS commands, I can't get the processing to stop and wait for an input, then continue...
    If anyone could help out, it would be great, Thanks!

    Here's my code at the moment... the commented out lines in the input class are wherre im playing around at the moment...
    Any help or references appreciated.
    Thanks :)
    // File: Console.java
    package MyConsoleIO;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Console extends JApplet
                        implements ActionListener{
        private JTextField      inputBox;
        private JTextArea      textBox;
        private String           gotString = "";
        private Game           game;
        public void trace(String msg){System.out.println(msg);}
        public void println(String msg){
             textBox.append("\n"+msg);
             trace("Tried to print: "+msg);
        public void init() {
             game = new Game();
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        createGUI();
            } catch (Exception e) {
                System.err.println("createGUI didn't successfully complete");
        private void createGUI() {
            JPanel contentPane = new JPanel(new GridBagLayout());
            contentPane.setBorder(BorderFactory.createCompoundBorder(
                                        BorderFactory.createLineBorder(Color.BLACK),
                                        BorderFactory.createEmptyBorder(10,10,5,5)));
            setContentPane(contentPane);
            GridBagConstraints c = new GridBagConstraints();
            c.insets = new Insets(0,0,5,5);
    //        // Label
    //        JLabel receiverLabel = new JLabel(">",
    //                                          JLabel.TRAILING);
    //        add(receiverLabel, c);
            // Text Field
            inputBox = new JTextField("Type Something", 10);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = 1.0;
            add(inputBox, c);
            inputBox.addActionListener(this);
            // Button
            JButton button = new JButton(">");
            c.gridwidth = GridBagConstraints.REMAINDER; //end row
            c.anchor = GridBagConstraints.LINE_START; //stick to the
                                                      //text field
            c.fill = GridBagConstraints.NONE; //keep the button
                                              //small
            c.weightx = 0.0;
            add(button, c);
            button.addActionListener(this);
            // Text Box
            textBox = new JTextArea(30, 80);
            textBox.setEditable(false);
            c.anchor = GridBagConstraints.CENTER; //reset to the default
            c.fill = GridBagConstraints.BOTH; //make this big
            c.weighty = 1.0;
            add(new JScrollPane(textBox), c);
        public void actionPerformed(ActionEvent event) {
             textBox.append("\n"+inputBox.getText());
             gotString = inputBox.getText();
             inputBox.setText("");
             Input.inString = gotString;
        public void start(){
             textBox.append(Output.messagelist);
    // File: Game.java
    package MyConsoleIO;
    public class Game{
         public Game(){
              Output.println("Game Started!");
              String name = Input.getString("Please enter your name: ");
              Output.println(name + ", ay... how odd.");
              Output.println("GAME OVER");
    // File: Input.java
    package MyConsoleIO;
    public class Input{
         static public String inString = "";
         public static String getString(String message){
              Output.println(message);
    //          while(inString.length() == 0){
    //               // wait for some input...
              return inString;
    // File: Output.java
    package MyConsoleIO;
    public class Output {
         public static String messagelist = "";
         public static void println(String line){
              messagelist += "\n" + line;
    }

  • Installed rdesktop - but keyboard input still goes to Mac Terminal??

    My work PC has been "upgraded" to Windows 7 which made the Microsoft Remote Desktop Connection v2.0.1 stop working (it connects OK, I can login and see my work PC screen, but as soon as I try to do something I am "disconnected" from the PC).  I can't install RDC 2.1 because I have a PPC G5.
    So I searched for alternative remote desktop apps.  Cord 0.5.0 crashes on my machine and 0.5.5 won't even start up.
    I ended up installing rdesktop (www.rdesktop.org)
    It looks promising - very fast, and gets me to my PC login screen.  My mouse pointer can click on the screen buttons, but any keyboard input appears in my G5 Terminal window and is not sent to the Windows 7 PC.  This makes it impossible to enter my Windows 7 password to login!
    I'm sure this is a simple problem to solve but I have no idea on how to solve it.
    Any clues appreciated.  Thanks.

    Try:
    rdesktop -x m -r clipboard:"CLIPBOARD" -g 1280x1024 -u<username> <hostip>
    I do recommend using ssh tunnel for RDP over internet. Is more secure and limits open ports to only ssh port in firewall.
    There are instructions about on how to use cygwin with RSA key login, turn off ssh password login when working properly.

  • HttpServer error in reading buffer size via keyboard input - HELP

    I've written a simple HttpServer program that reads keyboard input to construct a buffer to copy the requested file into the socket's output stream. I've done the string-to-integer conversion using BufferedReader and parse.Int. However, when I go to use the int later in the program, I keep getting the message "variable b may not have been initialized." Can anyone tell me what's missing from the code below? Thanks.
    private static void sendBytes(FileInputStream fis, OutputStream os)throws Exception
         //Construct a buffer via console input
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String str;
         int b;
              System.out.println("Enter desired buffer size or CTRL-C to break.");
         //Convert entry to an integer
         do
              str = br.readLine();
                 try
                   b = Integer.parseInt(str);
              catch(NumberFormatException e)
                   System.out.println("Invalid entry.");
         while((str=br.readLine())!=null);
         //Construct a buffer
         byte[] buffer = new byte;
         int bytes = 0;
         //Begin timing HTML page delivery
         long start, end;
              System.out.println("Timing for Web page delivery");
         start = System.currentTimeMillis();
         //Copy requested file into the socket's output stream
              while((bytes = fis.read(buffer)) != -1)
              os.write(buffer, 0, bytes);

    As the message suggests, what is missing is code to initialize the variable b. The first mention ("int b;") does not initialize it. The second mention ("b = Integer.parseInt(str);") only initializes it if no exception is thrown. So it's possible for b to be uninitialized when you actually try to use it.
    What do you need to change? First you need to decide what's to be done if the keyboard input isn't a valid integer. Do you have a default value in mind? If so, put that where you declare the variable ("int b = 42;"). If not, just initialize the variable to zero ("int b = 0;").

  • Multiple Keyboard inputs...

    I've finished up a version of Pong for extra credit for a Java class i am taking, and i ran into an interesting situation.
    I cannot figure out how to have a two player version of pong have both players control their paddles with the keyboard. The specific problem i run into is, when i enter one paddle to move, and the other attempts to move it stops the first paddle from moving, also there is the whole issue of the key delay that occurs when a key is held down. If anybody can help me out, i would be incredibly greatful.
    It seems like it could possibly being done, for example, in games ive played before a character has been able in mid run(holding arrow key) press another key(such as shift) and jump into the air, while still running, to perform a run-jump.
    I have tryed setting up a keyboard input test so if both keys are pressed both paddles move. This works for one movement, but have you ever tryed hitting two keys at once in word? they both will display once, their will be that short delay, then one of the two keys will continously repeat.
    Any advice? I have it working with one Keyboard input, and the other Mouse input, but the mouse clearly has a big advantage over the keyboard player...
    Thanks,
    Sean Green

    and the repeated key thing still happens as well as the delay....I guess you'll get this as long as you use keyTyped() for player1. Is
    there some reason why you're doing this?
    What I was thinking of was along these lines:boolean up1, up2, down1, down2;
    keyPressedHandler()
        if key is w up1=true
        if key is s down1=true
        if key is up, up2=true
        etc
    keyReleasedHandler()
        if key is w up1=false
        etc
    drawingCodeOrWhereever()
        if(up1 && !down1) player 1 is on the way up
        (else) if(down1 && !up1) player 1 is on the way down
        if(up2 && !down2) player 2 is on the way up
        (else) if(down2 && !up2) player 2 is on the way downYou may want to handle the case of up and down both pressed
    differently.
    If getting rid of keyTyped() doesn't help, post some code. An example
    simple enough to just show the problem woule be good. Say how
    you would make a dot move left-right and up-down indepently.

  • Keyboard Input Output Problems on Mac OS X

    Hey guys,
    I'm at college studying Java, however my teacher and the rest of the class all use the Kawa IDE, I've been using Project Builder, provided with Mac OS X. Our tutor gave us a class made up of various methods which the college designed to handle keyboard Input and Output, however when I import it I get unpredictable results. I've put it online at: http://www.lostroom.co.uk/inout/
    All I'm trying to do is run a simple program;
    import InOut;
    class CostReckoner
    public static void main(String[] args)
    // Declare the variables
    int quantity;
    double unitCost, basicCost, vatCost, totalCost;
    double vatRate = 0.175;
    // Input the number of items and the cost per item
    System.out.print("What is the unit cost of the items?");
    unitCost = InOut.readDouble();
    System.out.print("How many items in the order?");
    quantity = InOut.readInt();
    // Calculate the cost of the order
    basicCost = unitCost * quantity;
    vatCost = basicCost * vatRate;
    totalCost = basicCost + vatCost;
    //Output the total cost of the order
    System.out.println("Cost �"+InOut.format(basicCost,2));
    System.out.println("Vat �"+InOut.format(vatCost,2));
    System.out.println("Total �"+InOut.format(totalCost,2));
    I seem to need to press space bar after I input anything, as it doesn't recognise "Return" without it. Any ideas ??
    Strange thing is it seems to work fine on the PC Kawa IDE within college. Any advice you guys could offer would be really appreciated. Send me an email at: <[email protected]> if you can help.
    Regards, Gareth

    Hi thanks for your help, I tried compiling the code you gave me to read the streams, however I seem to be have problems with it.
    ERROR
    keys.java:18: unreported exception java.io.IOException; must be caught or declared to be thrown
    n=stream.read();
    HERE IS THE CODE I'M TRYING TO COMPILE
    import java.io.*;
    public class keys {
    public static void main(String[]arguments)
    BufferedInputStream stream = new BufferedInputStream(System.in);
    int n=0;
    while(true){
    n=stream.read();
    System.out.println(Integer.toHexString(n));
    if (n==0x30) break;// this termination condition is optional
    Any ideas ??

  • Kazakh keyboard input not works

    Hi.
    I'm can't figure out trouble with kazakh(cyrillic) input to text controls in Flex4.
    I'm embedded unicode fonts, and "Copy->Paste" kazakh text from notepad into flash app works fine!
    But i need to keyboard input. In my case ordinar cyrillic letters inputs normal, but kazakh-specific
    letters (located in keyboard's 1234 and 7890 keys) not works - ? symbol displays.
    Please, anyone help me. I'm wasting 2 weeks in attempt to resolve it.
    P.S: FlexSDK 4.0.0.12321, FP 10.0.42.34, OS Windows.

    When you paste and it works, take the string and look at the charCodeAt() for each character in the string.
    Then when you type, see if the keyDown event is reporting the same charCode or not.
    Another test is to verify that your browser can allow those characters when typed into an HTML INPUT tag.
    Hi!
    When i'm pasting kazakh letters into textInput, flexApp shows correct charCodes, e.g.:
    әіңғүұқөһ -> 1241 1110 1187 1171 1199 1201 1179 1257 1211
    but when i'm typing this letters from keyboard, flex shows these charCodes:
    ?і??????? -> 63 1110 63 63 63 63 63 63 63
    (cyrillic-kazakh letters located in place of 2,3,4,5,8,9,0,-,= symbols of keyboard, on simple click - lowercase, with ShiftKey - uppercase).
    testing app code:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
        <fx:Script>
            <![CDATA[
                import mx.controls.Alert;
                protected function richeditabletext1_keyDownHandler(event:KeyboardEvent):void
                protected function rt1_keyUpHandler(event:KeyboardEvent):void
                    ttt.text = "";               
                    for (var i:uint = 0; i<rt1.text.length; i++){
                        ttt.text = ttt.text+" "+ rt1.text.charCodeAt(i);
            ]]>
        </fx:Script>
        <fx:Style>
            @namespace s "library://ns.adobe.com/flex/spark";
            @namespace mx "library://ns.adobe.com/flex/mx";
            @font-face {
                src: url("arialuni.ttf"); /* Embed from file */
                fontFamily:"Thai_font";            
                /*unicodeRange:"Cyrillic";*/
                unicodeRange: U+0400-04F9;
                cff-hinting:none;
                embeddAsCFF:true;
            .test{
                font-family:Thai_font;
        </fx:Style>
        <s:TextInput id="ttt" width="100%" fontFamily="Arial Unicode MS"/>
        <s:TextInput id="rt1" x="562" y="243" text="RichEditableText" width="100%" height="500" enabled="true"
                            editable="true"  fontSize="18" keyDown="richeditabletext1_keyDownHandler(event)"
                            keyUp="rt1_keyUpHandler(event)"
                            direction="ltr"
                            styleName="test"/>
    </s:Application>

  • Keyboard Input

    http://www.rafb.net/paste/results/D3082433.html
    In that link are all three of my classes (UserInterface.java, CalcEngine.java, and Calculator.java)
    I'm trying to do keyboard input for the numbers, the decimal, all the operations and enter. But the way I have it set up, I can't get any of the methods in the CalcEngine.java to run once a button is pressed. It's hard for me the explain, but if you compile it and try looking at the code, you'll understand what I mean.
    -sachit

    Alright, I'll post the 3 classes here.
    #### UserInterface.java ####
    // Date Started: March 1, 2004
    // Date Finished: March 26, 2004
    // Program Description: A graphical user interface for the calculator.
    //                              No calculation is being done here. This class is
    //                              responsible just for putting up the display on
    //                              screen. It then refers to the "CalcEngine" to do
    //                              all the real work.
    import java.awt.*;
    import java.awt.event.*;
    public class UserInterface implements KeyListener
         private CalcEngine calc;
         Frame panelFrame=new Frame("Non-Scientific Calculator");
         static Label displayLabel;
         static String button="";
         // Method Name: UserInterface()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: A user interface for the given calcEngine.
         public UserInterface()
              makeFrame();
              panelFrame.setVisible(true);
         // Method Name: setVisible()
         // Parameters Passed: boolean variable visible
         //     Data Returned: None
         //     Method Purpose: Sets the panalFrame interface visible.
    public void setVisible(boolean visible)
              panelFrame.setVisible(visible);
         // Method Name: makeFrame()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: The full display of buttons and labels on the calculator.
         private void makeFrame()
              CalcEngine buttonHandler = new CalcEngine();
              Button[] myButtons=new Button[30];
              String[] labels={"","","BS","CE","C","PI","sin","cos","tan","%","sqrt","7","8","9","/","x�","4","5","6","x","1/x","1","2","3","-","-/+","0",".","=","+"};
              Font titleFont=new Font("Courier", Font.BOLD,20);
              Font buttonFont=new Font("Arial", Font.BOLD,13);
              String display="0";
              displayLabel=new Label(display);
              String info = buttonHandler.getInfo();
              Label infoLabel=new Label(info);
              //Labels all the buttons
              for(int i=0;i<myButtons.length;i++)
                   myButtons=new Button(labels[i]);
              panelFrame.setLayout(new BorderLayout(4,5));
              panelFrame.setBackground(Color.gray);
                   displayLabel.setFont(titleFont);
                   displayLabel.setAlignment(Label.RIGHT);
                   panelFrame.add("North",displayLabel);
              Panel secondPanel=new Panel();
              panelFrame.add("Center",secondPanel);
              secondPanel.setLayout(new GridLayout(6,5,5,2));
              secondPanel.setBackground(Color.gray);
                   for(int i=0; i<myButtons.length; i++)
                        secondPanel.add(myButtons[i]);     
                        myButtons[i].setFont(buttonFont);
                        myButtons[i].addKeyListener(this);
                        myButtons[i].addActionListener(buttonHandler);
                   myButtons[0].setBackground(Color.gray);
                   myButtons[0].hide();
                   myButtons[1].hide();
                   panelFrame.add("South",infoLabel);
              panelFrame.resize(270,250);
              panelFrame.show();
         // Method Name: redisplay()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Updates the display of the current number being inputed.
         //                         Also truncates the decimal if it is ".0".
         public static void redisplay()
              boolean itsInt=false;
              int doubleChecker = (int)CalcEngine.getDisplayValue();
              int intValue=0;
              if(CalcEngine.getDisplayValue() == (float)doubleChecker)
                   intValue=(int)Math.round(CalcEngine.getDisplayValue());
                   itsInt=true;
              if(itsInt)
                   displayLabel.setAlignment(Label.RIGHT);
                   displayLabel.setText("" +intValue);
              else
                   displayLabel.setAlignment(Label.RIGHT);
                   displayLabel.setText("" + CalcEngine.getDisplayValue());
         public void keyTyped(KeyEvent e)
              char keyChar = e.getKeyChar();
              button=""+keyChar;
              CalcEngine calcEng= new CalcEngine();
              if(keyChar == '+')
                   System.out.println("+ PRESSED!");
              else if(keyChar == '-')
                   System.out.println("- PRESSED!");
              else if(keyChar == KeyEvent.VK_SLASH)
                   System.out.println("/ PRESSED!");
              else if(keyChar == '*')
                   System.out.println("x PRESSED!");
              else if(keyChar == KeyEvent.VK_1)
                   System.out.println("1 PRESSED!");
              else if(keyChar == KeyEvent.VK_2)
                   System.out.println("2 PRESSED!");
              else if(keyChar == KeyEvent.VK_3)
                   System.out.println("3 PRESSED!");
              else if(keyChar == KeyEvent.VK_4)
                   System.out.println("4 PRESSED!");
              else if(keyChar == KeyEvent.VK_5)
                   System.out.println("5 PRESSED!");
              else if(keyChar == KeyEvent.VK_6)
                   System.out.println("6 PRESSED!");
              else if(keyChar == KeyEvent.VK_7)
                   System.out.println("7 PRESSED!");
              else if(keyChar == KeyEvent.VK_8)
                   System.out.println("8 PRESSED!");
              else if(keyChar == KeyEvent.VK_9)
                   System.out.println("9 PRESSED!");
              else if(keyChar == KeyEvent.VK_0)
                   System.out.println("0 PRESSED!");
              else if(keyChar == KeyEvent.VK_ENTER || keyChar == KeyEvent.VK_EQUALS)
                   calcEng.equals();
                   System.out.println("= PRESSED!");          
              else if(keyChar == KeyEvent.VK_PERIOD)
                   System.out.println(". PRESSED!");
              /*else
                   /// QUESTION: what do these next two lines do?
                   byte bytes[] = {(byte)keyChar};
                   System.out.println(bytes);
                   //     command = new String(bytes);
         public static String passButton()
              return button;
         public void keyPressed(KeyEvent e)
         public void keyReleased(KeyEvent e)
    #### CalcEngine.java #####
    // Date Started: March 1, 2004
    // Date Finished: March 26, 2004
    // Program Description: Does all the calculations for the calculator.
    import java.awt.event.*;
    import java.awt.*;
    public class CalcEngine implements ActionListener
         final int ARRAY_SIZE=100;
         String []buttonPressed = new String[ARRAY_SIZE];
         String buttonCheck="";
         static String userDisplay="";
         int numberLength=0;
         int currentNumber=0;
         int previousNumber=0;
         int currentElement=0;
         boolean allowDecimal=true;
         boolean cEPressed=false;
         String buttonCheckKey;
         // Method Name: CalcEngine()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Instance of the CalcEngine.
         public CalcEngine()
              buttonCheckKey=UserInterface.passButton();
              buttonCheck=buttonCheckKey;
              System.out.println("ButtonCheckKey " +buttonCheck);
              if(buttonCheck=="=")
                   if(currentElement>=2 && !buttonPressed[currentElement].equals(""))
                        equals();
              else if(buttonCheck.equals("C"))
                   clear();
              else if(buttonCheck.equals("CE"))
                   clearOne();
              else if(buttonCheck.equals("BS"))
                   backSpace();
              else if(buttonCheck.equals("sqrt"))
                   squareRoot();
              else if(buttonCheck.equals("sin") || buttonCheck.equals("cos") || buttonCheck.equals("tan"))
                   trig(buttonCheck);
              else if(buttonCheck.equals("PI"))
                   numPI();
              else if(buttonCheck.equals("1/x"))
                   oneOver();
              else if(buttonCheck.equals("x�"))
                   powerTwo();
              else if(buttonCheck.equals("-/+"))
                   negPos();
              //else if(buttonCheck.equals("."))
              //     decimal(event);
              else if((buttonCheck.equals("+") || buttonCheck.equals("-") || buttonCheck.equals("x") || buttonCheck.equals("/") || buttonCheck.equals("%")) && !buttonPressed[currentElement].equals(""))
                   operations(buttonCheck);
              //else     
              //     allNumbers(event);
              System.out.println("1st: "+buttonPressed[0]+ "\n2nd: " buttonPressed[1] "\n3rd: " buttonPressed[2] "\n4th: " buttonPressed[3] "\n5th: " +buttonPressed[4]);
              System.out.println("6th: "+buttonPressed[5]+ "\n7th: " buttonPressed[6] "\n8th: " buttonPressed[7] "\n9th: " buttonPressed[8]"\n");
         // Method Name: getDisplayValue()
         // Parameters Passed: None
         //     Data Returned: float variable N/A
         //     Method Purpose: Retrived the updated number to display on the calculator
         //                         and passes it as a double.
    public static double getDisplayValue()
              return Double.valueOf(userDisplay).doubleValue();
         // Method Name: actionPerformed()
         // Parameters Passed: ActionEvent variable event
         //     Data Returned: None
         //     Method Purpose: Run the correct method depending on what button is pressed.
         public void actionPerformed(ActionEvent event/*, String button, boolean keyBoard*/)
              //Removes null from buttonPressed array
              for(int i=0; i<buttonPressed.length; i++)
                   if(buttonPressed[i]==null)
                        buttonPressed[i]="";
              numberLength++;
              buttonCheck=event.getActionCommand();     //Gets the button that was pressed
              //Runs the correct method depending on which button is pressed
              if(buttonCheck=="=")
                   if(currentElement>=2 && !buttonPressed[currentElement].equals(""))
                        equals();
              else if(buttonCheck.equals("C"))
                   clear();
              else if(buttonCheck.equals("CE"))
                   clearOne();
              else if(buttonCheck.equals("BS"))
                   backSpace();
              else if(buttonCheck.equals("sqrt"))
                   squareRoot();
              else if(buttonCheck.equals("sin") || buttonCheck.equals("cos") || buttonCheck.equals("tan"))
                   trig(buttonCheck);
              else if(buttonCheck.equals("PI"))
                   numPI();
              else if(buttonCheck.equals("1/x"))
                   oneOver();
              else if(buttonCheck.equals("x�"))
                   powerTwo();
              else if(buttonCheck.equals("-/+"))
                   negPos();
              else if(buttonCheck.equals("."))
                   decimal(event);
              else if((buttonCheck.equals("+") || buttonCheck.equals("-") || buttonCheck.equals("x") || buttonCheck.equals("/") || buttonCheck.equals("%")) && !buttonPressed[currentElement].equals(""))
                   operations(buttonCheck);
              else     
                   allNumbers(event);
              System.out.println("1st: "+buttonPressed[0]+ "\n2nd: " buttonPressed[1] "\n3rd: " buttonPressed[2] "\n4th: " buttonPressed[3] "\n5th: " +buttonPressed[4]);
              System.out.println("6th: "+buttonPressed[5]+ "\n7th: " buttonPressed[6] "\n8th: " buttonPressed[7] "\n9th: " buttonPressed[8]"\n");
         // Method Name: clear()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "C" button is pressed. Clears all the numbers
         //                         inputted into the calculator.
         public void clear()
              for(int i=0; i<buttonPressed.length; i++)
                        buttonPressed[i]="";
              userDisplay="0";
              currentElement=0;
              numberLength=0;
              UserInterface.redisplay();
         // Method Name: clearOne()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "CE" button is pressed. Deletes the last
         //                         entire number inputted into the calculator. For example,
         //                         if "5x123" was inputted, it would go back to "5x".
         public void clearOne()
              if(currentElement >= 2)
                   buttonPressed[currentElement]="";
                   userDisplay=buttonPressed[currentElement-2];
                   numberLength=0;
                   cEPressed=true;
                   UserInterface.redisplay();
         // Method Name: backSpace()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "BS" button is pressed. Deletes the last
         //                         number inputted into the calculator. For example,
         //                         if "5x123" was inputted, it would go back to "5x12".
         public void backSpace()
                   int stringSize=buttonPressed[currentElement].length();
                   buttonPressed[currentElement] = userDisplay.substring(0, userDisplay.length() - 1);
                   userDisplay=buttonPressed[currentElement];
                   UserInterface.redisplay();
         // Method Name: trig()
         // Parameters Passed: String variable buttonCheck
         //     Data Returned: None
         //     Method Purpose: Is run if the "sin", "cos", or "tan" button is pressed.
         //                         Finds the sin, cos or tan of the current number.
         public void trig(String buttonCheck)
              if(buttonCheck.equals("sin"))
                   double sinThisNum=Double.valueOf(buttonPressed[currentElement]).doubleValue();
                   double sinNum=Math.sin(sinThisNum);
                   buttonPressed[currentElement]=""+sinNum;               
              else if(buttonCheck.equals("cos"))
                   double cosThisNum=Double.valueOf(buttonPressed[currentElement]).doubleValue();
                   double cosNum=Math.cos(cosThisNum);
                   buttonPressed[currentElement]=""+cosNum;                              
              else if(buttonCheck.equals("tan"))
                   double tanThisNum=Double.valueOf(buttonPressed[currentElement]).doubleValue();
                   double tanNum=Math.tan(tanThisNum);
                   buttonPressed[currentElement]=""+tanNum;                              
              userDisplay=buttonPressed[currentElement];
              UserInterface.redisplay();
         // Method Name: squareRoot()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "sqrt" button is pressed. Sqaures the current
         //                         number.
         public void squareRoot()
              if(currentElement==0 || currentElement % 2==0)
                   double rootThisNum=Double.valueOf(buttonPressed[currentElement]).doubleValue();
                   double rootedNum=Math.sqrt(rootThisNum);
                   buttonPressed[currentElement]=""+rootedNum;
                   userDisplay=buttonPressed[currentElement];
                   UserInterface.redisplay();
         // Method Name: numPI()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "PI" button is pressed. Allows the user to
         //                         input the value of PI.
         public void numPI()
              double PInumber=Math.PI;
              buttonPressed[currentElement]=""+PInumber;
              userDisplay=buttonPressed[currentElement];
              UserInterface.redisplay();
         // Method Name: oneOver()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "1/x" button is pressed. This will divide
         //                         the current number by 1.
         public void oneOver()
              if(currentElement==0 || currentElement % 2==0)
                   double oneOverNum=Double.valueOf(buttonPressed[currentElement]).doubleValue();
                   oneOverNum=1/oneOverNum;
                   buttonPressed[currentElement]=""+oneOverNum;
                   userDisplay=buttonPressed[currentElement];
                   UserInterface.redisplay();
         // Method Name: powerTwo()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "x^2" button is pressed. This will take the
         //                         current number to the power 2.
         public void powerTwo()
              if(currentElement==0 || currentElement % 2==0)
                   double powNum=Double.valueOf(buttonPressed[currentElement]).doubleValue();
                   powNum=Math.pow(powNum,2);
                   buttonPressed[currentElement]=""+powNum;
                   userDisplay=buttonPressed[currentElement];
                   UserInterface.redisplay();
         // Method Name: negPos()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "-/+" button is pressed. Toggles the number
         //                         between a negative and positive value.
         public void negPos()
              if(userDisplay.charAt(0)!='-')
                   userDisplay="-"+userDisplay;
              else
                   userDisplay=userDisplay.substring(1);
              buttonPressed[currentElement]=userDisplay;
              UserInterface.redisplay();
         // Method Name: decimal()
         // Parameters Passed: ActionEvent variable event
         //     Data Returned: None
         //     Method Purpose: Is run if the "C" button is pressed. Clears all the numbers
         //                         inputted into the calculator.
         public void decimal(ActionEvent event)
              if(allowDecimal)
                   buttonPressed[currentElement]+=event.getActionCommand();
                   userDisplay+=event.getActionCommand();
                   allowDecimal=false;
                   UserInterface.redisplay();
         // Method Name: operations()
         // Parameters Passed: String variable buttonCheck
         //     Data Returned: None
         //     Method Purpose: Is run if the "+","-","x","/","%" button is pressed. Depending
         //                         on which operation is selected, the calculator will perform that.
         public void operations(String buttonCheck)
              currentElement++;
              if(buttonCheck.equals("+"))
                   buttonPressed[currentElement]="+";
              else if(buttonCheck.equals("-"))
                   buttonPressed[currentElement]="-";
              else if(buttonCheck.equals("x"))
                   buttonPressed[currentElement]="x";
              else if(buttonCheck.equals("/"))
                   buttonPressed[currentElement]="/";
              else if(buttonCheck.equals("%"))
                   buttonPressed[currentElement]="%";
              currentElement++;
              numberLength=0;
              userDisplay="0";
              allowDecimal=true;               
         // Method Name: allNumbers()
         // Parameters Passed: ActionEvent variable event
         //     Data Returned: None
         //     Method Purpose: Is run if any of the numbers are pressed. Adds the inputted
         //                         number to the already ongoing number in the display.
         public void allNumbers(ActionEvent event)
              if(checkInt(event.getActionCommand()))
                   if(cEPressed)
                        buttonPressed[currentElement]+=event.getActionCommand();
                        UserInterface.redisplay();
                        userDisplay=event.getActionCommand();
                        cEPressed=false;                         
                        UserInterface.redisplay();
                   else
                        buttonPressed[currentElement]+=event.getActionCommand();
                        userDisplay+=event.getActionCommand();
                        UserInterface.redisplay();
         // Method Name: checkInt()
         // Parameters Passed: String variable dataInput
         //     Data Returned: None
         //     Method Purpose: A quick check to see if the button pressed is a number.
         //                         Rather than doing if(buttonCheck=="1") for every number.
         public boolean checkInt(String dataInput)
              try
                   int n=Integer.parseInt(dataInput);
                   return true;          
              catch (NumberFormatException nfe)
                   return false;
         // Method Name: equals()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Is run if the "=" button is pressed. Takes all the inputted
         //                         numbers and operations and executes all the calculations.
         public void equals()
              double firstNum=0;
              double secondNum=0;
              double currentAns=0;
              int howBig=0;
              for(int i=0; i<buttonPressed.length;i+=2)
                   if(buttonPressed[i]!="")
                        howBig++;
              firstNum=Double.valueOf(buttonPressed[0]).doubleValue();
              for(int j=0; j<=howBig-1; j+=2)
                   secondNum=Double.valueOf(buttonPressed[j+2]).doubleValue();
                   if(buttonPressed[j+1].equals("+"))
                        currentAns=firstNum+secondNum;
                   else if(buttonPressed[j+1].equals("-"))
                        currentAns=firstNum-secondNum;
                   else if(buttonPressed[j+1].equals("x"))
                        currentAns=firstNum*secondNum;
                   else if(buttonPressed[j+1].equals("/"))
                        currentAns=firstNum/secondNum;
                   else if(buttonPressed[j+1].equals("%"))
                        currentAns=firstNum%secondNum;
                   firstNum=currentAns;     
              for(int i=0; i<buttonPressed.length; i++)
                        buttonPressed[i]="";
              buttonPressed[0]=""+currentAns;
              currentElement=0;
              userDisplay=""+currentAns;
              UserInterface.redisplay();
         // Method Name: getInfo()
         // Parameters Passed: None
         //     Data Returned: String variable N/A
         //     Method Purpose: Return the title of this calculation engine.
         public String getInfo()
              return "ver 0.9 Copyright � 2001-2003 Harish.";
    ### Calculator.java ###
    // Date Started: March 1, 2004
    // Date Finished: March 26, 2004
    // Program Description: The main class of a simple calculator.
    public class Calculator
         private CalcEngine engine;
         private UserInterface gui;
         // Method Name: Calculator()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: Creates the calculator and displays it on the screen.
         public Calculator()
              engine = new CalcEngine();
              gui = new UserInterface();
         // Method Name: show()
         // Parameters Passed: None
         //     Data Returned: None
         //     Method Purpose: If the window is closed, it will show it again.
         public void show()
              gui.setVisible(true);
         // Method Name: main()
         // Parameters Passed: String variable []args
         //     Data Returned: None
         //     Method Purpose: The main method that runs the Calculator()
         public static void main(String [] args)
              new Calculator();
    -s64

  • Keyboard Input Sans Keyboard

    I'm looking for the most simple program that will let me do keyboard input from a bash script.  (or if library I can write a quick script with). Being able to move the mouse as well is also desired, or a seperate program/library for that.
    Thanks.
    Last edited by Mardoct (2010-06-12 21:14:16)

    Im not sure what you want? Do you want to simulate keypresses in an X environment?

  • Keyboard input - single char

    All I want is a single character of keyboard input. Is there a better (simpler) way to do this?
    byte[]     bInput;
    String     cResult;
    bInput = new byte[1];
    bInput[0] = 0;
    System.out.print("\nStart FirewallChat in [C]lient or [S]erver mode? ");
    try
    {     System.in.read(bInput);
    } catch (IOException e)
    {     System.out.println("System.in.read(byte[] b) threw IOException. An I/O error occurred - maybe the input stream has been closed? Exception follows : " + e);
    System.out.println(Character.toLowerCase((char)new Byte(bInput[0]).intValue()));

    char c = (char)System.in.read();

  • TS3280 How can i enable both paired bluetooth and ios keyboard input at the same time?

    How can i enable both paired bluetooth and ios keyboard input at the same time?
    This is needed for the app im working on. Need some user input via keypad as well as scanner input via a paired bluetooth scanner.

    You probably should not be using a keyboard bluetooth profile for a scanner, I am not a developer for apple so do not know the location for you to find out the correct profile you should be using for an input device that is not a keyboard. Sorry,
    I am sure if you navigate the apple developer site you will probaly finmd what you're looking for.
    https://developer.apple.com

  • I have a new mac book pro (sept 2014) and am suddenly stuck on the log-in screen. Keyboard input not working to enter my password. Already tried a basic restart and a cmmnd/ cntrl/ pwr troubleshoot to no effect.

    I have a new mac book pro (sept 2014) and am suddenly stuck on the log-in screen. Keyboard input is not working to enter my password. Seems to be a log in issue as keyboard works for forced troubleshooting. (And b/c when I first noticed the problem, I was able to enter my log in password but then everything sort of froze. Now, no ability to enter the password.) Already tried a basic restart and a cmmnd/ cntrl/ pwr troubleshoot to no effect.

    Reset PRAM:   http://support.apple.com/kb/PH14222
    Start up in Safe Mode.
    http://support.apple.com/kb/ph14204
    A new Mac is in warranty for 1 year from the date of purchase.
    A new Mac comes with 90 days of free tech support from AppleCare.
    AppleCare: 1-800-275-2273
    Call AppleCare or take it to the Apple store to have it checked out.
    Genius Bar reservation
    http://www.apple.com/retail/geniusbar/
    Best.

  • How to have same keyboards input source in Mac and Windows???

    I use Canadian French-CSA on my Mac keyboards input source. Using Windows 7, I can't find the good setting for my keyboards to be the same when I it keys.
    I run Windows over Parallels Desktop
    Can anybody help?
    Thank you

    Can I use an AirPort Extreme Base Station "n"
    Yes.
    and if so, will my MacBook work with this at maximum download / upload speed (i.e. equivalent to the cable)
    The speed of your internal network generally is much much faster than the speed of your internet connection. Unless he has an internet connection faster than approx 6Mbps then even dropping down to the old 802.11b Airport would not seen any decrease in speed of downloads etc...
    and will my brother's PC's also be able to connect?
    If his PC is 802.11b/g-compliant, it shouldn't have any problems connecting to the AirPort base station.
    Or is there another Airport base station?
    The other AirPorts would work, but the AirPort Express & older 802.11g AirPort Extreme base stations have a max. range of 150 feet.
    OR-- should I head down to "Generic Computer Store" and just by a wireless router (WiFi)(think that's what they call them) and connect this to his cable modem? IF SO WILL THAT WORK FOR MY MAC?
    That is always an option as well, especially since he will be the primary user throughout the year. I'd suggest going with a brand name, like Belkin, D-Link, or Linksys for the wireless router choice.

  • How to use the phone's Mini-Keyboard Input with the 'Textbox'(MIDP2.0)?

    (My apology. My English is not perfect but I'll try my best. >_<)
    Hi. I'm trying to create a textbox(in my own little application) that is compatible with the mini-keyboard input feature.
    This problem involved any device that have a built-in "mini-keyboard".
    Problem:
    I tried the 'Textbox' class from MIDP2.0 but the result, as expected, is like using the phones with no built-in keyboard.
    (Forexample if I want to input the character 'C' inthe text box, I need to press number '2' button three times to let it circle through 'A' -> 'B' then 'C'. )
    Then I tried entering URLs in the phone's built-in web browser, the result is I can use the mini keyboard to type like a PC keyboard.
    Question: How do I implement such textbox that is fully compatible with the built-in mini Keyboard?
    I tried browsing through the MIDP2.0 API but it seems the 'Textbox' class there couldn't do it.
    Thank you. =)
    /bow
    Edit/Delete Message

    The textbox should have input just as any other normal phone input. If not, something strange is going on.
    Anyway , there is no use to make your own input method, since every phone has another implementation of this anyway. It would only confuse users.

Maybe you are looking for

  • Remove element in linked list linked list

    here's my codes public class Student     private String name, matric;     public Student(){}     public Student( String name, String matric)        this.name = name;        this.matric = matric;      public String getName()      { return name;}     

  • Please tell me the significance of the alphanumerics in the serial number of my sound ca

    Hi, Will you please tell me the significance of the several letters and numbers in the serial number of my sound card. It is: MASB046755000468S. I am expecting that it will reveal the model family, the sub classification amongst that family, retail o

  • Where does the JAVA_DEPLOY role get created????

    Environment: OWB 10g Runtime: 9.2.0.4 Repository: 9.2.0.4 OS: AIX 5.2 I am trying to create a Runtime Repository on an RS6000 and am getting an error inthe log file that says the JAVA_DEPLOY role is not created. OK, I give up. I have searched and rea

  • Ghost emails in iPhone Exchange client

    For some reason occasionally when I delete an email while working on the iPhone they get deleted from the Exchange server but not from the phone itself. Subsequently when I try to delete them from the phone I get a message stating that they can not b

  • Prepaid Plan Change

    Hello, I'm currently have the $40/month plan which includes 1GB data.  Thinking about it I realized that 1GB is probably not enough for my needs. If I were to change plans now would I lose everything I have remaining on my current, $40/month, plan?