Calculator usinf applets..
Hello everyone,
I have constructed a code to from calculator using JFrame...I got it,,But while do the same by using Applet classmi'm getting some errors like...it is only taking one operand (either of first or second ) for calculation...
Here's the code...
import java.awt.*;
import java.io.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
public class Pcal extends Applet implements ActionListener
TextField txt;
char op;
String a;
double i,k;
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,badd,bmin,bmul,beq,bclr;
public void init()
setLayout(null);
b0=new Button("0");
add(b0);
b0.reshape(176,80,40,24);
b1=new Button("1");
add(b1);
b1.reshape(8, 48, 40, 24);
b2=new Button("2");
add(b2);
b2.reshape(64,48,40,24);
b3=new Button("3");
add(b3);
b3.reshape(120,48,40,24);
b4=new Button("4");
add(b4);
b4.reshape(8,80, 40, 24);
b5=new Button("5");
add(b5);
b5.reshape(64,80,40,24);
b6=new Button("6");
add(b6);
b6.reshape(120,80,40,24);
b7=new Button("7");
add(b7);
b7.reshape(8, 112, 40, 24);
b8=new Button("8");
add(b8);
b8.reshape(64,112,40,24);
b9=new Button("9");
add(b9);
b9.reshape(120,112,40,24);
badd=new Button("+");
add(badd);
badd.reshape(176,48,40,24);
bmin=new Button("-");
add(bmin);
bmin.reshape(176,112,40,24);
bmul=new Button("*");
add(bmul);
bmul.reshape(232,48,40,24);
beq=new Button("=");
add(beq);
beq.reshape(232,80,40,24);
bclr=new Button("ac");
add(bclr);
bclr.reshape(232,112,40,24);
txt=new TextField(" ");
txt.setEditable(false);
add(txt);
txt.reshape(8,8, 268, 31);
b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
badd.addActionListener(this);
bmin.addActionListener(this);
bmul.addActionListener(this);
beq.addActionListener(this);
bclr.addActionListener(this);
public void actionPerformed(ActionEvent e)
String s;
s=txt.getText();
if(e.getSource()==b0)
txt.setText("0");
txt.setText(s+txt.getText());
else if(e.getSource()==b1)
txt.setText("1");
txt.setText(s+txt.getText());
else if(e.getSource()==b2)
txt.setText("2");
txt.setText(s+txt.getText());
else if(e.getSource()==b3)
txt.setText("3");
txt.setText(s+txt.getText());
else if(e.getSource()==b4)
txt.setText("4");
txt.setText(s+txt.getText());
else if(e.getSource()==b5)
txt.setText("5");
txt.setText(s+txt.getText());
else if(e.getSource()==b6)
txt.setText("6");
txt.setText(s+txt.getText());
else if(e.getSource()==b7)
txt.setText("7");
txt.setText(s+txt.getText());
else if(e.getSource()==b8)
txt.setText("8");
txt.setText(s+txt.getText());
else if(e.getSource()==b9)
txt.setText("9");
txt.setText(s+txt.getText());
if(e.getSource()==bclr)
txt.setText("");
i= Double.parseDouble(txt.getText());
if(e.getSource()==badd)
op='+';
txt.setText("");
if(e.getSource()==beq)
double j= Double.parseDouble(txt.getText());
if(op=='+')
k= i+j;
txt.setText(String.valueOf(k));
txt.setText(String.valueOf(k));
i= k;
return;
/*<applet code="Pcal.java" width=400 height=400>
</applet>*/
Ya...i myself got the answer....using a counter as below ..i solved my problem....
counter ++;
if (counter == 1)
j = i;
i = 0;
}
Similar Messages
-
Hi
I have been having problems calling my own packages in java applets to no avail
For a basic example i am storing graphics in a package called graphics and i have a class with a drawline function.
How would i call this in my main program?
At the top of the code i have imported the correct package using import useful.oh;
I have tried the "oh oh = new oh();" which does not cause any compile errors however it doesnt result in a line on screen.
I have also tried the oh.doIt(); function as suggested in some books, but java seems to dislike this and say it cannot find symbol doIt()
Any help would be greatly appreciated!
Excuse the formatting
Thanks
J Selby
The package code:
package useful;
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class oh {
public void paint(Graphics g) {
g.drawRect(100,50,200,50);
The applet code:
//Declare Java Libraries
import useful.*;
import java.lang.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class calculator extends Applet
Font screen = new Font("Tahoma", Font.BOLD, 11);
public void init()
// Set null layout - Gives freedom for button placement
setSize(400,400);
setBackground(new Color(36, 48, 74));
setLayout(null);
Button exit = new Button("Exit");
Button go = new Button("Go");
add(exit);
exit.setLocation(155,10);
exit.setSize(40,22);
add(go);
go.setLocation(120,10);
go.setSize(25,22);
Choice tech=new Choice();
tech.addItem("Tutorial Menu");
tech.addItem("Applet A");
tech.addItem("Applet B");
tech.addItem("Applet C");
tech.addItem("Applet D");
tech.addItem("Applet E");
tech.addItem("Java Quiz");
add(tech);
tech.setLocation(10,10);
oh oh = new oh();From your code it is no where written that you are using the package called graphics
You are been using
package useful;
this implies u r using the package called useful
well let me tell you how to use packages.
For example if you use a package called pack1
then that file you need to compile from parent directory as
javac -d filename.java
this will give you the folder called pack1 and the compiled file placed in it..
so to use this in other folder from parent directory then
you have to import that file
import pack1.filename;
then this will allow you to acess all the methods from that class file..
i hope you get me if any concerns can mail me at
[email protected] -
im trying to create an applet using jewl. i keep getting the error message: cannot find symbol-mothod setupGUI(jewl.frame). a frame is a container but i dont know how to solve this as im obviously doing something wrong. any help would be appreciated, thank you.
import jewl.*;
* A simple calculator. It illustrates the use of textfields, fonts
* and buttons.
public class Calculator extends Applet {
Frame frame;
Font font;
IntegerField value;
public void setupGUI(Container c){
Font font = new Font("Monospaced",Font.BOLD,14);
IntegerField value = new IntegerField (getPanel(), 10, 10, -20, 25);
value.setFont(font);
value.setAlignment(TextControl.RIGHT);
// Create the buttons (using a loop to avoid repetition)
String buttons = "789+456-123*C0=/";
for (int i = 0; i < buttons.length(); i++) {
int x = (i % 4) * 60 + 10;
int y = (i / 4) * 50 + 45;
Button b = new Button (getPanel(), x, y, 50, 40,
"" + buttons.charAt(i),
buttons.charAt(i));
b.setFont(font);
public static void main (String args[]) {
Frame frame = new Frame (260, 275, "JEWL Calculator", 'Q');
Applet d = new Calculator();
d.setupGUI(frame);
while(frame.isValid()) {
char c = Window.nextCommand();
d.handleCommand(c);
public void createGUI() {
setupGUI(getPanel());
// Create the frame and value field
// Variables to record the state of the calculation
public void handleCommand(char command){
char operator = '=';
long left = 0;
long right = 0;
// The event loop
while (frame.isValid()) {
// Digit key: update displayed value
if (command >= '0' && command <= '9') {
right = right * 10 + command - '0';
value.setLong(right);
// Clear key: reset state of calculation and displayed value
else if (command == 'C') {
left = right = 0;
operator = '=';
value.setLong(0);
// Operator key: apply previous operator to left and right values.
// The left value and previous operator will have been set the last
// time an operator key was pressed. The result of the previous
// operation is stored in left, and the operator character is
// saved for next time.
else if (command != 'Q') {
right = value.getLong();
left = (operator == '+' ? left + right :
operator == '-' ? left - right :
operator == '*' ? left * right :
operator == '/' ? left / right : right);
operator = command;
right = 0;
value.setLong(left);
}anyone ideas?
-
I am very new to java, and having a small problem:
When i click on a button, i want the buttons name to be displayed
in a text field, saying "You have pressed" then the name of the button.
but i want to do this with multiple buttons and not just one button, so i want to be able to press any button and its name to be displayed in a text field.
your help will be appreciatedSorry if i did not display code, thanks to all those who replied, heres some of the code, if i have gone wrong in any where could you please help me too correct, i think you will have a general idea of what i am trying to achieve:
import java.awt.*;
import java.awt.event.*;
import java.awt.Button;
import java.lang.Object;
public class Calculator extends Applet implements ActionListener
Button b1 + b2 + b3 + b4 + b5 + b6 + b7 + b8 + b9 + b10 + b11 + b12 + b13 + b14 + b15 + b16 + b17 + b18;
setLayout(new GridLayout(5,4));
public void init( );
Button b1 = new Button( "1" );
b1.addActionListener ( this );
add(b1);
Button b2 = new Button( "2" );
b2.addActionListener ( this );
add( b2 );
Button b3 = new Button( "3" );
b3.addActionListener ( this );
add( b3 );
Button b4 = new Button( "4" );
b4.addActionListener ( this );
add( b4 );
Button b5 = new Button( "5" );
b5.addActionListener ( this );
add( b5 );
Button b6 = new Button( "6" );
b6.addActionListener ( this );
add( b6 );
Button b7 = new Button( "7" );
b7.addActionListener ( this );
add( b7 );
Button b8 = new Button( "8" );
b8.addActionListener ( this );
add( b8 );
Button b9 = new Button( "9" );
b9.addActionListener ( this );
add( b9 );
Button b10 = new Button( "10" );
b10.addActionListener ( this );
add( b10 );
Button b11 = new Button( "+" );
b11.addActionListener ( this );
add( b11 );
Button b12 = new Button( "-" );
b12.addActionListener (this );
add( b12 );
Button b13 = new Button( "x" );
b13.addActionListener ( this );
add( b13 );
Button b14 = new Button( "/" );
b14.addActionListener (this );
add( b14 );
Button b15 = new Button( "MC" );
b15.addActionListener ( this );
add( b15 );
Button b16 = new Button( "MR" );
b16.addActionListener ( this );
add( b16 );
Button b17 = new Button( "M+" );
b17.addActionListener ( this );
add( b17 );
Button b18 = new Button( "c" );
b18.addActionListener ( this );
add( b18 );
after this i get stuck, i don't know how to create a small text field that syas you have pressed (then the button name) if this coding is wrong, can you please explain what i have done wrong!
Thanks -
BC based on class CSSBCVExtern and data type
Hi all,
I'm working with siebel 8.1.1.5 and i've the following problem.
I've have a BC based on class CSSBCVExtern (get data from a web service by a business service defined into bus comp user prop Service Name) with all field defined type DTYPE_TEXT. The customer required some field with type DTYPE_CURRENCY (because the values are some king of amount for you're business) with total required true for automatic calculation (with applet based on applet web template Applet List Totals (Base/EditList), standard interactivity).
The problem is that if i put type DTYPE_CURRENCY on this fields when the field are viewed on applet the application respond with a SSA NOTOK error and if i put type DTYPE_TEXT the automatic calculated total is truncated to integer (removing the decimal information).
Anyone have an alternative solution or a workaround?
Thanks a lot,
AlessandroHi Jagadeesh,
thanks for your suggestion.
I don't understand what do you mean with 'at table level' because is a virtual BC but I tryed with DTYPE_INTEGER, DTYPE_NUMBER, DTYPE_CURRENCY always with precision 22 and scale 7.
Only With the combination DTYPE_CURRENCY and precision 22, scale 7 the applet list column show the decimal number.
Unfortunatly always 00, so the number 2130,25 is viewed 2130,00.
I have also tryed to setting the Display Format to #,###.#0 at List Column level unsuccesflully (2130,25 become 2130,0).
Regards,
Alessandro -
HI all !
I'm new on java card technology and would like to compil my first cardlet :)
I'm getting problem while charging my cardlet into my chip, Eclipse does not generate the cap file.
I'm using Eclipse 3.3.1 and JCop Tools 3.2.7.
I created a Java card projet and a Java card Applet file and here is my code :
package pck_calculator;
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.Util;
public class Calculator extends Applet
private static final byte[] CALC = { //
(byte) 0x63, // c
(byte) 0x61, // a
(byte) 0x6c, // l
(byte) 0x63, // c
(byte) 0x75, // u
(byte) 0x6c, // l
(byte) 0x61, // a
(byte) 0x74, // t
(byte) 0x72, // r
(byte) 0x69, // i
(byte) 0x63, // c
(byte) 0x65 // e
}; // Tableau de bytes (code ASCII) qui va être renvoyé si on envoit l'INS 0x00
//methode d'installation de l'applet dans la carte
public static void install(byte[] bArray, short bOffset, byte bLength)
// Enregistrement de l'applet (méthode register()) auprès du JCRE
// Lors de la création de l'applet (new)
new Calculator().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
public void process(APDU apdu)
//pour verifier que cette applet n'est pas entrain d'être sélectionné
if (selectingApplet())
return;
//réception de la commande APDU
byte[] buf = apdu.getBuffer();
switch (buf[ISO7816.OFFSET_INS])
case (byte) 0x00 :
Util.arrayCopy(CALC, (short) 0, buf, (short) 0, (short) CALC.length);
apdu.setOutgoingAndSend((short) 0, (short) CALC.length);
return;
// Ici, on copie le tableau (défini en haut) dans le buffer et on l'envoi sur la sortie
// En précisant la taille du champ de données
case (byte) 0x01 :
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] + buf[ISO7816.OFFSET_P2]);
// Ici, on additionne P1 et P2
break;
case (byte) 0x02 :
//Soustraction de P1 et P2
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] - buf[ISO7816.OFFSET_P2]);
break;
case (byte) 0x03 :
//Multiplication
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] * buf[ISO7816.OFFSET_P2]);
break;
case (byte) 0x04 :
//Division
if (buf[ISO7816.OFFSET_P2] == 0)
//Test de la division par 0
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
//Envoie de l'exception "mauvais paramètres"
buf[0] = (byte) (buf[ISO7816.OFFSET_P1] / buf[ISO7816.OFFSET_P2]);
break;
case (byte) 0x05 :
//Somme du champ de données de la commande APDU
short n = (short) (ISO7816.OFFSET_CDATA + apdu.setIncomingAndReceive());
byte sum = 0;
while (n-- > ISO7816.OFFSET_CDATA)
sum += buf[n];
buf[0] = sum;
break;
default :
//Envoie de l'exception "mauvais champ INS"
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
//Pour tous les cas la réponse APDU a des données de 1 octet
//Sauf pour le cas INS = 00
apdu.setOutgoingAndSend((short) 0, (short) 1);
}It's a simple calculator :)
To compile, I use right click on the projet => debug as... => Open debug dialog
and I set the correct AID of the package and class in the "Package upload".
Then I start debug and here is the problem :
The .cap is never created (cm> upload -d -b 250 path/file.cap)
The comunication with the card is ok because it answers some request like /card-info.
Do you have any idea about a step I forget or anything else ??
Thanks a lot :)At first, I tried java compiler 5.0 as the over topic and could get a cap file but I think it is not usable.
I changed to your configuration as compiler 1.3 and class compatibility 1.2 and problem is still the same.
cm> /term "tcl:10"
--Opening terminal
/card -a a000000003000000 -c com.ibm.jc.CardManagerresetCard with timeout: 0 (ms)
--Waiting for card...
ATS=0D 77 80 81 02 00 73 C8 40 13 00 90 00 .w....s.@....
ATS: FSC=128, DS=1/DR=1 (symmetrical), FWI=8 (FWT=0.077 sec), SFGI=1, NAD=1/CID=0, Hist=0073C84013009000
=> 00 A4 04 00 08 A0 00 00 00 03 00 00 00 00 ..............
(19856 usec)
<= 6F 19 84 08 A0 00 00 00 03 00 00 00 A5 0D 9F 6E o..............n
06 40 51 42 04 22 00 9F 65 01 FF 90 00 .@QB."..e....
Status: No Error
cm> set-key 255/1/DES-ECB/404142434445464748494a4b4c4d4e4f 255/2/DES-ECB/404142434445464748494a4b4c4d4e4f 255/3/DES-ECB/404142434445464748494a4b4c4d4e4f
cm> init-update 255
=> 80 50 00 00 08 CE F3 CB 4A D0 3D 1C 37 00 .P......J.=.7.
(69487 usec)
<= 00 00 43 52 00 32 72 90 68 81 FF 02 00 45 46 93 ..CR.2r.h....EF.
AD C1 8D 1D 50 D5 2C F4 14 89 82 3E 90 00 ....P.,....>..
Status: No Error
cm> ext-auth plain
=> 84 82 00 00 10 E5 7B 57 1A 9D EA 91 DF AD 6E 18 ......{W......n.
A3 B7 B8 64 73 ...ds
(66179 usec)
<= 90 00 ..
Status: No Error
cm> delete -r 012345678900
=> 80 E4 00 80 08 4F 06 01 23 45 67 89 00 00 .....O..#Eg...
(22288 usec)
<= 6A 88 j.
Status: Reference data not found
jcshell: Error code: 6a88 (Reference data not found)
jcshell: Wrong response APDU: 6A88
Ignoring expected error
cm> upload -d -b 250 "workspace\calc\bin\pck_calculator\javacard\pck_calculator.cap"
=> 80 E6 02 00 13 06 01 23 45 67 89 00 08 A0 00 00 .......#Eg......
00 03 00 00 00 00 00 00 00 .........
(25722 usec)
<= 00 90 00 ...
Status: No Error
=> 80 E8 00 00 FA C4 82 01 A1 01 00 1F DE CA FF ED ................
02 02 04 00 01 06 01 23 45 67 89 00 0E 70 63 6B .......#Eg...pck
5F 63 61 6C 63 75 6C 61 74 6F 72 02 00 21 00 1F _calculator..!..
00 21 00 0B 00 0B 00 2E 00 0E 00 C8 00 19 00 13 .!..............
00 00 00 67 02 69 00 02 00 01 00 0C 01 01 00 04 ...g.i..........
00 0B 01 03 01 07 A0 00 00 00 62 01 01 03 00 0B ..........b.....
01 07 01 23 45 67 89 00 01 00 08 06 00 0E 00 00 ...#Eg..........
00 80 03 00 FF 00 07 01 00 00 00 1C 07 00 C8 00 ................
01 10 18 8C 00 09 7A 05 30 8F 00 08 3D 8C 00 0A ......z.0...=...
18 1D 04 41 18 1D 25 8B 00 07 7A 05 23 18 8B 00 ...A..%...z.#...
05 60 03 7A 19 8B 00 01 2D 1A 04 25 73 00 8E 00 .`.z....-..%s...
00 00 05 00 13 00 2B 00 38 00 45 00 52 00 6A 7B ......+.8.E.R.j{
00 03 03 1A 03 7B 00 03 92 8D 00 00 3B 19 03 7B .....{......;..{
00 03 92 8B 00 02 7A 1A 03 1A 05 25 1A 06 25 41 ......z....%..%A
5B 38 70 5E 1A 03 1A 05 25 1A 06 25 43 5B 38 70 [8p^....%..%C[8p
51 1A 03 1A 05 25 1A 06 25 45 5B 38 70 44 1A 00 Q....%..%E[8pD..
(1746 msec)
<= 6A 80 j.
Status: Wrong data
jcshell: Error code: 6a80 (Wrong data)
jcshell: Wrong response APDU: 6A80
Unexpected error; aborting execution
{code} -
Can't Copy From New Google Calculator Applet
When I enter a mathematical expression into Googles search, it now brings up a javascript calculator that shows the result.
For example, when I search for "2+3" the calculator appears above the search results, showing "5" in the calculation window.
Unfortunately, while I the calculator appears to perform the indicated arithmatic, I'm unable to select the result to copy it from the calculator and paste it into the document I'm editing.
The cursor changes to the I-bar when it's over the result field, but the text cannot be selected.
It works fine in Chrome.
Upgrading Firefox to 14.0.1 and Java to 7.0.50.255 didn't help.That is caused by using -moz-user-select: none; instead of -moz-user-select: -moz-none;<br />
So Google needs to fix this for Firefox.
<pre><nowiki>.cwmd { -moz-user-select: none; }
</nowiki></pre>
*https://developer.mozilla.org/en/CSS/-moz-user-select
<pre><nowiki>-moz-none Non-standard
The text of the element and sub-elements cannot be selected, but selection can be enabled on sub-elements using -moz-user-select:text .</nowiki></pre>
Add code to the userContent.css file.
*http://kb.mozillazine.org/userContent.css
The customization files userChrome.css (interface) and userContent.css (websites) are located in the chrome folder in the user profile folder.
*http://kb.mozillazine.org/Editing_configuration
<pre><nowiki>
@-moz-document domain(www.google.com){
.cwmd { -moz-user-select: -moz-none!important; }
}</nowiki></pre> -
please Help!!!!!
This thing keeps giving a Null Pointer Exception whenever you click a button it compiles fine and runs ok until a button is clicked.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCalculator extends JApplet implements ActionListener {
private char op = 0;
private float num1 = 0, num2 = 0, value = 0 ;
private boolean clearNext = false;
private JTextField display, textField2;
private JButton buttonEq, buttonPlus, buttonMinus, buttonMult,buttonCos;
private JButton buttonDiv,buttonPlusMinus,buttonDec,buttonC,buttonSin;
private JButton buttonTan;
private JButton button = new JButton();
private boolean start = true;
// create GUI components
public void init() {
Container con = getContentPane();
con.setLayout( new BorderLayout());
con.setBackground(Color.darkGray);
//add display display
JTextField display = new JTextField( "0", 15 );
display.setBackground(Color.black);
display.setForeground(Color.red);
display.setEditable(false);
JTextField textField2 = new JTextField( " Design and Implementation By Erwin Zeitner" );
textField2.setBackground(Color.black);
textField2.setForeground(Color.red);
textField2.setEditable(false);
//create numbered buttons
JButton button0 = new JButton("0" );
button0.setBackground(Color.blue);
JButton button1 = new JButton( "1" );
button1.setBackground(Color.blue);
JButton button2 = new JButton( "2" );
button2.setBackground(Color.blue);
JButton button3 = new JButton( "3" );
button3.setBackground(Color.blue);
JButton button4 = new JButton( "4" );
button4.setBackground(Color.blue);
JButton button5 = new JButton( "5" );
button5.setBackground(Color.blue);
JButton button6 = new JButton( "6" );
button6.setBackground(Color.blue);
JButton button7 = new JButton( "7" );
button7.setBackground(Color.blue);
JButton button8 = new JButton( "8" );
button8.setBackground(Color.blue);
JButton button9 = new JButton( "9" );
button9.setBackground(Color.blue);
//create function buttons
JButton buttonC = new JButton( "clear" );
buttonC.setBackground(Color.green);
JButton buttonPlus = new JButton( "+" );
buttonPlus.setBackground(Color.green);
JButton buttonMinus = new JButton( "-" );
buttonMinus.setBackground(Color.green);
JButton buttonMult = new JButton( "*" );
buttonMult.setBackground(Color.green);
JButton buttonDiv = new JButton( "/" );
buttonDiv.setBackground(Color.green);
JButton buttonSin = new JButton( "Sin" );
buttonSin.setBackground(Color.green);
JButton buttonCos = new JButton( "Cos" );
buttonCos.setBackground(Color.green);
JButton buttonTan = new JButton( "Tan" );
buttonTan.setBackground(Color.green);
JButton buttonDec = new JButton( "." );
buttonDec.setBackground(Color.blue);
JButton buttonEq = new JButton( "=" );
buttonEq.setBackground(Color.orange);
JButton buttonPlusMinus = new JButton( "+/-" );
buttonPlusMinus.setBackground(Color.blue);
//create a panel for each row
JPanel row1 = new JPanel();
row1.setBackground(Color.darkGray);
JPanel row2 = new JPanel();
row2.setBackground(Color.darkGray);
JPanel row3 = new JPanel();
row3.setBackground(Color.darkGray);
JPanel row4 = new JPanel();
row4.setBackground(Color.darkGray);
JPanel row5 = new JPanel();
row5.setBackground(Color.darkGray);
JPanel row6 = new JPanel();
row6.setBackground(Color.darkGray);
JPanel row7 = new JPanel();
row7.setBackground(Color.darkGray);
//create panel for rows and set layout
JPanel p = new JPanel();
p.setLayout(new GridLayout( 7,1,0,5 ));
p.setBackground(Color.darkGray);
//set layout for rows
GridLayout grid = new GridLayout(1,4,5,0);
//add buttons & display field to rows
row1.setLayout(grid);
row1.add(display);
//add row to panel
p.add(row1);
row2.setLayout(grid);
buttonC.addActionListener(this);
row2.add(buttonC);
buttonSin.addActionListener(this);
row2.add(buttonSin);
buttonCos.addActionListener(this);
row2.add(buttonCos);
buttonTan.addActionListener(this);
row2.add(buttonTan);
//add row to panel
p.add(row2);
row3.setLayout(grid);
button7.addActionListener(this);
row3.add(button7);
button8.addActionListener(this);
row3.add(button8);
button9.addActionListener(this);
row3.add(button9);
buttonPlus.addActionListener(this);
row3.add(buttonPlus);
//add row to panel
p.add(row3);
row4.setLayout(grid);
button4.addActionListener(this);
row4.add(button4);
button5.addActionListener(this);
row4.add(button5);
button6.addActionListener(this);
row4.add(button6);
buttonMinus.addActionListener(this);
row4.add(buttonMinus);
//add row to panel
p.add(row4);
row5.setLayout(grid);
button1.addActionListener(this);
row5.add(button1);
button2.addActionListener(this);
row5.add(button2);
button3.addActionListener(this);
row5.add(button3);
buttonMult.addActionListener(this);
row5.add(buttonMult);
//add row to panel
p.add(row5);
row6.setLayout(grid);
button0.addActionListener(this);
row6.add(button0);
buttonDec.addActionListener(this);
row6.add(buttonDec);
buttonPlusMinus.addActionListener(this);
row6.add(buttonPlusMinus);
buttonDiv.addActionListener(this);
row6.add(buttonDiv);
//add row to panel
p.add(row6);
row7.setLayout(grid);
buttonEq.addActionListener(this);
row7.add(buttonEq);
//add row to panel
p.add(row7);
// add panel and textField2 to the container
con.add(p,BorderLayout.CENTER);
con.add(textField2,BorderLayout.SOUTH);
public void actionPerformed(ActionEvent e) {
String buttonPressed = e.getActionCommand();
try {
if (buttonPressed.equals( "+/-" )) {
value = getValue(display.getText());
value *= -1;
clearOutput();
addToOutput("" + value );
else switch ( buttonPressed.charAt(0) ) {
case '+':
case '-':
case '*':
case '/':
buttonEq.setEnabled(true);
buttonPlus.setEnabled(false);
buttonMinus.setEnabled(false);
buttonMult.setEnabled(false);
buttonDiv.setEnabled(false);
num1 = getValue(display.getText());
op = buttonPressed.charAt(0);
clearNext = true;
break;
case '=':
buttonEq.setEnabled(true);
buttonPlus.setEnabled(true);
buttonMinus.setEnabled(true);
buttonMult.setEnabled(true);
buttonDiv.setEnabled(true);
getResult();
num1 = getValue(display.getText());
op = 0 ;
clearNext = true;
break;
case 'C':
float num1 = getValue(display.getText());
op = buttonPressed.charAt(0);
getResult();
clearNext = false;
break;
case 'S':
num1 = getValue(display.getText());
op = buttonPressed.charAt(0);
getResult();
clearNext = false;
break;
case 'T':
num1 = getValue(display.getText());
op = buttonPressed.charAt(0);
getResult();
clearNext = false;
break;
case 'c':
clearOutput();
op = 0 ;
num1 = (float) 0 ;
break;
default:
if (clearNext) {
clearOutput();
clearNext = false;
addToOutput(buttonPressed);
catch( Exception exception) {
System.err.println(exception.toString());
public void getResult() {
float num2 = getValue(display.getText());
switch (op) {
case '+':
num1 += num2;
break;
case '-':
num1 -= num2;
break;
case '*':
num1 *= num2;
break;
case '/':
if (num2 != 0)
num1 /= num2;
else
num1 = 0;
break;
case 'C':
Math.cos(num1);
break;
case 'S':
Math.sin(num1);
break;
case 'T':
Math.tan(num1);
break;
clearOutput();
addToOutput( "" + num1 );
clearNext = true;
public void addToOutput( String buttonPressed) {
String newOutput = display.getText();
if (buttonPressed.equals(".")) {
if (newOutput.indexOf(".") == -1)
newOutput += ".";
else
newOutput += buttonPressed;
int newLength = newOutput.length();
display.setText(newOutput);
public void clearOutput() {
try{
display.setText( "" );
catch(Exception c) {
System.err.println(c.toString());
public float getValue(String arg) {
if (arg.equals("."))
arg = "0";
Float f = Float.valueOf(arg);
return f.floatValue();I have found your error please change this to the below one
//add display display
JTextField display = new JTextField( "0", 15 );
display.setBackground(Color.black);
display.setForeground(Color.red);
display.setEditable(false);
//add display display
display = new JTextField( "0", 15 );
display.setBackground(Color.black);
display.setForeground(Color.red);
display.setEditable(false);
if you noticed, you declared the display as a global variable but did not intialized it that is why u get NullPointerException.
By declaring JTextField display again in a method it only belong to that method which is init()
The other textfield also have to be changed if you wish to access it from elsewhere(ex. textfield2 )
Thanks
Joey -
How do I convert an applet to a standalone application.
Hi Everyone,
I am currently working on this Applet, I have tried putting the main in and building a frame to hold the applet but everytime I try something I just get new errors, What I conclusively want to do is put the applet in a frame and add menus to the frame. I have listed the code below, its quite a lot, I hope someone can help though, am pulling hair out.
Many Thanks. Chris
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class SciCalc extends Applet implements ActionListener
// Entered a UID due to String conversion
private static final long serialVersionUID = 1;
int Counter; //Counts the number of digits entered
double Result; //The answer displayed, as well as the second
//operator taken for an operation
double Operand; //The first number entered for an operation
double Mem; //The variable which holds whatever value the user
//wants kept in "memory"
boolean DecimalFlag; //The 'flag' that will signify whether or not the
//decimal button has been pressed
boolean SignFlag; //The 'flag' that will signify whether or not the
//plus/minus button has been pressed
boolean OperatorKey; //The 'flag' that will signify whether or not any
//operator button has been pressed
boolean FunctionKey; //The 'flag' that will signify whether or not any
//function button has been pressed
boolean Rad,Grad,Deg; //The 'flags' that will signify that Rad, Grad or
//deg has been pressed
int Operator; //an integer value to indicate which operator
//button was pressed
char currchar; //a character to hold the value of the key most
//recently pressed
String GrStatus; //String to hold the status of various graphic
//operations of the program
String Status; //String to hold the status of various parts
//of the program
// LABEL DECLARATIONS
//This label will display all error messages
Label DisplError = new Label(" ",Label.CENTER);
//This label is just to the left of the Display Label lcdDisplay, and will
//indicate whether or not a value is being held in the calculator's "memory"
Label LabelMem = new Label(" ",Label.LEFT);
Label LabelRad = new Label(" ",Label.CENTER);
Label LabelDeg = new Label(" ",Label.CENTER);
Label LabelGrad = new Label(" ",Label.CENTER);
//This is the Display Label, which is declared as a label so the user will not
//be able to enter any text into it to possibly crash the calculator
Label lcdDisplay = new Label("0",Label.RIGHT);
Label SciCalc = new Label ("Sci Calc V1.0",Label.CENTER);
// END OF LABEL DECLARATIONS
public void surround (Graphics g){
g.setColor(new Color(0,0,0));
g.drawRect(0,0,350,400);
// DELCLARATION OF NUMERIC BUTTONS
Button button1 = new Button("1");
Button button2 = new Button("2");
Button button3 = new Button("3");
Button button4 = new Button("4");
Button button5 = new Button("5");
Button button6 = new Button("6");
Button button7 = new Button("7");
Button button8 = new Button("8");
Button button9 = new Button("9");
Button button0 = new Button("0");
// END OF NUMERIC BUTTON DECLARATION
// DECLARATION OF OPERATOR BUTTONS
Button buttonMinus = new Button("-");
Button buttonMultiply = new Button("x");
Button buttonPlus = new Button("+");
Button buttonEquals = new Button("=");
Button buttonDivide = new Button("�");
Button buttonClear = new Button("C");
Button buttonDecimal = new Button(".");
Button buttonMPlus = new Button("M+");
Button buttonMClear = new Button("MC");
Button buttonMRecall = new Button("MR");
// END OF OPERATOR BUTTON DECLARATION
// SCIENTIFIC BUTTON DECLARATION
Button buttonPi = new Button("Pi");
Button buttonSqrt = new Button("Sqrt");
Button buttonCbrt = new Button("Cbrt");
Button buttonx2 = new Button("x2");
Button buttonyX = new Button("yX");
Button buttonPlusMinus = new Button("+-");
Button buttonRad = new Button("RAD");
Button buttonGrad = new Button("GRAD");
Button buttonDeg = new Button("DEG");
Button buttonSin = new Button("SIN");
Button buttonCos = new Button("COS");
Button buttonTan = new Button("TAN");
Button buttonExp = new Button("EXP");
Button buttonLogn = new Button("Ln");
Button buttonOpenBracket = new Button("(");
Button buttonLog = new Button("log");
// END OF SCIENTIFIC BUTTON DECLARATION
// START OF INIT METHOD
//This the only method that is called explicitly -- every other method is
//called depending on the user's actions.
public void init()
//Allows for configuring a layout with the restraints of a grid or
//something similar
setLayout(null);
//APPLET DEFAULTS
//This will resize the applet to the width and height provided
resize(350,400);
//This sets the default font to Helvetica, plain, size 12
setFont(new Font("Helvetica", Font.PLAIN, 12));
//This sets the applet background colour
setBackground(new Color(219,240,219));
//END OF APPLET DEFAULTS
//LABEL INITIALISATION
//Display Panel, which appears at the top of the screen. The label is
//placed and sized with the setBounds(x,y,width,height) method, and the
//font, foreground color and background color are all set. Then the
//label is added to the layout of the applet.
lcdDisplay.setBounds(42,15,253,30);
lcdDisplay.setFont(new Font("Helvetica", Font.PLAIN, 14));
lcdDisplay.setForeground(new Color(0,0,0));
lcdDisplay.setBackground(new Color(107,128,128));
add(lcdDisplay);
//Memory Panel, which appears just to the right of the Display Panel.
//The label is placed and sized with the setBounds(x,y,width,height)
//method, and the font, foreground color and background color are all
//set. Then the label is added to the layout of the applet.
LabelMem.setBounds(20,15,20,30);
LabelMem.setFont(new Font("Helvetica", Font.BOLD, 16));
LabelMem.setForeground(new Color(193,0,0));
LabelMem.setBackground(new Color(0,0,0));
add(LabelMem);
//Rad,Grad and Deg panels,which appear below the memory panel.
LabelRad.setBounds(20,50,20,15);
LabelRad.setFont(new Font("Helvetica", Font.BOLD, 8));
LabelRad.setForeground(new Color(193,0,0));
LabelRad.setBackground(new Color(0,0,0));
add(LabelRad);
LabelDeg.setBounds(20,70,20,15);
LabelDeg.setFont(new Font("Helvetica", Font.BOLD, 8));
LabelDeg.setForeground(new Color(193,0,0));
LabelDeg.setBackground(new Color(0,0,0));
add(LabelDeg);
LabelGrad.setBounds(20,90,20,15);
LabelGrad.setFont(new Font("Helvetica", Font.BOLD, 8));
LabelGrad.setForeground(new Color(193,0,0));
LabelGrad.setBackground(new Color(0,0,0));
add(LabelGrad);
//SciCalc v1.0 Label, this merely indicates the name.
SciCalc.setBounds(60,350,200,50);
SciCalc.setFont(new Font("papyrus", Font.BOLD, 25));
SciCalc.setForeground(new Color(0,50,191));
SciCalc.setBackground(new Color(219,219,219));
add(SciCalc);
//END OF LABEL INITIALISATION
//NUMERIC BUTTON INITIALISATION
button1.addActionListener(this);
button1.setBounds(42,105,60,34);
button1.setForeground(new Color(0,0,0));
button1.setBackground(new Color(128,128,128));
button1.setFont(new Font("Dialog", Font.BOLD, 18));
add(button1);
button2.addActionListener(this);
button2.setBounds(106,105,60,34);
button2.setForeground(new Color(0,0,0));
button2.setBackground(new Color(128,128,128));
button2.setFont(new Font("Dialog", Font.BOLD, 18));
add(button2);
button3.addActionListener(this);
button3.setBounds(170,105,60,34);
button3.setForeground(new Color(0,0,0));
button3.setBackground(new Color(128,128,128));
button3.setFont(new Font("Dialog", Font.BOLD, 18));
add(button3);
button4.addActionListener(this);
button4.setBounds(42,145,60,34);
button4.setForeground(new Color(0,0,0));
button4.setBackground(new Color(128,128,128));
button4.setFont(new Font("Dialog", Font.BOLD, 18));
add(button4);
button5.addActionListener(this);
button5.setBounds(106,145,60,34);
button5.setForeground(new Color(0,0,0));
button5.setBackground(new Color(128,128,128));
button5.setFont(new Font("Dialog", Font.BOLD, 18));
add(button5);
button6.addActionListener(this);
button6.setBounds(170,145,60,34);
button6.setForeground(new Color(0,0,0));
button6.setBackground(new Color(128,128,128));
button6.setFont(new Font("Dialog", Font.BOLD, 18));
add(button6);
button7.addActionListener(this);
button7.setBounds(42,185,60,34);
button7.setForeground(new Color(0,0,0));
button7.setBackground(new Color(128,128,128));
button7.setFont(new Font("Dialog", Font.BOLD, 18));
add(button7);
button8.addActionListener(this);
button8.setBounds(106,185,60,34);
button8.setForeground(new Color(0,0,0));
button8.setBackground(new Color(128,128,128));
button8.setFont(new Font("Dialog", Font.BOLD, 18));
add(button8);
button9.addActionListener(this);
button9.setBounds(170,185,60,34);
button9.setForeground(new Color(0,0,0));
button9.setBackground(new Color(128,128,128));
button9.setFont(new Font("Dialog", Font.BOLD, 18));
add(button9);
button0.addActionListener(this);
button0.setBounds(106,225,60,34);
button0.setForeground(new Color(0,0,0));
button0.setBackground(new Color(128,128,128));
button0.setFont(new Font("Dialog", Font.BOLD, 18));
add(button0);
//END OF NUMERIC BUTTON INITIALISATION
//OPERATOR BUTTON INITIALISATION
buttonDecimal.addActionListener(this);
buttonDecimal.setBounds(42,225,60,34);
buttonDecimal.setForeground(new Color(0,0,0));
buttonDecimal.setBackground(new Color(254,204,82));
buttonDecimal.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonDecimal);
buttonPlusMinus.addActionListener(this);
buttonPlusMinus.setBounds(106,325,60,17);
buttonPlusMinus.setForeground(new Color(0,0,0));
buttonPlusMinus.setBackground(new Color(0,118,191));
buttonPlusMinus.setFont(new Font("Dialog", Font.BOLD, 16));
add(buttonPlusMinus);
buttonMinus.addActionListener(this);
buttonMinus.setBounds(234,145,60,34);
buttonMinus.setForeground(new Color(0,0,0));
buttonMinus.setBackground(new Color(254,204,82));
buttonMinus.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonMinus);
buttonMultiply.addActionListener(this);
buttonMultiply.setBounds(234,225,60,34);
buttonMultiply.setForeground(new Color(0,0,0));
buttonMultiply.setBackground(new Color(254,204,82));
buttonMultiply.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonMultiply);
buttonPlus.addActionListener(this);
buttonPlus.setBounds(234,105,60,34);
buttonPlus.setForeground(new Color(0,0,0));
buttonPlus.setBackground(new Color(254,204,82));
buttonPlus.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonPlus);
buttonEquals.addActionListener(this);
buttonEquals.setBounds(170,225,60,34);
buttonEquals.setForeground(new Color(0,0,0));
buttonEquals.setBackground(new Color(254,204,82));
buttonEquals.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonEquals);
buttonDivide.addActionListener(this);
buttonDivide.setBounds(234,185,60,34);
buttonDivide.setForeground(new Color(0,0,0));
buttonDivide.setBackground(new Color(254,204,82));
buttonDivide.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonDivide);
buttonClear.addActionListener(this);
buttonClear.setBounds(234,65,60,34);
buttonClear.setFont(new Font("Dialog", Font.BOLD, 18));
buttonClear.setForeground(new Color(0,0,0));
buttonClear.setBackground(new Color(193,0,0));
add(buttonClear);
buttonMPlus.addActionListener(this);
buttonMPlus.setBounds(170,65,60,34);
buttonMPlus.setFont(new Font("Dialog", Font.BOLD, 18));
buttonMPlus.setForeground(new Color(0,0,0));
buttonMPlus.setBackground(new Color(254,204,82));
add(buttonMPlus);
buttonMClear.addActionListener(this);
buttonMClear.setBounds(42,65,60,34);
buttonMClear.setForeground(new Color(193,0,0));
buttonMClear.setBackground(new Color(254,204,82));
buttonMClear.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonMClear);
buttonMRecall.addActionListener(this);
buttonMRecall.setBounds(106,65,60,34);
buttonMRecall.setForeground(new Color(0,0,0));
buttonMRecall.setBackground(new Color(254,204,82));
buttonMRecall.setFont(new Font("Dialog", Font.BOLD, 18));
add(buttonMRecall);
//END OF OPERATOR BUTTON INITIALISATION
// SCIENTIFIC BUTTONS INITIALISATION
buttonPi.addActionListener(this);
buttonPi.setBounds(42,265,60,17);
buttonPi.setForeground(new Color(0,0,0));
buttonPi.setBackground(new Color(0,118,191));
buttonPi.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonPi);
buttonSqrt.addActionListener(this);
buttonSqrt.setBounds(106,265,60,17);
buttonSqrt.setForeground(new Color(0,0,0));
buttonSqrt.setBackground(new Color(0,118,191));
buttonSqrt.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonSqrt);
buttonCbrt.addActionListener(this);
buttonCbrt.setBounds(170,265,60,17);
buttonCbrt.setForeground(new Color(0,0,0));
buttonCbrt.setBackground(new Color(0,118,191));
buttonCbrt.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonCbrt);
buttonyX.addActionListener(this);
buttonyX.setBounds(42,285,60,17);
buttonyX.setForeground(new Color(0,0,0));
buttonyX.setBackground(new Color(0,118,191));
buttonyX.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonyX);
buttonx2.addActionListener(this);
buttonx2.setBounds(234,265,60,17);
buttonx2.setForeground(new Color(0,0,0));
buttonx2.setBackground(new Color(0,118,191));
buttonx2.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonx2);
buttonRad.addActionListener(this);
buttonRad.setBounds(170,285,60,17);
buttonRad.setForeground(new Color(0,0,0));
buttonRad.setBackground(new Color(0,118,191));
buttonRad.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonRad);
buttonGrad.addActionListener(this);
buttonGrad.setBounds(234,285,60,17);
buttonGrad.setForeground(new Color(0,0,0));
buttonGrad.setBackground(new Color(0,118,191));
buttonGrad.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonGrad);
buttonDeg.addActionListener(this);
buttonDeg.setBounds(106,285,60,17);
buttonDeg.setForeground(new Color(0,0,0));
buttonDeg.setBackground(new Color(0,118,191));
buttonDeg.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonDeg);
buttonSin.addActionListener(this);
buttonSin.setBounds(42,305,60,17);
buttonSin.setForeground(new Color(0,0,0));
buttonSin.setBackground(new Color(0,118,191));
buttonSin.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonSin);
buttonCos.addActionListener(this);
buttonCos.setBounds(106,305,60,17);
buttonCos.setForeground(new Color(0,0,0));
buttonCos.setBackground(new Color(0,118,191));
buttonCos.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonCos);
buttonTan.addActionListener(this);
buttonTan.setBounds(170,305,60,17);
buttonTan.setForeground(new Color(0,0,0));
buttonTan.setBackground(new Color(0,118,191));
buttonTan.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonTan);
buttonExp.addActionListener(this);
buttonExp.setBounds(234,305,60,17);
buttonExp.setForeground(new Color(193,0,0));
buttonExp.setBackground(new Color(0,118,191));
buttonExp.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonExp);
buttonLogn.addActionListener(this);
buttonLogn.setBounds(234,325,60,17);
buttonLogn.setForeground(new Color(0,0,0));
buttonLogn.setBackground(new Color(0,118,191));
buttonLogn.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonLogn);
buttonOpenBracket.addActionListener(this);
buttonOpenBracket.setBounds(42,325,60,17);
buttonOpenBracket.setForeground(new Color(0,0,0));
buttonOpenBracket.setBackground(new Color(0,118,191));
buttonOpenBracket.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonOpenBracket);
buttonLog.addActionListener(this);
buttonLog.setBounds(170,325,60,17);
buttonLog.setForeground(new Color(0,0,0));
buttonLog.setBackground(new Color(0,118,191));
buttonLog.setFont(new Font("Dialog", Font.BOLD, 10));
add(buttonLog);
//END OF SCIENTIFIC BUTTON INITIALISATION
//DISPLERROR INITIALISATION
DisplError.setBounds(42,45,253,15);
DisplError.setFont(new Font("Dialog", Font.BOLD, 8));
DisplError.setForeground(new Color(16711680));
DisplError.setBackground(new Color(0));
add(DisplError);
//END OF DISPLERROR INITIALISATION
Clicked_Clear(); //calls the Clicked_Clear method (C button)
} //END OF INIT METHOD
//The following integers are declared as final as they will
//be used for determining which button has been pushed
public final static int OpMinus=11,
OpMultiply=12,
OpPlus=13,
OpDivide=15,
OpMPlus=19,
OpMClear=20,
OpMR=21,
OpyX=22,
OpExp=23;
//This method is called whenever anything needs to be displayed
//in the error message field at the bottom of the calculator,
//accepting a String as an argument
void DisplayError(String err_msg)
//Calls the setText method of the Label DisplError, sending
//whatever string it received initially
DisplError.setText(err_msg);
//This method is called whenever a numeric button (0-9) is pushed.
public void NumericButton(int i)
DisplayError(" "); //Clears the error message field
//Declares a String called Display that will initialize to whatever
//is currently displayed in the lcdDisplay of the calculator
String Display = lcdDisplay.getText();
//Checks if an operator key has just been pressed, and if it has,
//then the limit of 20 digits will be reset for the user so that
//they can enter in up to 20 new numbers
if (OperatorKey == true)
Counter = 0;
Counter = Counter + 1; //increments the counter
//This is a condition to see if the number currently displayed is zero OR
//an operator key other than +, -, *, or / has been pressed.
if ((Display == "0") || (Status == "FIRST"))
Display= ""; //Do not display any new info
if (Counter < 21) //if more than 20 numbers are entered
//The number just entered is appended to the string currently displayed
Display = Display + String.valueOf(i);
else
//call the DisplayError method and send it an error message string
DisplayError("Digit Limit of 20 Digits Reached");
lcdDisplay.setText(Display); //sets the text of the lcdDisplay
//Label
Status = "VALID"; //sets the Status string to valid
OperatorKey = false; //no operator key was pressed
FunctionKey = false; //no function key was pressed
//This method is called whenever an operator button is pressed, and is
//sent an integer value representing the button pressed.
public void OperatorButton(int i)
DisplayError(" "); //Clears the error message field
//Creates a new Double object with the specific purpose of retaining
//the string currently on the lcdDisplay label, and then immediately
//converts that string into a double-precision real number and then
//gives that number to the variable Result.
Result = (new Double(lcdDisplay.getText())).doubleValue();
//If no operator key has been pressed OR a function has been pressed
if ((OperatorKey == false) || (FunctionKey = true))
switch (Operator) //depending on the operation performed
//if the user pressed the addition button, add the two numbers
//and put them in double Result
case OpPlus : Result = Operand + Result;
break;
//if the user pressed the subtraction button, subtract the two
//numbers and put them in double Result
case OpMinus : Result = Operand - Result;
break;
//if the user pressed the multiplication button, multiply
//the two numbers and put them in double Result
case OpMultiply : Result = Result * Operand;
break;
//if the user pressed the yX button, take first number
//and multiply it to the power of the second number
case OpyX : double temp1=Operand;
for (int loop=0; loop<Result-1; loop++){
temp1= temp1*Operand;
Result=temp1;
break;
//if the user pressed the Exp button -----------------Find out what this does-------------
case OpExp : temp1=10;
for(int loop=0; loop<Result-1; loop++)
temp1=temp1*10;
Result=Result*temp1;
break;
//if the user pressed the division button, check to see if
//the second number entered is zero to avoid a divide-by-zero
//exception
case OpDivide : if (Result == 0)
//set the Status string to indicate an
//an error
Status = "ERROR";
//display the word "ERROR" on the
//lcdDisplay label
lcdDisplay.setText("ERROR");
//call the DisplayError method and
//send it a string indicating an error
//has occured and of what type
DisplayError("ERROR: Division by Zero");
else
//divide the two numbers and put the
//answer in double Result
Result = Operand / Result;
//if after breaking from the switch the Status string is not set
//to "ERROR"
if (Status != "ERROR")
Status = "FIRST"; //set the Status string to "FIRST" to
//indicate that a simple operation was
//not performed
Operand = Result; //Operand holds the value of Result
Operator = i; //the integer value representing the
//operation being performed is stored
//in the integer Operator
//The lcdDisplay label has the value of double Result
//displayed
lcdDisplay.setText(String.valueOf(Result));
//The boolean decimal flag is set false, indicating that the
//decimal button has not been pressed
DecimalFlag = false;
//The boolean sign flag is set false, indicating that the sign
//button has not been pressed
SignFlag = false;
//The boolean OperatorKey is set true, indicating that a simple
//operation has been performed
OperatorKey = true;
//The boolean FunctionKey is set false, indicating that a
//function key has not been pressed
FunctionKey = false;
DisplayError(" "); //Clears the error message field
} //end of OperatorButton method
//This is a method that is called whenever the decimal button is
//pressed.
public void DecimalButton()
DisplayError(" "); //Clears the error message field
//Declares a String called Display that will initialize to whatever
//is currently displayed in the lcdDisplay of the calculator
String Display = lcdDisplay.getText();
//if a simple operation was performed successfully
if (Status == "FIRST")
Display = "0"; //set Display string to character 0
//If the decimal button has not already been pressed
if (!DecimalFlag)
//appends a decimal to the string Display
Display = Display + ".";
else
//calls the DisplayError method, sending a string
//indicating that the number already has a decimal
DisplayError("Number already has a Decimal Point");
//calls the setText method of the Label lcdDisplay and
//sends it the string Display
lcdDisplay.setText(Display);
DecimalFlag = true; //the decimal key has been pressed
Status = "VALID"; //Status string indicates a valid
//operation has been performed
OperatorKey = false; //no operator key has been pressed
} //end of the DecimalButton method
/* This method is called whenever the percent button is pressed
void Open_Bracket(){
String Display = "(";
lcdDisplay.setText(Display);//-----------Change this--------------
//This method is called first when the calculator is initialized
//with the init() method, and is called every time the "C" button
//is pressed
void Clicked_Clear()
Counter = 0; //sets the counter to zero
Status = "FIRST"; //sets Status to FIRST
Operand = 0; //sets Operand to zero
Result = 0; //sets Result to zero
Operator = 0; //sets Operator integer to zero
DecimalFlag = false; //decimal button has not been
//pressed
SignFlag = false; //sign button has not been pressed
OperatorKey = false; //no operator button has been
//pressed
FunctionKey = false; //no function button has been
//pressed
//calls the setText method of Label lcdDisplay and sends
//it the character "0"
lcdDisplay.setText("0");
DisplayError(" "); //clears the error message field
//This method is called whenever the sign button is pressed
void PlusMinusButton()
DisplayError(" "); //clears the error message field
//Declares a String called Display that will initialize to whatever
//is currently displayed in the lcdDisplay of the calculator
String Display = lcdDisplay.getText();
//if Status is not set to FIRST and the Display string does not
//hold the value "0"
if ((Status != "FIRST") || (Display != "0"))
//Creates a new Double object with the specific purpose of retaining
//the string currently on the lcdDisplay label, and then immediately
//converts that string into a double-precision real number and then
//gives that number to the variable Result.
Result = (new Double(lcdDisplay.getText())).doubleValue();
//sets the double Result to it's negative value
Result = -Result;
//call the setText method of Label lcdDisplay and send it the string
//that represents the value in Result
lcdDisplay.setText(String.valueOf(Result));
Status = "VALID"; //sets Status string to VALID
SignFlag = true; //the sign button has been pressed
DecimalFlag = true; //a decimal has appeared
} //end of the PlusMinusButton method
//This method is called whenever the square button is pressed */
void SqrButton()
DisplayError(" "); //clears the error message field
//Declares a String called Display that will initialize to whatever
//is currently displayed in the lcdDisplay of the calculator
String Display = lcdDisplay.getText();
//if Status is not set to FIRST and the Display string does not
//hold the value "0"
if ((Status != "FIRST") || (Display != "0"))
//Creates a new Double object with the specific purpose of retaining
//the string currently on the lcdDisplay label, and then immediately
//converts that string into a double-precision real number and then
//gives that number to the variable Result.
Result = (new Double(lcdDisplay.getText())).doubleValue();
//multiply the double Result by itself, effectively squaring
//the number
Result = Result * Result;
//call the setText method of Label lcdDisplay and send it the string
//that represents the value in Result
lcdDisplay.setText( &Chris,
Two issues:
1) Applet has init(), start(), etc. Application has main().
2) Applet is a container and you can add stuff to it. With application, you need to create your own container.
What you want to do is code so that you can run either way. In the applet, create a Panel or JPanel and add everything to the panel. Then add the panel to the applet. Get that working as an applet.
Now add a main(). All it has to do is create a Frame or JFrame, add the panel to the frame and then call init().
On another subject, your code looks very good, except for the method length getting out of hand. Try breaking init() into pieces in a bunch of methods:
public void init() {
doThis();
doThat();
doTheOther();
private void doThis() {
// maybe a couple dozen lines here
// etc. -
How do I convert my GUI java app to be an applet or display it on a webpage
I have created a loan calculator program in netbeans, I got the application to run fine but now I want to add it into a html page.
I'm just looking for a place to start, I just don't know where to go from here, I want to know if I can actually convert my app with a few changes to an applet or if any one can point me to a forum of similar interest or tutorials that explain what I'm looking for.
I don't even know what i'm looking for except i want this program to run on a webpage.
Or is there a way to run my .jar file on a webpage??
My teacher has not taught us anything on this matter except the below code suggestions on converting and my program is more extensive than her examples for converting. This is what she briefly described on this subject.
1.To convert an application to an applet the main differences are: import java.awt.Graphics; import javax.swing.JApplet; import javax.swing.JOptionPane;
Extend JApplet Replace main with public void init() method
Output with public void paint( Graphics g ) method
2. Remove calls to setSize, setTitle, pack, and any window listener calls, e.g., setDefaultCloseOperation. Compile the program---if something doesn't compile just comment it out for now.
3. Create a simple web page with the following body.
<applet CODE="__________.class" WIDTH="300" HEIGHT="300"
archive="http://www.cs.duke.edu/courses/fall01/cps108/resources/joggle.jar">
Your browser does not support applets </applet>
I understand those steps for a simple program like hello world but not my current app
Heres my code on the 2 extend off my first GUI of the Loan Application
public class AnalysisGUI extends GUI {
/** Creates new form AnalysisGUI */
public AnalysisGUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}//end constructor
private DecimalFormat currency = new DecimalFormat("0.00");
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
analysisjButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
writejTextArea = new javax.swing.JTextArea();
clearTextAreajButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
analysisjButton.setText("Analysis");
analysisjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
analysisjButtonActionPerformed(evt);
writejTextArea.setColumns(20);
writejTextArea.setRows(5);
jScrollPane1.setViewportView(writejTextArea);
clearTextAreajButton.setText("Clear Analysis Output");
clearTextAreajButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearTextAreajButtonActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(analysisjButton)
.addComponent(clearTextAreajButton))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 433, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(86, 86, 86))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(306, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(analysisjButton)
.addGap(84, 84, 84)
.addComponent(clearTextAreajButton)
.addGap(113, 113, 113))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22))))
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-700)/2, (screenSize.height-627)/2, 700, 627);
}// </editor-fold>
private void analysisjButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//importing values for FOR loop of 13 pyaments a years
ir13 = super.rate;
balance13 = super.balance;
time13 = super.time;
payment13 = MortgageCalculator.CalculatePayment(ir13, balance13, time13, PayperYear13);
interest13 = round((balance13 * (ir13/PayperYear13)));
principle13 = round(payment13 - interest13);
//set up for 12 pyaments a year
balance = super.balance;
ir = super.rate;
time = super.time;
payment = super.payment;
interest = round((balance * (ir/PayperYear12)));
principle = round(payment - interest);
//set up for 24 payments a year
balance24 = super.balance;
ir24 = super.rate;
time24 = super.time;
payment24 = super.payment/2;
interest24 = round((balance24 * (ir/PayperYear24)));
principle24 = round(payment24 - interest24);
//set up for 26 payemnts a years
ir26 = super.rate;
balance26 = super.balance;
time26 = super.time;
payment26 = MortgageCalculator.CalculatePayment(ir26, balance26, time26, PayperYear26);
interest26 = round((balance26 * (ir26/PayperYear26)));
principle26 = round(payment26 - interest26);
double totalPrinciple = 0; //set to zero
double totalInterest = 0; //set to zero
for( int n = 0; n < time; n++) //check Year of Loan
totalPrinciple = 0; //reset to zero for totaling Year n totals
totalInterest = 0; //reset to zero for totaling Year n totals
writejTextArea.append("-----Based on 12 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly payments
for(int i = 1; i <= PayperYear12; i++ )
//Calculate applied amounts for chart to be printed
interest = round((balance * ir)/PayperYear12);
principle = round(payment - interest);
balance = round(balance - principle);
//total year end amounts
totalPrinciple = totalPrinciple + principle;
totalInterest = totalInterest + interest;
writejTextArea.append("Payment " + i + " $" + currency.format(principle) + " " +
currency.format(interest) + " $" +
currency.format(balance)+"\n");
}//end for 12 payments per year
//print 12 payments Totals
int yr = n + 1;
writejTextArea.append("\n---Year " + yr + " Totals Based on 12 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
//Start 13 PAYMENTS A YEAR TABLE
double totalPrinciple13 = 0; //reset to zero for totaling Year n totals
double totalInterest13 = 0; //reset to zero for totaling Year n totals
writejTextArea.append("-----Based on 13 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly 13 payments
for(int j = 1; j <= PayperYear13; j++ )
//Calculate applied amounts for chart to be printed
interest13 = round((balance13 * ir13)/PayperYear13);
principle13 = round(payment13 - interest13);
balance13 = round(balance13 - principle13);
//total year end amounts
totalPrinciple13 = totalPrinciple13 + principle13;
totalInterest13 = totalInterest13 + interest13;
//System.out.printf("\n%-10s %-10s %-10s %-10s %-10s", n + 1 , i + 1,Principle, Interest, Balance);
//System.out.printf("\n%-10s %-10s %-10.2f %-10.2f %-10.2f", n + 1 , i + 1,round(principle), round(interest), balance);
writejTextArea.append("Payment " + j + " $" + currency.format(principle13) + " " +
currency.format(interest13) + " $" +
currency.format(balance13)+"\n");
}//end for 13 payments per year
//Print totals for 13 payments a year
yr = n + 1;
writejTextArea.append("\n---Year " + yr + " Totals Based on 13 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple13));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest13));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance13)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
//Start 24 PAYMENTS A YEAR TABLE
double totalPrinciple24 = 0; //reset to zero for totaling Year n totals
double totalInterest24 = 0; //reset to zero for totaling Year n totals
writejTextArea.append("-----Based on 24 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly payments
for(int i = 1; i <= PayperYear24; i++ )
//Calculate applied amounts for chart to be printed
interest24 = round((balance24 * ir24)/PayperYear24);
principle24 = round(payment24 - interest24);
balance24 = round(balance24 - principle24);
//total year end amounts
totalPrinciple = totalPrinciple + principle24;
totalInterest = totalInterest + interest24;
writejTextArea.append("Payment " + i + " $" + currency.format(principle24) + " " +
currency.format(interest24) + " $" +
currency.format(balance24)+"\n");
}//end for 24 payments per year
//print 24 payments Totals
yr = n +1;
writejTextArea.append("\n---Year " + yr + " Totals Based on 24 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple24));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest24));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance24)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
//Start 26 PAYMENTS A YEAR TABLE
double totalPrinciple26 = 0;//reset to zero for totaling Year n totals
double totalInterest26 = 0; //reset to zero for totaling Year n totals
writejTextArea.append("------Based on 26 Payments Per Year-----\n");
writejTextArea.append(" "+" "+"Principle" + " " +
"Interest"+ " "+
"Balance"+"\n");
//loops through the monthly payments 26 times
for(int i = 1; i <= PayperYear26; i++ )
//Calculate applied amounts for chart to be printed
interest26 = round((balance26 * ir24)/PayperYear26);
principle26 = round(payment26 - interest26);
balance26 = round(balance26 - principle26);
totalPrinciple = totalPrinciple + principle26;
totalInterest = totalInterest + interest26;
writejTextArea.append("Payment " + i + " $" + currency.format(principle26) + " " +
currency.format(interest26) + " $" +
currency.format(balance26)+"\n");
}//end for 26 payments per year
yr = n + 1;
//prints 26 payments yearly totals
writejTextArea.append("\n---Year " + yr + " Totals Based on 26 Payments Per Year---");
writejTextArea.append("\nYear Total Principle: $" + currency.format(totalPrinciple26));
writejTextArea.append("\nYear Total Interest: $" + currency.format(totalInterest26));
writejTextArea.append("\nRemaining Balance: $" + currency.format(balance26)+"\n");
writejTextArea.append("\n-------------------------------------------------------\n");
}//end for years of the loan
private void clearTextAreajButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//clear analysis field
writejTextArea.setText("");
public static double round(double r)//round to cents method
return Math.ceil(r*100)/100;
}//end round
/**HI micha what a long progam
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
AnalysisGUI dialog = new AnalysisGUI(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
dialog.setVisible(true);
});//end announymous
}//end main mehtod
//12 year declared varialbes
//private double balance;
private double principle;
private double ir;
private double interest;
private double PayperYear12 = 12;
//Variables for 13 payments a years
private int PayperYear13 = 13;
private double balance13;
private double principle13;
private double ir13;
private double interest13;
private double payment13;
private double time13;
//Varialbes for 24 payments a year
private int PayperYear24 = 24;
private double balance24;
private double principle24;
private double ir24;
private double interest24;
private double payment24;
private double time24;
//Varialbes for 24 payments a year
private int PayperYear26 = 26;
private double balance26;
private double principle26;
private double ir26;
private double interest26;
private double payment26;
private double time26;
// Variables declaration - do not modify
private javax.swing.JButton analysisjButton;
private javax.swing.JButton clearTextAreajButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea writejTextArea;Your original program extends "GUI" which appears to extend JFrame (correct me if I'm wrong). If so, the first thing you should do would be to re-write this so that it extends JPanel which shouldn't be that hard to do (at least it's not hard to do if you know a little Swing -- but I worry about someone coming into this from the netbeans-generated code world). Purists will tell you to not even extend this, to have your main GUI class hold an instance of JPanel instead, and this would work fine too, as long as one way or another, the main GUI program can produce your application displayed on a JPanel on demand.
If you've done this correctly, then using your JPanel in a JFrame is trivial: in a main method create a JFrame, and then simply add your JPanel to the JFrame's contentPane and display it. Likewise using your JPanel in a JApplet is just as trivial as you'd do essentially the same thing: add your JPanel to the JApplet's contentPane, but this time do it in the JApplet's init method. -
Security issues with applets and windows Vista when printing to file
Hi, everyone
I am currently developing an application that prints out the result of some calculations.
from a Javascript file, the output finally ends up in a java applet that should print the file in a special printer.
For debugging purposes I have created a File printer that creates a file from the output comming to the printer; this way I can debug what commands the printer is receiving.
This worked well on Windows Xp; Vista always asks for permissions for the applet, and altough I guarantee these permissions, printer is not allowed to create the output file and reports an error writing
after a little research, I have found that java applets have all permissions when certificated as trusted applications; all but file creating permissions
anyone has any idea of how could I fix this problem?
Thanks in advanceHI,
Have you actually signed your applet? If the signers certificate is the trusted key store for Java it should treat your applet as trusted. You can use a self signed certificate for testing as long as the cert is in the trusted key store.
Some links that might help:
[http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/keytool.html]
[http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/rsa_signing.html]
Cheers,
Shane -
How to change an applet to an application ?
My new applet (used to be a working application) has no error messages but does nothing !
any advice is appreciated
StanSteve
steps taken so far to change an application to an applet:
1) added import javax.swing.JApplet;2) removed the constructor and replaced it with public void init()[/code
3)removed public static void main(String[] args) method
4) created an html file with
<html>
<head>
<title> Pick a Program !</title>
<body>
<h3>Adventures in Learning</h3>
<applet
archive = "objectdraw.jar"
codeBase = "."
code = "TryGridLayout.class" width = 400 height = 400 >
</applet>
</body>
</html>5)added all the classes
In the ActionListener anonymous class it is supposed to (at the click of a button) call
one of 3 applications or another applet. Below is the top level class (used to be the main() driver class)
import objectdraw.*;
import javax.swing.JApplet;
import objectdraw.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.awt.event.*;
public class ChooseProgram1 extends JApplet
private JLabel invalidInputLabel;
JButton myJButtonSketcher;
JButton myJButtonCalculator;
JButton myJButtonInfo;
JButton myJButtonVideo;
public void init()
JFrame myJFrame = new JFrame("Choose your program ! !");
Toolkit myToolkit = myJFrame.getToolkit();
Dimension myScreenSize = myToolkit.getDefaultToolkit().getScreenSize();
// center on screen and set size of frame to half the screen size
myJFrame.setBounds(myScreenSize.width / 4, myScreenSize.height / 4,
myScreenSize.width / 2, myScreenSize.height / 2); //(position, size)
//change the background color
myJFrame.getContentPane().setBackground(Color.yellow);
//create the layout manager
GridLayout myGridLayout = new GridLayout(2,2);
//get the content pane
Container myContentPane = myJFrame.getContentPane();
//set the container layout manager
myContentPane.setLayout(myGridLayout);
//create an object to hold the button's style
Border myEdge = BorderFactory.createRaisedBevelBorder();
//create the button size
Dimension buttonSize = new Dimension(50,50);
//create the button's font object
Font myFont = new Font("Arial", Font.BOLD,18);
//create 1st button's object
myJButtonCalculator = new JButton("Calculator");
myJButtonCalculator.setBackground(Color.red);
myJButtonCalculator.setForeground(Color.black);
//set the button's border and size and font
myJButtonCalculator.setBorder(myEdge);
myJButtonCalculator.setPreferredSize(buttonSize);
myJButtonCalculator.setFont(myFont);
//create 2nd button's object
myJButtonSketcher = new JButton("Sketcher");
myJButtonSketcher.setBackground(Color.pink);
myJButtonSketcher.setForeground(Color.black);
//set the button's border and size and font
myJButtonSketcher.setBorder(myEdge);
myJButtonSketcher.setPreferredSize(buttonSize);
myJButtonSketcher.setFont(myFont);
//create 3rd button's object
myJButtonVideo = new JButton("Airplane-Blimp Video");
myJButtonVideo.setBackground(Color.green);
myJButtonVideo.setForeground(Color.black);
//set the button's border and size and font
myJButtonVideo.setBorder(myEdge);
myJButtonVideo.setPreferredSize(buttonSize);
myJButtonVideo.setFont(myFont);
//create 4th button's object
myJButtonInfo = new JButton(" Information Directory");
myJButtonInfo.setBackground(Color.white);
myJButtonInfo.setForeground(Color.black);
//set the button's border and size and font
myJButtonInfo.setBorder(myEdge);
myJButtonInfo.setPreferredSize(buttonSize);
myJButtonInfo.setFont(myFont);
//add the buttons to the content pane
myContentPane.add(myJButtonCalculator);
myContentPane.add(myJButtonSketcher);
myContentPane.add(myJButtonVideo);
myContentPane.add(myJButtonInfo);
//add behaviors
ActionListener l = new ActionListener()
public void actionPerformed(ActionEvent e)
if(e.getSource() == myJButtonCalculator)
new Calculator6();
System.out.println("The calculator program executed");
else
if(e.getSource() == myJButtonSketcher)
new Sketcher().init();
System.out.println("The Sketcher program executed");
else
if(e.getSource() == myJButtonVideo)
new Grass().init();
System.out.println("The applet executed");
else
if(e.getSource() == myJButtonInfo)
TryInfo.main(new String[]{});
System.out.println("The Information Directory program executed");
else
invalidInputLabel.setText("input invalid");
//add the object listener to listen for the click event on the buttons
myJButtonCalculator.addActionListener(l);
myJButtonSketcher.addActionListener(l);
myJButtonVideo.addActionListener(l);
myJButtonInfo.addActionListener(l);
//myJFrame.setVisible(true);
} //end init() methodTItle should read " How to change an application to an applet"
sorry about that -
How to disable Query for single controls in a Form Applet?
Hi All,
this should be so simple, but seems like I don't get it at the moment.
I have a Form Applet in HI Mode and want to disable the possibility to Query on certain fields. these are Calculated fields and querying will most likely crash the application due to heavy performance impact. They should be for displaying only. How to do that? I have searched for Applet Control User Properties and such stuff but couldn't find one.
ThxHi Siebelade thanks for your reply,
in the meantime I managed to do it using a BusComp Field User Property called "DisableSearch". If you set this to "TRUE" for the desired fields, the user will receive an error message when trying to query for these fields.
Benny -
Applet not working - Please Help!
Hi everybody,
I'm trying to make this calculator program work as an applet AND as an application. I tried using:
public class calcg extends JApplet implements ActionListener{ in many different ways, but it didn't work. Can sombody help me make it work?
Below is the source code for my calculator program.
Thanks in advance,
-Maria
ps-You can also e-mail me at [email protected]
// calculator
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class calcg extends JFrame implements ActionListener
private JButton one, two, three, four, five, six, seven,
eight, nine, zero, dec, eq, plus, minus, mult, div, clear;
private JLabel output, spacer;
private Container container;
private String operation;
private double num1, num2, answer;
private boolean clear_flag = false;
//set up GUI
public calcg()
//Create Title
super("Calculator");
JPanel container = new JPanel();
container.setLayout( new FlowLayout( FlowLayout.CENTER
output = new JLabel("");
output.setBorder(new MatteBorder(2,2,2,2,Color.gray));
output.setPreferredSize(new Dimension(1,26));
getContentPane().setBackground(Color.white);
getContentPane().add( "North",output );
getContentPane().add( "Center",container );
//set up spacer
spacer = new JLabel( "
container.add( spacer );
//set up clear
clear = new JButton( "CE" );
clear.addActionListener(this);
container.add( clear );
//set up seven and register its event handler
seven = new JButton( "7" );
seven.addActionListener(this);
container.add( seven );
//set up eight
eight = new JButton( "8" );
eight.addActionListener(this);
container.add( eight );
//set up nine
nine = new JButton( "9" );
nine.addActionListener(this);
container.add( nine );
//set up div
div = new JButton( "/" );
div.addActionListener(this);
container.add( div );
//set up four
four = new JButton( "4" );
four.addActionListener(this);
container.add( four );
//set up five
five = new JButton( "5" );
five.addActionListener(this);
container.add( five );
//set up six
six = new JButton( "6" );
six.addActionListener(this);
container.add( six );
//set up mult
mult = new JButton( "*" );
mult.addActionListener(this);
container.add( mult );
//set up one
one = new JButton( "1" );
one.addActionListener(this);
container.add( one );
//set up two
two = new JButton( "2" );
two.addActionListener(this);
container.add( two );
//set up three
three = new JButton( "3" );
three.addActionListener(this);
container.add( three );
//set up minus
minus = new JButton( "-" );
minus.addActionListener(this);
container.add( minus );
//set up zero
zero = new JButton( "0" );
zero.addActionListener(this);
container.add( zero );
//set up dec
dec = new JButton( "." );
dec.addActionListener(this);
container.add( dec );
//set up eq
eq = new JButton( "=" );
eq.addActionListener(this);
container.add( eq );
//set up plus
plus = new JButton( "+" );
plus.addActionListener(this);
container.add( plus );
//Set size and make visible
setSize( 190, 225 );
setVisible( true );
setResizable( false );
public void actionPerformed(ActionEvent ae)
JButton but = ( JButton )ae.getSource();
//Handle what button was pushed
//Action for dec button
if( but.getText() == "." )
//if dec is pressed, first check to make shure there
is not already a decimal
String temp = output.getText();
if( temp.indexOf( '.' ) == -1 )
output.setText( output.getText() + but.getText() );
//Action for clear button
else if( but.getText() == "CE" )
output.setText( "" );
operation = "";
num1 = 0.0;
num2 = 0.0;
//Action for plus button
else if( but.getText() == "+" )
operation = "+";
num1 = Double.parseDouble( output.getText() );
clear_flag = true;
//output.setText( "" );
//Action for minus button
else if( but.getText() == "-" )
operation = "-";
num1 = Double.parseDouble( output.getText() );
clear_flag = true;
//output.setText( "" );
//Action for mult button
else if( but.getText() == "*" )
operation = "*";
num1 = Double.parseDouble( output.getText() );
clear_flag = true;
//output.setText( "" );
//Action for div button
else if( but.getText() == "/" )
operation = "/";
num1 = Double.parseDouble( output.getText() );
clear_flag = true;
//output.setText( "" );
//Action for eq button
else if( but.getText() == "=" )
num2 = Double.parseDouble( output.getText() );
//handle addition
if( operation == "+" )
answer = num1 + num2;
else if( operation == "-" )
answer = num1 - num2;
else if( operation == "*" )
answer = num1 * num2;
else if( operation == "/" )
answer = num1 / num2;
//display answer in output field
output.setText( String.valueOf( answer ) );
clear_flag = true;
operation = "";
//Default action should only be used for numbers
else
if( clear_flag == true )
output.setText( "" );
clear_flag = false;
output.setText( output.getText() + but.getText() );
//execute application
public static void main( String args[] )
calcg application = new calcg();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}Ok I think I know what you problem is.
First move the main method above the calcg method ok. Just to make it easy.
Then you did something like
public static void main( String args[] )
calcg application = new calcg();
>> application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }}
the arrows indicate your error. You need to put the setDefaultCloseOperation inside the calcg method then you would put this:
public static void main(String[] args)
calcg application = new calcg();
application.calcg();
see you call the application to run the calcg method which will start your program. -
Need help with Java, have a few questions about my Applet
Purpose of the program: To create a mortgage calculator that will allow the user to input the loan principal then select 1 of 3 choices from a combo-box (7 years @ 5.35%, 15 years @ 5.50%, 30 years @ 5.75%).
Problem: My program was working properly (so I thought). I can get the program to properly compile and run through TextPad. However, I noticed that when the user clicks the calculate more than once (with the same input), it slightly alters the output calculations. So that is my first question, Why is it doing that? How can I get it only calculate that information once unless the user changes it etc?
My next question is regarding my exit button. I was told by my instructor (who has already stated he won't help any of us) that my exit button does not work for an applet and only for an application. So, how can I create an exit button that will work with an applet? I thought I did it right but I can't find any resources online for this.
Next question, why isn't my program properly validating invalid input? My program should only allow numeric input and nothing more.
And last question, when invalid input is entered and the user clicks calculate, why isn't my JOptionPane window for error messages not displaying?
I know my code is a little long so I have to post this in two messages. Please don't criticize me for what I am doing, that is why I am learning and have come to this forum for help. Thanks
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.text.NumberFormat;
import java.text.DecimalFormat;
// Creating the main class
public class test extends JApplet implements ActionListener
// Defining of format information
JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
JButton calculate = new JButton("Calculate");
JButton exitButton = new JButton("Quit");
JButton clearButton = new JButton("Clear");
JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
// Declaration of variables
private double principalAmount;
private JLabel principalLabel = new JLabel("Principal Amount");
private NumberFormat principalFormat;
private JTextField enterPrincipal = new JTextField(10);
private double finalPayment;
private JLabel monthlyPaymentLabel = new JLabel(" Monthly Payment \t Interest Paid \t \t Loan Balance");
private NumberFormat finalPaymentFormat;
private JTextField displayMonthlyPayment = new JTextField(10);
private JTextField displayInterestPaid = new JTextField(10);
private JTextField displayBalance = new JTextField(10);
// Creation of the String of arrays for the ComboBox
String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
JComboBox selections = new JComboBox(list);
// Creation of the textArea that will display the output
private TextArea txtArea = new TextArea(5, 10);
StringBuffer buff = null;
Edited by: LoveMyAJ on Jan 19, 2009 1:49 AM// Initializing the interface
public void init()
// Creation of the panel design and fonts
JPanel upper = new JPanel(new BorderLayout());
JPanel middle = new JPanel(new BorderLayout());
JPanel lower = new JPanel(new BorderLayout());
JPanel areaOne = new JPanel(new BorderLayout());
JPanel areaTwo = new JPanel(new BorderLayout());
JPanel areaThree = new JPanel(new BorderLayout());
JPanel areaFour = new JPanel(new BorderLayout());
JPanel areaFive = new JPanel(new BorderLayout());
JPanel areaSix = new JPanel(new BorderLayout());
Container con = getContentPane();
getContentPane().add(upper, BorderLayout.NORTH);
getContentPane().add(middle, BorderLayout.CENTER);
getContentPane().add(lower, BorderLayout.SOUTH);
upper.add(areaOne, BorderLayout.NORTH);
middle.add(areaTwo, BorderLayout.NORTH);
middle.add(areaThree, BorderLayout.CENTER);
middle.add(areaFour, BorderLayout.SOUTH);
lower.add(areaFive, BorderLayout.NORTH);
lower.add(areaSix, BorderLayout.SOUTH);
heading.setFont(newFontOne);
instructions.setFont(newFontTwo);
instructions2.setFont(newFontTwo);
principalLabel.setFont(newFontThree);
monthlyPaymentLabel.setFont(newFontFour);
displayInterestPaid.setFont(newFontFour);
displayBalance.setFont(newFontFour);
areaOne.add(heading, BorderLayout.NORTH);
areaOne.add(instructions, BorderLayout.CENTER);
areaOne.add(instructions2, BorderLayout.SOUTH);
areaTwo.add(principalLabel, BorderLayout.WEST);
areaTwo.add(enterPrincipal, BorderLayout.EAST);
areaThree.add(selections, BorderLayout.NORTH);
areaFour.add(calculate, BorderLayout.CENTER);
areaFour.add(exitButton, BorderLayout.EAST);
areaFour.add(clearButton, BorderLayout.WEST);
areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
areaSix.add(txtArea, BorderLayout.CENTER);
// Using the ActionListener to determine when each button is clicked
calculate.addActionListener(this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
enterPrincipal.requestFocus();
selections.addActionListener(this);
// The method that will perform specific actions defined below
public void actionPerformed(ActionEvent e)
Object source = e.getSource();
buff = new StringBuffer();
// Outcome of pressing the calculate button
if (source == calculate)
// Used to call upon the user chosen selection
int selection = selections.getSelectedIndex();
// If statement to call upon Loan One's Method
if (selection == 0)
Double data = (Double)calculateLoanOne();
String sourceInput = data.toString();
displayMonthlyPayment.setText(sourceInput);
txtArea.setText(buff.toString());
// If statement to call upon Loan Two's Method
else if (selection == 1)
Double data = (Double)calculateLoanTwo();
String sourceInput = data.toString();
displayMonthlyPayment.setText(sourceInput);
txtArea.setText(buff.toString());
// If statement to call upon Loan Three's Method
else if (selection == 2)
Double data = (Double)calculateLoanThree();
String sourceInput = data.toString();
displayMonthlyPayment.setText(sourceInput);
txtArea.setText(buff.toString());
// Outcome of pressing the clear button
else if (source == clearButton)
enterPrincipal.setText("");
displayMonthlyPayment.setText("");
selections.setSelectedIndex(0);
txtArea.setText("");
// Outcome of pressing the quit button
else if (source == exitButton)
System.exit(1);
// Method used to validate user input
private static boolean validate(JTextField in)
String inText = in.getText();
char[] charInput = inText.toCharArray();
for(int i = 0; i < charInput.length; i++)
int asciiVal = (int)charInput;
if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
else
JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
return false;
return true;
Maybe you are looking for
-
How Can I Create a new Role in an PCD address?
Hello EveryBody, I need to develop a new class that it can manage SAP Portal roles. I got how to recover all the roles of a user or how to recover all the roles in a PCD path. Now I have the problem when I try to create a new role in a PCD path. The
-
How to automatically open browser window for getting user id & password
i have created a jsp page, that page cannot be open by anyone anyway, it should be only visible to me only. how do i achieve this. my requirement is that whenever any one request for that jsp page, browser should automatically open one window and ask
-
can anybody tell me what is this happening i have type exp on my command prompt .but instade of asking exp parameter it is login to the sql and giving me this type of output.... its very strange os path>exp SQL*Plus: Release 9.2.0.5.0 - Production on
-
Hello everyone, Where I can see the list of Held documents report of all users. In SAP there is an option to see the own held documents.. Please be aware that the system I'm asking the report for is 4.6C Thanks in advance Krysia
-
Originally when viewing photos, a "play" icon didn't show up in between the bottom left extra tools logo and the bin.. However it's now suddenly shown up and I can't seem to get rid of it! Any help?