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.

Similar Messages

  • 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

  • Can java program simulate keyboard input?

    is it possible to create a java program or applet that simulates an end-user's keyboard input into another java applet? is it also possible to feed the output of that target applet to a file based on the different input combinations?
    and How?
    Thanks.

    Take a look at the API-docs for the class java.awt.Robot . This generates system-level input-events. Might not work in an applet, I do not know whether an applet has the right to do this.
    The second question is actually the more difficult one, since normal applets can not do file access.

  • Keyboard input failure in 2nd java applet

    The (London) Times offers crosswords developed as Java applets. With Mandriva 2007 newly installed on my laptop (Firefox 1.5.0.8, JRE1.5.0_08), I completed one crossword and loaded a second: no keyboard input to cells, no focus shown on cells. Killed the applet, reloaded: same problem. Quit Firefox, restarted crossword: same problem. Quit session, restarted, reloaded Firefox and crossword: same problem.
    Upgraded to Firefox 2.0 and JRE1.5.0_09. Started a crossword with a couple of entries, quit and started a second: same problem - no focus on cell, no input.
    I think this is connected in some way with Mandriva 2007, because the combination Mandriva 2006 with Firefox 1.5.0.7 and JRE 1.4.2-09 works correctly.
    I believe the problem lies initially with Java, because keyboard input to non-Java pages in Firefox worked without problems.

    I have exactly the same problem with opera 9.02 browser, jre1.6, linux debian sarge and the crossword puzzle of "Le Monde" http://www.lemonde.fr/web/article/0,1-0@2-3280,36-139043,0.html
    It worked with jre 1.4 linux FC2, same opera.

  • Applet opens a form doesn't allow keyboard input

    Hi,
    I testing something so everything I've done is really simple. I wrote a JApplet that has a JMenubar. Selecting a menu item opens a new webpage which contains an HTML form. The form has 2 radio buttons and a text field. The problem is I can't type anything into the text field. Press keys just causes the computer to go "ding" at me.
    If I open a new browser for the form the text field is accessible. I want to keep the form in the same window. What's wrong with my code?
    <applet>
    import java.applet.Applet;
    import java.awt.Graphics;
    import javax.swing.*;
    import javax.swing.JApplet.*;
    import java.awt.event.*;
    import java.net.*;
    public class MenuApplet extends JApplet
    StringBuffer buffer;
    public void init()
    buffer = new StringBuffer();
    /* addItem("init..."); */
    try
    javax.swing.SwingUtilities.invokeAndWait(new Runnable()
    {public void run()
                                                             {createMenu();}
    catch (Exception e)
    { System.err.println("createMenu didn't successfully complete"); }
    void createMenu()
    JMenuBar jmb = new JMenuBar();
    setJMenuBar(jmb);
    JMenu menu = new JMenu("Listings");
    jmb.add(menu);
    JMenuItem contactList = new JMenuItem("Contacts");
    menu.add(contactList);
    JMenuItem customerList = new JMenuItem("Customers");
    menu.add(customerList);
    contactList.addActionListener(new ActionListener()
    { public void actionPerformed(ActionEvent ae)
    { boolean good;
    good = linkTo("file:///c:/1.private/pages/testform.html");
    void addItem(String newWord)
    System.out.println(newWord);
    buffer.append(newWord);
    repaint();
    private boolean linkTo(String theURLString)
    try
    URL theURL = new URL(theURLString);
    getAppletContext().showDocument(theURL);
    catch(MalformedURLException e)
    System.out.println("Bad URL: " + theURLString + "\n");
    return false;
    return true;
    </applet>
    <html>
    <HTML>
    <HEAD>
    <TITLE></TITLE>
    <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
    <meta name="generator" content="CSE HTML Validator Professional (http://www.htmlvalidator.com/)">
    </HEAD>
    <BODY>
    <APPLET CODE="MenuApplet.class" WIDTH="100%" HEIGHT="25px"></APPLET>
    </BODY>
    </HTML>
    </html>
    <html form>
    <HTML>
    <HEAD>
    <TITLE>Testing forms</TITLE>
    </HEAD>
    <BODY ONLOAD="document.tf.criteria.focus()">
    <!-- <FORM METHOD="POST" ACTION="tracker/jte/contactslist.p"> -->
    <FORM NAME="tf" METHOD="POST" ACTION="file:///c:/1.private/pages/tables.html">
    <FIELDSET>
    <P>Search by:<BR>
    <INPUT TYPE="RADIO" NAME="searchtype" VALUE="customer" CHECKED>Customer <BR>
    <INPUT TYPE="RADIO" NAME="searchtype" VALUE="contact">Contact <BR>
    </P>
    <P>
    Enter name:
    <INPUT TYPE="TEXT" NAME="criteria" VALUE="who">
    </P>
    <INPUT TYPE="SUBMIT">
    </FIELDSET>
    </FORM>
    </BODY>
    </HTML>
    </html form>

    P.S. This problem occurs when using Netscape 6.2. The applet works fine with IE 6.0.26. Other than "use ie" does anyone have any suggestions?

  • CS1 for Java (Keyboard Input)

    I downloaded CS1 for my Comp. Sci class in order to use Keyboard input in my Java coding. However, I don't know where to put the downloaded .jar file. Could somebody please help me? This is where I downloaded it from: http://duke.csc.villanova.edu/jss1/bookResources/keyboard.jsp
    Thanks

    Hi Max
    It's not your fault but I am appalled that Java teachers are still using bodges like the Keyboard class, when the standard Scanner class has been available for over 12 months.
    So here's what I suggest:
    1) Try putting the jar file into /Library/Java/Extensions
    2) Tell your tutor to get his notes up to date and use the Scanner class instead of Keyboard
    Bob

  • Java applets in a browser, and Serial port input

    I know that there is a special package for serial port input in java. (java.Comm.SerialPort)
    What I am trying to figure out before a final decision on design is made, is if there is anyway of reading serial port input into a java applet that is running inside of a browser.
    I have found lots of reference to Serial port input, but nothing that really goes in the direction that I am lookind for.
    Any little tid bits of information pertaining to this would be greatly appreciated.
    Cuervo

    You should also consider that applets are not allowed to access their client system's hardware without being signed; in other words, the user must agree (by clicking a button) to disable the applet security features. Why would you use an applet to do this? Applets are meant to be an extension of a website. You should use an application in this situation.

  • 2 simple java applet

    Hi
    I have 2 short questions about java applets.
    1. when my applet comes up in the web browser, I have to click it before it will identify and fire off keyup and keydown method. (it's like i have click it with the mouse to wake it up or put it in focus) these are the methods i'm using
    public boolean keyUp(Event e, int key){
         showStatus(" ");
         return true; }
    public boolean keyDown(Event e, int key){
    return true;}
    QUESTION: Is there something special, that I have to do to make it automatically accept or see keyDown actions.
    2. QUESTION 2: What is the syntax to capture key event for the Spacebar and Esc button?
    For example I know that the event to catch the letter m is like this :
    if(key=='m'||key=='M'){
    and function key is caught like this
    if(key==Event.F1){
    But how do I catch the spaceBar and Escape?
    Thanks a lot in advance.
    Stephen
         

    hi is requestFocus() part of jdk 1.0 ?
    Have you ever used it before successfully?
    If so, can type a little syntax about how it works ?
    and to the person who had the javascript solution could you type a little syntax about how it works ? i also tried that. i put my applet in a div container and try to give it focus. I also tried to give the applet itself a name and give it focus with
    document.appletname.focus();

  • 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;
    }

  • Java Applet in a HTML page: failing with PLS-00306: wrong number of args

    We are trying to use a Java Applet in a HTML page. as our system needs to be able to retrieve a predefined set of data from a third party system that uses Dynamic Data Exchange Protocol (DDE) and are encountering errors from APEX and in IE itself.
    We are using JavaDde from www.nevaobject.com that enables our Java applet to interact with Windows applications (Third Party System) using DDE.
    This functionality is currently used in our Web Form 6i application and we are trying to use the same in the new ApEx application.
    We are using ApEx version : 2.1 and actually aer encountering 2 problems:
    Problem 1: ApEx failing with PLS-00306: wrong number or types of arguments in call to 'ACCEPT'
    Problem 2: IE crashes if Applet used in a complex page with several regions (1 Context, 4 Report Regions, 2 level Tabs, Links)
    This problem does not occur in the page where there is only applet and one region. In the case of complex page the IE crashes if the page is reloaded
    Test scenario:
    1- Create a simple page with the HTML region.
    2- Define the Source of the above region as follows
    <OBJECT CLASSID="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    CODEBASE="http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-i586.cab#version=1,4,0,0"
    WIDTH="1"
    HEIGHT="1"
    ID="simpleApplet"
    NAME="simpleApplet">
    <PARAM NAME="code" VALUE="simpleApplet.class" >
    <PARAM NAME="archive" VALUE="simpleApplet.jar" />
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.4">
    </OBJECT>
    3- Create a simple Java applet "simpleApplet" - for the test its enough if the applet will have just the init method printing out the mesage to the console
    4- Create a Submit Button (not redirect) in Region Header and create unconditional (do not set When Button Pressed property) Page Branch to navigate to another page (the page without the applet)
    6- Run the page and Submit -
    The error below is returned by the engine:
    In our case our applet is called ddeApplet - I do not know why is ApEx passing the Applet's ID down to the wwv_flow.accept method as a parameter
    Tue, 24 Jul 2007 08:15:39 GMT
    ORA-06550: line 7, column 2:
    PLS-00306: wrong number or types of arguments in call to 'ACCEPT'
    ORA-06550: line 7, column 2:
    PL/SQL: Statement ignored
    DAD name: rbdev2_ax
    PROCEDURE : wwv_flow.accept
    URL : http://castor:7778/pls/rbdev2_ax/wwv_flow.accept
    PARAMETERS :
    ============
    P_FLOW_ID:
    147
    P_FLOW_STEP_ID:
    500
    P_INSTANCE:
    6986070096861669560
    P_PAGE_SUBMISSION_ID:
    1005758
    P_REQUEST:
    CRASH
    P_ARG_NAMES:
    100380029717786501
    P_T01:
    147
    P_T02:
    101
    P_T03:
    5000044
    P_T04:
    1
    P_T05:
    S
    DDEAPPLET:
    Ddeapplet[panel0,0,0,1x1,layout=java.awt.BorderLayout,rootPane=javax.swing.JRootPane[,0,0,1x1,layout=javax.swing.JRootPane$RootLayout,alignmentX=null,alignmentY=null,border=,flags=385,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    P_MD5_CHECKSUM:
    ENVIRONMENT:
    ============
    PLSQL_GATEWAY=WebDb
    GATEWAY_IVERSION=2
    SERVER_SOFTWARE=Oracle HTTP Server Powered by Apache/1.3.19 (Unix) mod_fastcgi/2.2.10 mod_perl/1.25 mod_oprocmgr/1.0
    GATEWAY_INTERFACE=CGI/1.1
    SERVER_PORT=7778
    SERVER_NAME=castor
    REQUEST_METHOD=POST
    QUERY_STRING=
    PATH_INFO=/pls/rbdev2_ax/wwv_flow.accept
    SCRIPT_NAME=/pls
    REMOTE_HOST=
    REMOTE_ADDR=192.168.66.169
    SERVER_PROTOCOL=HTTP/1.1
    REQUEST_PROTOCOL=HTTP
    REMOTE_USER=
    HTTP_CONTENT_LENGTH=661
    HTTP_CONTENT_TYPE=application/x-www-form-urlencoded
    HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
    HTTP_HOST=castor:7778
    HTTP_ACCEPT=image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*
    HTTP_ACCEPT_ENCODING=gzip, deflate
    HTTP_ACCEPT_LANGUAGE=en-us
    HTTP_ACCEPT_CHARSET=
    HTTP_COOKIE=ISCOOKIE=true; LOGIN_USERNAME_COOKIE=rdanko; ORACLE_PLATFORM_REMEMBER_UN=RDANKO:ngrb; WWV_FLOW_USER2=70FBB00945FE46B9; V6_AUTHENTICATION_COOKIE=70FBB00945FE46B9
    Authorization=
    HTTP_IF_MODIFIED_SINCE=
    HTTP_REFERER=http://castor:7778/pls/rbdev2_ax/f?p=147:500:6986070096861669560:::::
    HTTP_SOAPACTION=

    "theArrow",
    It looks like whatever HTML you're including on your page is creating HTML input form elements inside the HTML form "wwv_flow". This form is posted to wwv_flow.accept, and of course, the PL/SQL procedure wwv_flow.accept doesn't know anything these additional arguments/form elements you're attempting to POST.
    Joel

  • The window of a java applet is not displayed by Netscape7.1.

    I am using Netscape7.1.
    A parent window is only what opens a new window.
    Please see index.html.
    --------index.html--------
    <HTML>
    <HEAD><TITLE>OYA</TITLE></HEAD>
    <BODY>
    <FORM>
    <CENTER><BR><BR><BR><BR><BR><BR><BR><BR>
    <input type="button" onClick="WIN=open('KODOMO.html', 'win_new_comp', ''); WIN.focus();" value="Open the Window">
    </FORM>
    </CENTER>
    </BODY>
    </HTML>
    There is a button of "CLOSE" with the Java applet called "SimplaApplet.class" in the window opened newly.
    Please see KODOMO.html and SimplaApplet.java.
    --------KODOMO.html--------
    <html>
    <title>Using Applet</title>
    <body>
    <FORM>
    <CENTER><BR><BR><BR>
    <!-- for IE -->
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"width="100" height="50">
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.4">
    <PARAM NAME="java_CODE" VALUE="SimpleApplet">
    <COMMENT>
    <!-- for Netscape-->
    <EMBED type="application/x-java-applet;version=1.4"
    width="100" height="50"
    code="SimpleApplet">
    </EMBED>
    </COMMENT>
    </OBJECT><BR><BR><BR><BR><BR><BR>
    <INPUT TYPE="button" VALUE="CLOSE" onClick="window.close()">
    </CENTER>
    </FORM>
    </BODY>
    </HTML>
    --------SimpleApplet.java--------
    import java.awt.*;
    import java.applet.*;
    public class SimpleApplet extends Applet {
    public void paint (Graphics g) {
    g.drawString("Simple Applet", 10, 30);
    The following operations are performed at this time.
    Step1: "Open the Window" is clicked by index.html.
    Step2: "CLOSE" is clicked by KODOMO.html.
    Step3: "Open the Window" is again clicked by index.html.
    Then, in second KODOMO.html, a Java applet and a "CLOSE" button are never displayed.
    If the same thing is performed by IE6.0 or Netscape4.75, this bug will not happen.
    Please let me know what is bad and whether there is any evasion measure.

    It forgot to write.
    The version of JavaPlug-IN is 1.4.2_03.
    OS is the Windows2000 Japanese version.
    Please access confirming this bug at the following HTML.
    http://web-p.wics.ne.jp/char_audi/index.html

  • 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 ??

  • Disable most of keyboard input

    Would it be possible with a pure Java code only to disable normal use of keyboard input (like have the application just eat every keystroke except the ESC key for example)?
    I'm most interested in using this for disabling screen capture key sequences (such as CTRL-Alt-PrtScr in Windows) but also for disabling many other key sequences such as CTRL-Alt-Del.
    Thanks.

    This would be too insecure so it's not possible. Imagine if an applet on a webpage could intercept all your keyboard input and steal all your passwords as you log into sites !

  • 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

Maybe you are looking for

  • How do i use the "prepaid" Fedex label that came with my return box?

    i am returning my 1st gen nano, but the shipping label doesn't make much sense to me.  The instructions say '3. Remove the top copy of the shipping label affixed to the box. the top label is your receipt and should be saved for your records. The bott

  • Make transition last full duration of freeze frame?

    Hi, so in an iMovie that I'm editing, the opening shot is a freeze frame of an image for 2.9 seconds. What I'd like to do is have this image fade in with a cross dissolve for the full 2.9 seconds. However, when I add the transition, I can't make it l

  • Model based on ORACLE in Web Dynpro

    Hi all, Hi All, i want to create a web Dynpro application which would extract material data from ORACLE database. Apart from BAPI and WEBSERVICE, i dont find any provision or facility to build a model based on ORACLE. if there is a provision of build

  • Burned iPhoto Library to CD, said 'Successful' but CD empty??

    Just burned my iPhoto Library to a CD-RW (finally)...burn showed as successful, however, the new Library does not show in the list as a disk? moved the disk icon from the desktop to the library list & shows as 'empty'...did I miss a step? wanted to m

  • Configure ESR in CE

    Working through the installation guide for CE and taking guidence from Amir Glatts excellent blogg: link:/people/community.user/blog/2008/02/18/discovery-system-composition-environment-and-esr-150-how-does-it-all-come-together Up to the Configuration