Help on GUI calculator
I'm making a calculator on netbeans and so far i have been able to get the interface and an the function of the number buttons. Also I got the plus button to work but it does not work after using it once. I have tried, but im stuck and can't firgure out what to do next plz help. This is the code i have:
* Calulator.java
* Created on April 3, 2008, 11:30 AM
package me;
* @author period4
public class Calulator extends javax.swing.JFrame {
/** Creates new form Calulator */
public Calulator() {
initComponents();
/** 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 ">//GEN-BEGIN:initComponents
private void initComponents() {
jButton17 = new javax.swing.JButton();
Input = new javax.swing.JTextField();
Button1 = new javax.swing.JButton();
Button4 = new javax.swing.JButton();
Button7 = new javax.swing.JButton();
Button2 = new javax.swing.JButton();
Button5 = new javax.swing.JButton();
Button8 = new javax.swing.JButton();
Button3 = new javax.swing.JButton();
Button6 = new javax.swing.JButton();
Button9 = new javax.swing.JButton();
Button0 = new javax.swing.JButton();
ButtonPlus = new javax.swing.JButton();
ButtonMinus = new javax.swing.JButton();
ButtonMultiply = new javax.swing.JButton();
ButtonDecimal = new javax.swing.JButton();
ButtonPositiveNegative = new javax.swing.JButton();
ButtonDivide = new javax.swing.JButton();
ButtonEquals = new javax.swing.JButton();
jButton17.setText("jButton17");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Calculator");
Button1.setText("1");
Button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button1ActionPerformed(evt);
Button4.setText("4");
Button4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button4ActionPerformed(evt);
Button7.setText("7");
Button7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button7ActionPerformed(evt);
Button2.setText("2");
Button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button2ActionPerformed(evt);
Button5.setText("5");
Button5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button5ActionPerformed(evt);
Button8.setText("8");
Button8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button8ActionPerformed(evt);
Button3.setText("3");
Button3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button3ActionPerformed(evt);
Button6.setText("6");
Button6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button6ActionPerformed(evt);
Button9.setText("9");
Button9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button9ActionPerformed(evt);
Button0.setText("0");
Button0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button0ActionPerformed(evt);
ButtonPlus.setText("+");
ButtonPlus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonPlusActionPerformed(evt);
ButtonMinus.setText("-");
ButtonMultiply.setText("*");
ButtonDecimal.setText(".");
ButtonDecimal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonDecimalActionPerformed(evt);
ButtonPositiveNegative.setText("+/-");
ButtonDivide.setText("/");
ButtonEquals.setText("=");
ButtonEquals.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonEqualsActionPerformed(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(Input, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Button7, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(Button4, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(Button1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(Button2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Button5, 0, 0, Short.MAX_VALUE)
.addComponent(Button8, 0, 0, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(Button3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonPlus))
.addGroup(layout.createSequentialGroup()
.addComponent(Button6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonMinus))
.addGroup(layout.createSequentialGroup()
.addComponent(Button9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonMultiply))))
.addGroup(layout.createSequentialGroup()
.addComponent(ButtonDecimal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Button0)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonPositiveNegative)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonDivide)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ButtonEquals)))
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(Input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Button1)
.addComponent(Button2)
.addComponent(Button3)
.addComponent(ButtonPlus))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Button4)
.addComponent(Button5)
.addComponent(Button6)
.addComponent(ButtonMinus))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Button7)
.addComponent(Button8)
.addComponent(Button9)
.addComponent(ButtonMultiply))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ButtonDecimal)
.addComponent(Button0)
.addComponent(ButtonPositiveNegative)
.addComponent(ButtonDivide)))
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(ButtonEquals, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(44, Short.MAX_VALUE))
pack();
}// </editor-fold>//GEN-END:initComponents
private void ButtonEqualsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonEqualsActionPerformed
if(operator.equals("+"))
solution = Double.parseDouble(integer1) + Double.parseDouble(integer2);
Input.setText(Double.toString(solution));
operator = null;
integer1 = "";
integer2 = "";
//Input.setText(Double.toString(solution));
solution = 0;
// TODO add your handling code here:
}//GEN-LAST:event_ButtonEqualsActionPerformed
private void ButtonPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonPlusActionPerformed
operator = "+";
// TODO add your handling code here:
}//GEN-LAST:event_ButtonPlusActionPerformed
private void ButtonDecimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonDecimalActionPerformed
Input.setText(".");// TODO add your handling code here:
}//GEN-LAST:event_ButtonDecimalActionPerformed
private void Button0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button0ActionPerformed
if(operator == null)
integer1 = integer1.concat("0");
Input.setText(integer1);
else
integer2 = integer2.concat("0");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button0ActionPerformed
private void Button9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button9ActionPerformed
if(operator == null)
integer1 = integer1.concat("9");
Input.setText(integer1);
else
integer2 = integer2.concat("9");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button9ActionPerformed
private void Button6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button6ActionPerformed
if(operator == null)
integer1 = integer1.concat("6");
Input.setText(integer1);
else
integer2 = integer2.concat("6");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button6ActionPerformed
private void Button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button3ActionPerformed
if(operator == null)
integer1 = integer1.concat("3");
Input.setText(integer1);
else
integer2 = integer2.concat("3");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button3ActionPerformed
private void Button8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button8ActionPerformed
if(operator == null)
integer1 = integer1.concat("8");
Input.setText(integer1);
else
integer2 = integer2.concat("8");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button8ActionPerformed
private void Button5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button5ActionPerformed
if(operator == null)
integer1 = integer1.concat("5");
Input.setText(integer1);
else
integer2 = integer2.concat("5");
Input.setText(integer2);
// TODO and your handling code here:
}//GEN-LAST:event_Button5ActionPerformed
private void Button7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button7ActionPerformed
if(operator == null)
integer1 = integer1.concat("7");
Input.setText(integer1);
else
integer2 = integer2.concat("7");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button7ActionPerformed
private void Button4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button4ActionPerformed
if(operator == null)
integer1 = integer1.concat("4");
Input.setText(integer1);
else
integer2 = integer2.concat("4");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button4ActionPerformed
private void Button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button1ActionPerformed
if(operator == null)
integer1 = integer1.concat("1");
Input.setText(integer1);
else
integer2 = integer2.concat("1");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button1ActionPerformed
private void Button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button2ActionPerformed
if(operator == null)
integer1 = integer1.concat("2");
Input.setText(integer1);
else
integer2 = integer2.concat("2");
Input.setText(integer2);
// TODO add your handling code here:
}//GEN-LAST:event_Button2ActionPerformed
* @param args the command line arguments
double solution;
String integer1 = "";
String integer2 = "";
String operator;
public static void main(String args[])
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
new Calulator().setVisible(true);
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Button0;
private javax.swing.JButton Button1;
private javax.swing.JButton Button2;
private javax.swing.JButton Button3;
private javax.swing.JButton Button4;
private javax.swing.JButton Button5;
private javax.swing.JButton Button6;
private javax.swing.JButton Button7;
private javax.swing.JButton Button8;
private javax.swing.JButton Button9;
private javax.swing.JButton ButtonDecimal;
private javax.swing.JButton ButtonDivide;
private javax.swing.JButton ButtonEquals;
private javax.swing.JButton ButtonMinus;
private javax.swing.JButton ButtonMultiply;
private javax.swing.JButton ButtonPlus;
private javax.swing.JButton ButtonPositiveNegative;
private javax.swing.JTextField Input;
private javax.swing.JButton jButton17;
// End of variables declaration//GEN-END:variables
}
Yeah. Seriously. I don't think anybody wants to wade through a whole bunch of IDE generated crap that you didn't bother to format with code tags.
I know I don't.
So maybe post some formatted relevent code (10 lines or less).
Similar Messages
-
I am trying to create a GUI calculator which:
-must use the JOptionPane class to create dialog boxes for user input and
output.
-If the user attempts to divide by 0, you must print a message to that effect (e.g.,
"division by 0 not allowed").
-If the user enters an invalid operator, you must print a message to that effect
(e.g., "operation not supported").
My Program will not work, and any help would be greatly appreciated!
import javax.swing.JOptionPane;
public class GUI {
String numberString =
JOptionPane.showInputDialog("Welcome to my GUI Calculator!\n The following operations are supported:\n +(addition), -(subtraction), *(multiplication)\n /(division),and ^(exponent)\n\n Enter your calculation separated by spaces and press OK.\n Example:2.5 + 3");
int firstSpace =
numberString.indexOf(" ");
double answer;
double
operand1 = Double.parseDouble(numberString.substring(0,firstSpace));
double
operand2 = Double.parseDouble(numberString.substring(firstSpace+3,numberString.length()));
char
operator = numberString.charAt(firstSpace+1);
while (operator == "+")
answer = operand1 + operand2;
while (operator == "-")
answer = operand1 - operand2;
while (operator == "*")
answer = operand1 * operand2;
while (operator == "/")
{ if (operand2 == 0)
JOptionPane.showInputDialog("Division by 0 not allowed!");
else
answer = operand1 / operand2;
while (operator == "^")
answer = Math.pow(operand1, operand2);
while (operator != "+, -, *, /, ^")
JOptionPane.showInputDialog("Operation not supported.");
JOptionPane.showMessageDialog("numberString = answer");
System.exit(0);
}When you post code, please wrap it in [code] [/code] tags so it's easy to read.
You're confusing strings with characters. You read the operator as a character. But when you check it, you compare it with Strings (you can tell they're Strings because you're using double quotes). You should be using single quotes there.
Your code makes a lot of assumptions about the format of the data it's given, for example the number of spaces and where they'll appear.
And this part:while (operator != "+, -, *, /, ^") There's absolutely no reason why that would work. Where did you get the idea that was a thing to do? If you want to see if the operator is in a list of characters, there are a variety of things you can do, but probably the simplest is just to have five if/else statements. You're going to need those anyway when you do the math operation; when you get to the last one, just put an else statement saying that you don't recognize the operator. -
Please Help/ GUI Calculator
I'm trying to create a GUI Calculator but cannot get my program to compile. Please could someone assistm, thanks.
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorFrame extends JFrame
private Container contentPane;
//The componenets used in the calculator
private JTextField display;
private JButton addition;
private JButton subtract;
private JButton multiply;
private JButton divide;
private JButton mod;
private JButton enter;
private JButton [] digits;
//End of components
//Integer representations for the arithmetic operations needed
private final static int ADD = 1;
private final static int SUB = 2;
private final static int MUL = 3;
private final static int DIV = 4;
private final static int MOD = 5;
//ENd of arithmethic operations
//Integer holding the operator that the user requested
private int op;
//Boolean variable to help perform the calculations
private boolean firstFilled;
private boolean clearScreen;
//Constructor for the class
public CalculatorFrame()
contentPane=new Container();
this.setSize(400,300); //sets the size of the frame
this.setTitle("MIS 222 Calculator"); //sets the title of the frame
//allows the "X" box in the upper right hand corner to close the entire application
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane=this.getContentPane(); //gets the content pane
//Methods
addDisplay();
addDigits();
addDigitActionListeners();
addOperation();
private void addDisplay()
JLabel displayLab = new JLabel("Answer");
JPanel north = new JPanel();
north.add(displayLab);
contentPane.add(north, "North");
//diplay was already declared above the constructor
display = new JTextField(25);
//adding the components to the panel
north.add(displayLab);
north.add(display);
//adding the panel to frame's content pane
contentPane.add(north, "North");
//Declaring the global digits array
private void addDigits()
//Add 1 large panel to hold the 3 inner panels
JPanel digPanel = new JPanel();
//Set the panel's preferred size so that it will keep everything in line
digPanel.setPreferredSize(new Dimension(200, 275));
//Initialize the top 3 digits' JPanel and set its preferrd size
JPanel topDigits = new JPanel();
topDigits.setPreferredSize(new Dimension(200,60));
//Initialize the middle 2 digits' JPanel and set its preferred size
JPanel midDigits = new JPanel();
midDigits.setPreferredSize(new Dimension(200,60));
//Initialize the bottom digits' JPanel and set its preferred size
JPanel botDigits = new JPanel();
botDigits.setPreferredSize(new Dimension(200, 75));
//Initialize the JButton array
digits = new JButton[11];
//Initialize each of the top Panel's digit buttons, and add it to the top panel
for(int i=1; i<4; i++)
String lab=(new Integer(i)).toString();
digits=new JButton(lab);
topDigits.add(digits[i]);
//Adding the top Digit Panel to the overall digit panel
digPanel.add(topDigits, BorderLayout.CENTER);
//Adding the middle Digit Panel to the overall digit panel
digPanel.add(midDigits, BorderLayout.CENTER);
//Adding the bottom Digit Panel to the overall digit panel
digPanel.add(botDigits, BorderLayout.CENTER);
//Add the overall digit Panel to the Frame's contentpane
contentPane.add(digPanel, BorderLayout.CENTER);
//Method created to add the DigitAction Listeners
addDigitActionListeners();
//Method created to add all of the DigitActionListeners
private void addDigitActionListeners()
for(int i=0; i<10; i++)
digits[i].addActionListener(new DigitActionListener(i));
digits[10].addActionListener(new DigitActionListener("."));
//DigitActionListener class
public class DigitActionListener implements ActionListener
private String myNum;
public DigitActionListener(int num)
myNum=""+num;
public DigitActionListener(String num)
myNum=num;
public void actionPerformed(ActionEvent e)
if(display.getText().equals("Please enter a valid number")|| clearScreen)
clearScreen=false;
display.setText("");
//OperatorActionListener class
public void OpActionListener implements ActionListener
private int myOpNum;
public OpActionListener(int op)
myOpNum=op;
public void actionPerformed(ActionEvent e)
{ //Checks to see if the user has already enterd a number
if(!firstFilled)
try{
//Parse the number entered
String number=display.getText();
dNum1=Double.parseDouble(number);
//Sets the flag for the firstFilled to true
firstFilled=true
//Sets the op variable so when the "Enter" button is pressed, it will know which operation to perform
op=myOpNum;
//Clears the textbox
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
//This is the second number being entered
else{
try{
String number=display.getText();
String result;
dNum2=Double.parseDouble(number);
firstFilled=true;
op=myOpNum;
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
private void addOperation()
JPanel opPanel=new JPanel();
opPanel.setPreferredSize(new Dimension(75,200));
JButton clear = new JButton("C");
JButton addition = new JButton("+");
JButton subtraction = new JButton("-");
JButton multiply = new JButton("*");
JButton divide = new JButton("/");
JButton mod = new JButton("%");
JButton enter = new JButton("Enter");
addition.addActionListener(new OpActionListener(ADD));
subtraction.addActionListener(new OpActionListener(SUB));
multiply.addActionListener(new OpActionListener(MUL));
divide.addActionListener(new OpActionListener(DIV));
mod.addActionListener(new OpActionListener(MOD));
clear.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
display.setText("");
firstFilled=false;
enter.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
double result;
String answer="";
String number = display.getText();
dNum2 = Double.parseDouble(number);
dNum1=Double.parseDouble(number);
switch(op)
case ADD:
result = dNum1 + dNum2;
break;
case SUB:
result = dNum1 - dNum2;
break;
case MUL:
result = dNum1 * dNum2;
break;
case DIV:
result = dNum1 / dNum2;
break;
default:
result= -1.0;
break;
if(result==(int)result)
answer=(new Integer((int)result)).toString();
else
answer=(new Double(result)).toString();
display.setText(answer);
clearScreen=true;
firstFilled=false;
dNum1=0;
dNum2=0;
opPanel.add(clear);
opPanel.add(addition);
opPanel.add(subtraction);
opPanel.add(multiply);
opPanel.add(divide);
opPanel.add(mod);
opPanel.add(enter);
contentPane.add(opPanel, "East");
//Creating the frame object
public class CalculatorMain
public void main(String[] args)
CalculatorFrame cf=new CalculatorFrame();
cf.show();
ERRORS THAT I HAVE!!:
javac calculatorframe.javacalculatorframe.java:150: '(' expected
public void OpActionListener implements ActionListener
^
calculatorframe.java:7: class CalculatorFrame is public, should be declared in a file named CalculatorFrame.java
public class CalculatorFrame extends JFrame
^
calculatorframe.java:54: cannot resolve symbol
symbol : method addOperation ()
location: class CalculatorFrame
addOperation();
^
3 errors
>Hi, actually it's all written there:
>
ERRORS THAT I HAVE!!:
javac calculatorframe.javacalculatorframe.java:150: '(' expected
public void OpActionListener implements
ActionListenerpublic void ... is part of a possible method signature. That's probably why the compiler expects '(' as this is need for a method.
To define a class use:
public class ... (or better: private class ..., if the class is not used outside of this file.
^
calculatorframe.java:7: class CalculatorFrame is
public, should be declared in a file named
CalculatorFrame.java
public class CalculatorFrame extends JFrame
^As it says, you defined a class CalculatorFrame in a file calculatorframe.java. But the file name should be the same as the class name (case sensitive). Java classes should start with capital letters, so rename the file to:
CalculatorFrame.java
calculatorframe.java:54: cannot resolve symbol
symbol : method addOperation ()
location: class CalculatorFrame
addOperation();
^
3 errors
>You didn't declare the method 'addOperation' (-> cannot resolve symbol; which simbol: method addOperation (); where: location: class CalculatorFrame; you see it's all there)
Note there is a method called 'addOperation' in the class OpActionListener, but not in CalculatorFrame.
Note I didn't read the code, just the error messages. I hope this helps.
-Puce -
Hello everyone! I'm trying to create a GUI Calculator but cannot get my program to compile. Please could someone assist me, thanks.
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorFrame extends JFrame
private Container contentPane;
//The componenets used in the calculator
private JTextField display;
private JButton addition;
private JButton subtract;
private JButton multiply;
private JButton divide;
private JButton mod;
private JButton enter;
private JButton [] digits;
//End of components
//Integer representations for the arithmetic operations needed
private final static int ADD = 1;
private final static int SUB = 2;
private final static int MUL = 3;
private final static int DIV = 4;
private final static int MOD = 5;
//ENd of arithmethic operations
//Integer holding the operator that the user requested
private int op;
//Boolean variable to help perform the calculations
private boolean firstFilled;
private boolean clearScreen;
//Constructor for the class
public CalculatorFrame()
contentPane=new Container();
this.setSize(400,300); //sets the size of the frame
this.setTitle("MIS 222 Calculator"); //sets the title of the frame
//allows the "X" box in the upper right hand corner to close the entire application
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane=this.getContentPane(); //gets the content pane
//Methods
addDisplay();
addDigits();
addDigitActionListeners();
addOperation();
private void addDisplay()
JLabel displayLab = new JLabel("Answer");
JPanel north = new JPanel();
north.add(displayLab);
contentPane.add(north, "North");
//diplay was already declared above the constructor
display = new JTextField(25);
//adding the components to the panel
north.add(displayLab);
north.add(display);
//adding the panel to frame's content pane
contentPane.add(north, "North");
//Declaring the global digits array
private void addDigits()
//Add 1 large panel to hold the 3 inner panels
JPanel digPanel = new JPanel();
//Set the panel's preferred size so that it will keep everything in line
digPanel.setPreferredSize(new Dimension(200, 275));
//Initialize the top 3 digits' JPanel and set its preferrd size
JPanel topDigits = new JPanel();
topDigits.setPreferredSize(new Dimension(200,60));
//Initialize the middle 2 digits' JPanel and set its preferred size
JPanel midDigits = new JPanel();
midDigits.setPreferredSize(new Dimension(200,60));
//Initialize the bottom digits' JPanel and set its preferred size
JPanel botDigits = new JPanel();
botDigits.setPreferredSize(new Dimension(200, 75));
//Initialize the JButton array
digits = new JButton[11];
//Initialize each of the top Panel's digit buttons, and add it to the top panel
for(int i=1; i<4; i++)
String lab=(new Integer(i)).toString();
digits=new JButton(lab);
topDigits.add(digits);
//Adding the top Digit Panel to the overall digit panel
digPanel.add(topDigits, BorderLayout.CENTER);
//Adding the middle Digit Panel to the overall digit panel
digPanel.add(midDigits, BorderLayout.CENTER);
//Adding the bottom Digit Panel to the overall digit panel
digPanel.add(botDigits, BorderLayout.CENTER);
//Add the overall digit Panel to the Frame's contentpane
contentPane.add(digPanel, BorderLayout.CENTER);
//Method created to add the DigitAction Listeners
addDigitActionListeners();
//Method created to add all of the DigitActionListeners
private void addDigitActionListeners()
for(int i=0; i<10; i++)
digits.addActionListener(new DigitActionListener(i));
digits[10].addActionListener(new DigitActionListener("."));
//DigitActionListener class
public class DigitActionListener implements ActionListener
private String myNum;
public DigitActionListener(int num)
myNum=""+num;
public DigitActionListener(String num)
myNum=num;
public void actionPerformed(ActionEvent e)
if(display.getText().equals("Please enter a valid number")|| clearScreen)
clearScreen=false;
display.setText("");
//OperatorActionListener class
public void OpActionListener implements ActionListener
private int myOpNum;
public OpActionListener(int op)
myOpNum=op;
public void actionPerformed(ActionEvent e)
{ //Checks to see if the user has already enterd a number
if(!firstFilled)
try{
//Parse the number entered
String number=display.getText();
dNum1=Double.parseDouble(number);
//Sets the flag for the firstFilled to true
firstFilled=true
//Sets the op variable so when the "Enter" button is pressed, it will know which operation to perform
op=myOpNum;
//Clears the textbox
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
//This is the second number being entered
else{
try{
String number=display.getText();
String result;
dNum2=Double.parseDouble(number);
firstFilled=true;
op=myOpNum;
display.setText("");
catch(Exception er)
display.setText("Please enter a valid number");
private void addOperation()
JPanel opPanel=new JPanel();
opPanel.setPreferredSize(new Dimension(75,200));
JButton clear = new JButton("C");
JButton addition = new JButton("+");
JButton subtraction = new JButton("-");
JButton multiply = new JButton("*");
JButton divide = new JButton("/");
JButton mod = new JButton("%");
JButton enter = new JButton("Enter");
addition.addActionListener(new OpActionListener(ADD));
subtraction.addActionListener(new OpActionListener(SUB));
multiply.addActionListener(new OpActionListener(MUL));
divide.addActionListener(new OpActionListener(DIV));
mod.addActionListener(new OpActionListener(MOD));
clear.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
display.setText("");
firstFilled=false;
enter.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
double result;
String answer="";
String number = display.getText();
dNum2 = Double.parseDouble(number);
dNum1=Double.parseDouble(number);
switch(op)
case ADD:
result = dNum1 + dNum2;
break;
case SUB:
result = dNum1 - dNum2;
break;
case MUL:
result = dNum1 * dNum2;
break;
case DIV:
result = dNum1 / dNum2;
break;
default:
result= -1.0;
break;
if(result==(int)result)
answer=(new Integer((int)result)).toString();
else
answer=(new Double(result)).toString();
display.setText(answer);
clearScreen=true;
firstFilled=false;
dNum1=0;
dNum2=0;
opPanel.add(clear);
opPanel.add(addition);
opPanel.add(subtraction);
opPanel.add(multiply);
opPanel.add(divide);
opPanel.add(mod);
opPanel.add(enter);
contentPane.add(opPanel, "East");
//Creating the frame object
public class CalculatorMain
public void main(String[] args)
CalculatorFrame cf=new CalculatorFrame();
cf.show();
ERRORS THAT I HAVE!!:
javac calculatorframe.javacalculatorframe.java:150: '(' expected
public void OpActionListener implements ActionListener
^
calculatorframe.java:7: class CalculatorFrame is public, should be declared in a file named CalculatorFrame.java
public class CalculatorFrame extends JFrame
^
calculatorframe.java:54: cannot resolve symbol
symbol : method addOperation ()
location: class CalculatorFrame
addOperation();
^
3 errors
>Here I did this for someone in the 'new to' forum about 2 weeks back. They had some really awful code they say they got from a java book -cannot recall the author, but I do know his work should be burned and the person executed with a mercy killing (I still haven't recovered from the shock of this and I think most of the regular contributors in these forums could write FAR BETTER books than this clown)
Hmm... I do rant sometimes. Erm, you're welcome - this is their rebuild;-import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
JButton []buttons = new JButton[25];
private JTextField display= new JTextField("0.0",12);
String status = " Status : ";
JLabel label = new JLabel(status);
private double sum = 0.0d;
private String nums = "";
private double arg = 0.0d;
private double tot = 0.0d;
private boolean start = true,div,mult,add,sub;
private String memory = "0";
java.text.DecimalFormat df=new java.text.DecimalFormat("#,##0.0####");
Font f = new Font("Times New Roman", Font.BOLD,14);
Color midBlue = new Color(20, 15, 140);
public Calculator(){
super();
setTitle("Java Calculator");
JPanel mainPan = new JPanel();
mainPan.setLayout(new BorderLayout() );
JPanel textPanel = new JPanel();
textPanel.setBackground(midBlue);
textPanel.setLayout(new BorderLayout());
display.setHorizontalAlignment(JTextField.RIGHT);
label.setForeground(Color.white);
display.setFont(new Font("",0,14));
display.setEditable(false);
display.setBackground(Color.white);
label.setFont(new Font("Arial",0,12));
JPanel emptyPan = new JPanel();
emptyPan.setBackground(midBlue);
JPanel emptyP1 = new JPanel();
emptyP1.setBackground(midBlue);
JPanel emptyP2 = new JPanel();
emptyP2.setBackground(midBlue);
textPanel.add("North", label);
textPanel.add("Center", display);
textPanel.add("South",emptyPan );
textPanel.add("East",emptyP1 );
textPanel.add("West",emptyP2 );
JPanel butPanel = new JPanel();
butPanel.setBackground(midBlue);
butPanel.setLayout(new GridLayout(5, 5, 10, 10));
String []str = {"","","","CE","C","1","2","3","/","RM","4","5","6",
"*","CM","7","8","9","+","M+","0",".","=","-","M-"};
for(int j=0; j<25; j++) {
if(j<3) {
buttons[j] = new JButton(str[j]);
butPanel.add(buttons[j]);
else {
buttons[j] = new JButton(str[j]);
buttons[j].addActionListener(this);
buttons[j].setFont(f);
buttons[j].setBorder(BorderFactory.createRaisedBevelBorder());
butPanel.add(buttons[j]);
JPanel emptyPan1 = new JPanel();
emptyPan1.setBackground(midBlue);
JPanel emptyPan2 = new JPanel();
emptyPan2.setBackground(midBlue);
JPanel emptyPan3 = new JPanel();
emptyPan3.setBackground(midBlue);
mainPan.add("North", textPanel);
mainPan.add("Center", butPanel);
mainPan.add("South", emptyPan1);
mainPan.add("East", emptyPan2);
mainPan.add("West", emptyPan3);
getContentPane().add(mainPan);
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if ((s.equals("1"))||(s.equals("2"))||(s.equals("3"))||(s.equals("4"))
||(s.equals("5"))||(s.equals("6"))||(s.equals("7"))||(s.equals("8"))
||(s.equals("9"))||(s.equals("0"))||(s.equals("."))){
nums += s;
display.setText(nums);
if (s.equals("/")){
arg=Double.parseDouble(display.getText());
nums="";
div=true;
if (s.equals("*")){
arg=Double.parseDouble(display.getText());
nums="";
mult=true;
if (s.equals("-")){
arg=Double.parseDouble(display.getText());
nums="";
sub=true;
if (s.equals("+")){
arg=Double.parseDouble(display.getText());
nums="";
add=true;
if (s.equals("=")){
tot=Double.parseDouble(display.getText());
if(div)tot=arg/tot;
if(mult)tot=arg*tot;
if(add)tot=arg+tot;
if(sub)tot=arg-tot;
display.setText(df.format(tot));
div=mult=sub=add=false;
public static void main(String[] args){
Calculator frame = new Calculator();
frame.setVisible(true);
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
Image onFrame = Toolkit.getDefaultToolkit().getImage("flag.gif") ;
frame.setIconImage(onFrame);
frame.setLocation(300, 240);
frame.setResizable(false);
frame.pack();
} -
URGENT Help With Scientific Calculator!
Hi everybody,
I designed a calculator, and I need help with the rest of the actions. I know I need to use the different Math methods, but I tried tried that and it didn't work. Also, it needs to work as an applet and application, and in the applet, the buttons don't appear in order, how can I fix that?
I will really appreciate your help with this program, I can't get it to work and I'm frustrated, I need to finish this for next Tuesday 16th. Please e-mail me at [email protected].
Below is the code for the calcualtor.
Thanks a lot!
-Maria
// calculator
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class calculator extends JApplet implements
ActionListener
private JButton one, two, three, four, five, six, seven,
eight, nine, zero, dec, eq, plus, minus, mult, div, clear,
mem, mrc, sin, cos, tan, asin, acos, atan, x2, sqrt, exp, pi, percent;
private JLabel output, blank;
private Container container;
private String operation;
private double number1, number2, result;
private boolean clear = false;
//GUI
public void init()
container = getContentPane();
//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 );
//blank
blank = new JLabel( " " );
container.add( blank );
//clear
clear = new JButton( "CE" );
clear.addActionListener(this);
container.add( clear );
//seven
seven = new JButton( "7" );
seven.addActionListener(this);
container.add( seven );
//eight
eight = new JButton( "8" );
eight.addActionListener(this);
container.add( eight );
//nine
nine = new JButton( "9" );
nine.addActionListener(this);
container.add( nine );
//div
div = new JButton( "/" );
div.addActionListener(this);
container.add( div );
//four
four = new JButton( "4" );
four.addActionListener(this);
container.add( four );
//five
five = new JButton( "5" );
five.addActionListener(this);
container.add( five );
//six
six = new JButton( "6" );
six.addActionListener(this);
container.add( six );
//mult
mult = new JButton( "*" );
mult.addActionListener(this);
container.add( mult );
//one
one = new JButton( "1" );
one.addActionListener(this);
container.add( one );
//two
two = new JButton( "2" );
two.addActionListener(this);
container.add( two );
//three
three = new JButton( "3" );
three.addActionListener(this);
container.add( three );
//minus
minus = new JButton( "-" );
minus.addActionListener(this);
container.add( minus );
//zero
zero = new JButton( "0" );
zero.addActionListener(this);
container.add( zero );
//dec
dec = new JButton( "." );
dec.addActionListener(this);
container.add( dec );
//plus
plus = new JButton( "+" );
plus.addActionListener(this);
container.add( plus );
//mem
mem = new JButton( "MEM" );
mem.addActionListener(this);
container.add( mem );
//mrc
mrc = new JButton( "MRC" );
mrc.addActionListener(this);
container.add( mrc );
//sin
sin = new JButton( "SIN" );
sin.addActionListener(this);
container.add( sin );
//cos
cos = new JButton( "COS" );
cos.addActionListener(this);
container.add( cos );
//tan
tan = new JButton( "TAN" );
tan.addActionListener(this);
container.add( tan );
//asin
asin = new JButton( "ASIN" );
asin.addActionListener(this);
container.add( asin );
//acos
acos = new JButton( "ACOS" );
cos.addActionListener(this);
container.add( cos );
//atan
atan = new JButton( "ATAN" );
atan.addActionListener(this);
container.add( atan );
//x2
x2 = new JButton( "X2" );
x2.addActionListener(this);
container.add( x2 );
//sqrt
sqrt = new JButton( "SQRT" );
sqrt.addActionListener(this);
container.add( sqrt );
//exp
exp = new JButton( "EXP" );
exp.addActionListener(this);
container.add( exp );
//pi
pi = new JButton( "PI" );
pi.addActionListener(this);
container.add( pi );
//percent
percent = new JButton( "%" );
percent.addActionListener(this);
container.add( percent );
//eq
eq = new JButton( "=" );
eq.addActionListener(this);
container.add( eq );
//Set size and visible
setSize( 190, 285 );
setVisible( true );
public static void main(String args[]){
//execute applet as application
//applet's window
JFrame applicationWindow = new JFrame("calculator");
applicationWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//applet instance
calculator appletObject = new calculator();
//init and start methods
appletObject.init();
appletObject.start();
} // end main
public void actionPerformed(ActionEvent ae)
JButton but = ( JButton )ae.getSource();
//dec action
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() );
//clear action
else if( but.getText() == "CE" )
output.setText( "" );
operation = "";
number1 = 0.0;
number2 = 0.0;
//plus action
else if( but.getText() == "+" )
operation = "+";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//minus action
else if( but.getText() == "-" )
operation = "-";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//mult action
else if( but.getText() == "*" )
operation = "*";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//div action
else if( but.getText() == "/" )
operation = "/";
number1 = Double.parseDouble( output.getText() );
clear = true;
//output.setText( "" );
//eq action
else if( but.getText() == "=" )
number2 = Double.parseDouble( output.getText() );
if( operation == "+" )
result = number1 + number2;
else if( operation == "-" )
result = number1 - number2;
else if( operation == "*" )
result = number1 * number2;
else if( operation == "/" )
result = number1 / number2;
//output result
output.setText( String.valueOf( result ) );
clear = true;
operation = "";
//default action
else
if( clear == true )
output.setText( "" );
clear = false;
output.setText( output.getText() + but.getText() );
}Multiple post:
http://forum.java.sun.com/thread.jsp?forum=31&thread=474370&tstart=0&trange=30 -
Hi to everyone,I'm making a calculator in java (with GUI) and I'm stuck so if anyone can help me for two things:
I need a code as simple as possible for keyboard shortcuts for Buttons(I found for JMenuItems but I cant find for JButton) and
I need to freeze the calcuator when its executed so that I cant maximaze or resize it (just like the calculator in Windows).
Thanx in advance and I hope you understood what I need.I need a code as simple as possible for keyboard
shortcuts for Buttons(I found for JMenuItems but I
cant find for JButton) I assume that here you want to make the calculator enter 1 when the "1" is typed? If so, look into keybindings. There's a tutorial on this at Sun's java tutorial site.
and
I need to freeze the calcuator when its executed so
that I cant maximaze or resize it (just like the
calculator in Windows).have you tried calling setResizable on your JFrame (if you are using a JFrame)? -
GUI Calculator (Swing, BorderLayout, etc.)
I am a bit of a crossroads and am needing some advice. I am trying to create a Calculator in a Window (GUI) that looks similar to a keypad. I have three files that I am working on but cannot get any of them to compile without errors. I am confused as to what I have left out and/or where I have taken a wrong turn. I will post them below and would greatly appreciate any insight and/or direction as to how to make this work! Also, I have heard from a "birdie" that there may be some problems that occur if the files are compiled out of order....does this make sense to anyone? Thank you in
advance for any help--Christle
Constants.java file
//Christle Chumney
import java.awt.*;
public interface Constants
Color FUNCTION_COLOR = Color.red;
Color OPERATOR_COLOR = Color.blue;
Color NUMBER_COLOR = Color.black;
}calculator.java file
//Christle Chumney
import java.awt.*;
public class Calculator {
public static void main(String[] args){
theApp = new Calculator();
theApp.init();
public void init() {
aWindow = new CalculatorFrame("My Calculator");
aWindow.setBounds(10, 10, 250, 250);
aWindow.setVisible(true); }
private static CalculatorFrame aWindow;
private static Calculator theApp;
}calculatorFrame.java file
//Christle Chumney
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
public class CalculatorFrame extends JFrame implements Constants //, ActionListener
private Calculator theApp;
JPanel top, bottom;
JTextField display;
JButton button;
// Constructor
public CalculatorFrame(String title)
setTitle(title); // Set the window title
this.theApp = theApp;
JMenuBar swingMenuBar = new JMenuBar();
JMenu swingMenu = new JMenu("swingMenu");
JMenuItem swingMenuItem1, swingMenuItem2, swingMenuItem3;
swingMenuBar.add(swingMenu);
setJMenuBar(swingMenuBar);
JMenu applicationMenu = new JMenu("Function"); // Create Application menu
applicationMenu.setMnemonic('A'); // Create shortcut
// Construct the application pull down menu
exitItem = applicationMenu.add("Exit"); // Add exit item
exitItem.setAccelerator(KeyStroke.getKeyStroke('X',Event.CTRL_MASK ));
applicationMenu.add(exitItem);
menuBar.add(applicationMenu); // Add the file menu
makeButtons();
public void makeButtons() {
BorderLayout border = new BorderLayout();
Container content = getContentPane();
content.setLayout(border);
top = new JPanel(new BorderLayout());
display = new JTextField("");
display.setEditable(false);
display.setBackground(Color.white);
display.setHorizontalAlignment(display.RIGHT);
top.add(display);
bottom = new JPanel();
GridLayout grid = new GridLayout(5,4,5,5);
bottom.setLayout(grid);
bottom.add(button = new JButton("C"));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("<=="));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("%"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("/"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("7"));
bottom.add(button = new JButton("8"));
bottom.add(button = new JButton("9"));
bottom.add(button = new JButton("*"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("4"));
bottom.add(button = new JButton("5"));
bottom.add(button = new JButton("6"));
bottom.add(button = new JButton("-"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("1"));
bottom.add(button = new JButton("2"));
bottom.add(button = new JButton("3"));
bottom.add(button = new JButton("+"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("0"));
bottom.add(button = new JButton("+/-"));
bottom.add(button = new JButton("."));
bottom.add(button = new JButton("="));
button.setForeground(OPERATOR_COLOR);
Container content = aWindow.getContentPane();
content.setLayout(new BorderLayout());
content.add(top, BorderLayout, NORTH);
content.add(bottom, BorderLayout, CENTER);
private JMenuBar menuBar = new JMenuBar(); // Window menu bar
private JMenuItem exitItem; // application menu item
}Thanks in advance (again)-
ChristleHERE R U .JAVA FILES AND THEY WORK FINE NOW NO ERRORS NOTHING JUST THAT U HAVE TO CODE THE EVENTS OF UR APPLICATION
ANYOTHER HELP U NEED UR MOST WELCOME
VIJAY
// CALCULATORFRAME.JAVA
//Christle Chumney
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
public class CalculatorFrame extends JFrame implements Constants //,ActionListener
private Calculator theApp;
JPanel top, bottom;
JTextField display;
JButton button;
// Constructor
public CalculatorFrame(String title)
setTitle(title);
// Set the window title
this.theApp = theApp;
JMenuBar swingMenuBar = new JMenuBar();
JMenu swingMenu = new JMenu("swingMenu");
JMenuItem swingMenuItem1, swingMenuItem2, swingMenuItem3;
swingMenuBar.add(swingMenu);
setJMenuBar(swingMenuBar);
JMenu applicationMenu = new JMenu("Function");
// Create Application menu
applicationMenu.setMnemonic('A');
// Create shortcut
// Construct the application pull down menu
exitItem = applicationMenu.add("Exit");
// Add exit item exitItem.setAccelerator(KeyStroke.getKeyStroke('X',Event.CTRL_MASK )); applicationMenu.add(exitItem);
menuBar.add(applicationMenu);
// Add the file menu
makeButtons();
public void makeButtons()
BorderLayout border = new BorderLayout();
Container content = getContentPane();
content.setLayout(border);
top = new JPanel(new BorderLayout());
display = new JTextField("");
display.setEditable(false);
display.setBackground(Color.white);
display.setHorizontalAlignment(display.RIGHT);
top.add(display);
bottom = new JPanel();
GridLayout grid = new GridLayout(5,4,5,5);
bottom.setLayout(grid);
bottom.add(button = new JButton("C"));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("<=="));
button.setForeground(FUNCTION_COLOR);
bottom.add(button = new JButton("%"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("/"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("7"));
bottom.add(button = new JButton("8"));
bottom.add(button = new JButton("9"));
bottom.add(button = new JButton("*"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("4"));
bottom.add(button = new JButton("5"));
bottom.add(button = new JButton("6"));
bottom.add(button = new JButton("-"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("1"));
bottom.add(button = new JButton("2"));
bottom.add(button = new JButton("3"));
bottom.add(button = new JButton("+"));
button.setForeground(OPERATOR_COLOR);
bottom.add(button = new JButton("0"));
bottom.add(button = new JButton("+/-"));
bottom.add(button = new JButton("."));
bottom.add(button = new JButton("="));
button.setForeground(OPERATOR_COLOR);
Container content1 = this.getContentPane();
content.setLayout(new BorderLayout());
content1.add(top, BorderLayout.NORTH);
content1.add(bottom, BorderLayout.CENTER);
private JMenuBar menuBar = new JMenuBar();
// Window menu bar
private JMenuItem exitItem;
// application menu item
// CALCULATOR.JAVA
import java.awt.*;
public class Calculator
public static void main(String[] args)
{ theApp = new Calculator();
theApp.init();
public void init()
aWindow = new CalculatorFrame("My Calculator");
aWindow.setBounds(10, 10, 250, 250);
aWindow.setVisible(true);
private static CalculatorFrame aWindow;
private static Calculator theApp;
// CONSTANTS.JAVA
import java.awt.*;
public interface Constants
Color FUNCTION_COLOR = Color.red;
Color OPERATOR_COLOR = Color.blue;
Color NUMBER_COLOR = Color.black; -
HC - A scientific, graphing, supp complex nums CLI and GUI calculator
I uploaded all three packages to AUR! Please use the PKGBUILDs there if you want to install this now. Thanks a lot goran'agar and foutrelis for help with the PKGBUILDs.
AUR links:
mapm : http://aur.archlinux.org/packages.php?ID=32319
hc : http://aur.archlinux.org/packages.php?ID=32321
hcg : http://aur.archlinux.org/packages.php?ID=32320
UPDATE (28.2.2010) : I now also finally have a github account where you can find the newest version of hc (cli only) which obviously has all the newest things I implemented but on the other hand it may be unstable. Anyway, here's the link : http://github.com/houbysoft/hc
Hello ArchLinux users,
some time ago, I was a little unsatisfied with existing calculators (either it was too memory/CPU-consuming (it had to work well, among others, on a 128MB RAM computer), or it lacked the functions I needed (f.ex. nCr and nPr)), and so I decided to write my own command-line (now there also is a GUI version) calculator.
Here is a little description:
The goal of this program is to provide an open source calculator with a
simple and easy-to-use interface, similar to a command prompt, but a lot of
options and a multitude of functions.
You can also type "help" in the command prompt if you need any help - or
contact me here.
There are two major versions of HC -- a CLI (command line interface) and a
GUI (graphical user interface).
To get you an idea, have some screenshots:
CLI version
GUI version
I thought some of you might like it, so I posted it here. It is of course open source (GPL v3) and cross-platform (precompiled for Linux and Windows).
The calculator's homepage is
http://houbysoft.com/hc/
If you're interested, you'll find a lot more details there.
Please post some feedback/criticism etc.; also please report any bugs - I started this project ~2 months ago so it is not yet completely stable and complete.
Thanks for reading, give it a try!
Last edited by y27 (2010-03-01 01:24:13)goran'agar wrote:I'm not able to create any PKGBUILD for the application itself as the website executes a php script before allowing the download.
Thanks a lot, I'll test it out soon.
If you'd help me with the PKGBUILD for my app itself, the full links are:
http://houbysoft.com/download/hc-VERSION-TYPE.tar.gz
where VERSION is the version number, so for example 0.4.2, and TYPE is either linux or src.
I'm not sure which format of URLs is needed so please ask me if you need something else.
Also, for windows versions, the urls are:
http://houbysoft.com/download/hc-VERSION-win.[b]zip[/b]
(in case you care).
tomd123 wrote:Feature requests: variable assignment and function declaration.
BTW, have you considered using the python interpretor for your calculations? If the functions you need aren't already in it, you can easily add them.
Functions and variables:
I'll put it on my roadmap
For the python interpreter : yes, I did, but dismissed it because:
- it's not very convenient - you have to retype stuff to floats if you don't want only integer results
- it's slow (again, this had to work and take a very small amount of CPU and memory on a 333MHz and 128 MB RAM system), and in algorithms where speed is crucial this would be even more of a concern
- I know about psyco to speed it up, but AFAIK it doesn't work on 64bit processors
- I wanted it to be small and minimalistic, installing a python distribution imo isn't
- I like programming, writing a calculator is fun -
Need help with a calculated column - is there any way to reference a value in the current row?
Hey guys,
I'm a bit of a DAX newbie, and I'm running into a block. I'm creating a Power View report about IT tickets. We are going to be creating a cube to automate the data soon, I'm currently working with a flat Excel Data Table of data to demonstrate the Power
View reporting capabilities to the team. I need the default display to show the top 4-5 items basked on the Ticket Count. The three applicable columns I'm using are the TicketID, the ContactReason, and the AssetCategory - all three are
text. One slide will show the top five Contact Reasons by Ticket Count, and the other will show the top five Categories by Ticket Count. The users will see this default view, but will be able to change it to see differently ranked items or can clear the
ranking slicer altogether.
What I've accomplished so far is to create the Calculated Field [Ticket Count] = COUNTA(Table1[TicketID])
And 2 other calculated fields:
[Contact Rank] = RANKX(ALL(Table1[ContactReason]),[Ticket Count],,,DENSE)
[Asset Rank] = RANKX(ALL(Table1[AssetCategory]),[Ticket Count],,,DENSE)
If I were creating a Pivot Table, this would be great. These fields calculate everything the right way. The problem is, I need to have a Rank slicer on each slide and the calculation by itself contains no data - with no data, there's nothing to slice. I
realized I need to actually have columns of data so I can create a slicer. I need each row of the table to show the same [Contact Rank] for every instance of a particular ContactReason (and the same for the [Asset Rank] and AssetCategory).
The RANKX formulas pasted into the Calculated Column section only show a value of 1 - with no Pivot table summarizing the fields, it's counting each row's ticket once, giving every line the tied Rank of #1.
I've solved the problem in Excel by creating 2 Pivot Tables on a separate sheet that have the data field and the calculated field for ContactRason and AssetCategory. Then on my Excel Data Table, I've added two columns that do a VLOOKUP and pull over a the
Calculated Rank from each Pivot Table that match the ContactReason and AssetCategory fields. This works on the flat Excel Data Table now, but will not be a solutions when we start pulling the data from the cube (and there is no flat table).
What I think I need is an Expression for the RANKX formula that can give me, for each row, the count of all of the times a ContactReason shows up in an entire column. There's only about 100,000 lines of data and each ContactReason or AssetCategory
may show up several thousand times. But if I can get the expression to return that count, then the RANKX formula should work in the Column. If it wasn't a DAX formula, I'd use a COUNTIF and say 'Count the entire ContactReason column anytime it's equal to the
ContactReason on THIS row', but in DAX I don't know how to reference a single value in a row. I've tried the CALCULATE() formula, but it seems like the filter needs a specific value, and doesn't work on a dynamic "cell" value.
Any help would be greatly appreciated! (I hope it all makes sense!)If I've understood you correctly then the ALLEXCEPT function may be what you're after and it could be applied in a similar way to the following...
=
RANKX(
ALL(Table1),
CALCULATE(
COUNTROWS(table1),
ALLEXCEPT(Table1, Table1[ContactReason])
DENSE
If this has missed the mark, would it be possible to clarify the requirement further?
Regards,
Michael Amadi
Please use the 'Mark as answer' link to mark a post that answers your question. If you find a reply helpful, please remember to vote it as helpful :)
Website: http://www.nimblelearn.com
Blog: http://www.nimblelearn.com/blog
Twitter: @nimblelearn -
Need Help With Custom Calculation Script
Hey everyone. I'm using Acrobat Pro X and stumbling a bit on the syntax for the following equation. I need to add the value of "Cell1" & "Cell2" then add the value of "Cell3". However,the value of "Cell3" is entered by the user and specifies a percentage of the sum of "Cell1 & "Cell2". For example: If the user enters "3" into "Cell3" I need the returned value to be 3% of the sum of "Cell1" + "Cell2". If the user enters "9" into "Cell3" I need the returned value for "Cell3" to be 9% of the sum of "Cell1 & Cell2" and the end result needs to be the sum of "Cell1+Cell2+Cell3". In greater detail:
If "Cell1" = $500, "Cell2" = $500 and "Cell3" = "3" then I need the returned value to be $1030.00.
I hope this makes sense. Here's what I have so far but alas, it's not working. Any help would be GREATLY appreciated.
// Get first field value, as a number
var v1 = +getField("Cell1").value;
// Get second field value, as a number
var v2 = +getField("Cell2").value;
// Get processing field value, as a number
//var v3 = +getField("Cell3"/100).value;
// Calculate and set this field's value to the result
event.value = v3+(v1+v2);
Thanks,
SolanI posted an answer but realized it wasn't what you wanted. There is some confusion about what you want for Cell3. On the one hand, you say you want the user to enter a vaule in the field, but them you say you want its value to be calculated based on what the user enters and two other field values. It seems to me Cell3 should be the field that the user enters the percentage and the calculated field's (Cell4) script could then be:
// Get first field value, as a number
var v1 = +getField("Cell1").value;
// Get second field value, as a number
var v2 = +getField("Cell2").value;// Get processing field value, as a number
// Get the percentage
var v3 = +getField("Cell3").value;
// Calculate and set this field's value to the result
event.value = (1 + v3 / 100) * (v1 + v2); -
Help with Custom calculation script in Acrobat 8
Hi all, I am using acrobat 8 on OS 10.5
I am trying to add certain fields (numbers) and then subtract another field value to give an end result.
I don't know anything about Javascript, would anyone be able to help with any info on how I achieve this result? I can only see Add, x and average etc... nothing there for subtraction
Thanks for any help in advance
SwenThis should get you started:
>if (event) {
// get values from two text fields
var a = Number(this.getField('Text1').value);
var b = Number(this.getField('Text2').value);
// subtract the values and show it
this.event.target.value = a - b;
Place this in a 3d text field, as a Custom Calculation Script. -
Need help with form calculations
I'm converting a non-editable PDF form into an editable one and could use some help as I'm am new to this. Note: I did not create the non-editable form, It's a form I downloaded and use in my business.
I already figured out how to create text fields in the already created PDF non-editable form, now I'm trying to add in calculations. I can create the (value is the) calculations between 2 or more text fields, but now I need to multiply one text field by the number 3 and have the answer show up in another text field.
Example:
I'll use the letters A & B for the text filed names in my example.
I have text field A calculating the sum of other text fields using the (value is the sum of) option under the (calculate properties box.)
Now I want text field B to multiply text field A by a fixed number of 3. (A=24) x 3=72. I need text field B to have the answer of 72 in it.
I need text field B to always multiply text field A by 3.
Does anyone know how I can accomplish this?
I'm using Adobe 8 Pro.
Please note that I have no experiance using custom calculation script if that is the only way this will work and will step by step instruction on how to write the code.
Thank you very much.You can use the simplified field notation option. In this case, you'd enter:
3 * A
Where "A" the the exact name of the A field. It is best to avoid spaces and any other special characters for any fields that you'll want to include when using simplified field notation option. -
Help with query calculations (recursive)
Hi All,
I want some help with a query using a base rate and the result use in the next calculation year.
Here an example:
create table rate_type(
rate_type_id number,
rate_desc nvarchar2(50),
rate_base_year number
insert into rate_type(rate_type_id, rate_desc, rate_base_year) values (1, 'Desc1', 4.6590);
insert into rate_type(rate_type_id, rate_desc, rate_base_year) values (2, 'Desc2', 4.6590);
create table rates (
rate_type_id number
rate_year number,
rate_value number
insert into rates(rate_type_id, rate_year, rate_value) values (1, 2012, 1.2);
insert into rates(rate_type_id, rate_year, rate_value) values (1, 2013, 1.3);
insert into rates(rate_type_id, rate_year, rate_value) values (1, 2014, 1.4);
insert into rates(rate_type_id, rate_year, rate_value) values (2, 2012, 1.2);
insert into rates(rate_type_id, rate_year, rate_value) values (2, 2013, 1.3);
insert into rates(rate_type_id, rate_year, rate_value) values (2, 2014, 1.4);The calculation for the first year should be the base rate of the rate type. The next year should use the result of the previous year and so on.
The result of my sample data is:
2012 = 4.659 + 1.2 + 4.659 * (1.2 * 0.01) = 5.9149
2013 = 5.9149 + 1.3 + 5.9149 * (1.3 * 0.01) = 7.1859
2014 = 7.1859 + 1.4 + 7.1859 * (1.4 * 0.01) = 8.4721Query result:
NAME 2012 2013 2014
Desc1 5.9149 7.1859 8.4721
Desc2 XXXX XXX XXXX
How can I do this in one select statement? Any ideas?
Thanks!Assuming you are on 11.2:
with t as (
select a.rate_type_id,
rate_desc,
rate_year,
rate_base_year,
rate_value,
count(*) over(partition by a.rate_type_id) cnt,
row_number() over(partition by a.rate_type_id order by rate_year) rn
from rate_type a,
rates b
where a.rate_type_id = b.rate_type_id
r(
rate_type_id,
rate_desc,
rate_year,
rate_base_year,
rate_value,
cnt,
rn,
result
) as (
select rate_type_id,
rate_desc,
rate_year,
rate_base_year,
rate_value,
cnt,
rn,
rate_base_year + rate_value + rate_base_year * rate_value * 0.01 result
from t
where rn = 1
union all
select t.rate_type_id,
t.rate_desc,
t.rate_year,
t.rate_base_year,
t.rate_value,
t.cnt,
t.rn,
r.result + t.rate_value + r.result * t.rate_value * 0.01 result
from r,
t
where t.rate_type_id = r.rate_type_id
and t.rn = r.rn + 1
select *
from (
select rate_desc name,
rate_year,
result
from r
where rn <= cnt
pivot (sum(result) for rate_year in (2012,2013,2014))
order by name
NAME 2012 2013 2014
Desc1 5.914908 7.2918018 8.79388703
Desc2 5.914908 7.2918018 8.79388703
SQL> Obviously pivoting assumes you know rate_year values upfront. If not, then without pivoting:
with t as (
select a.rate_type_id,
rate_desc,
rate_year,
rate_base_year,
rate_value,
count(*) over(partition by a.rate_type_id) cnt,
row_number() over(partition by a.rate_type_id order by rate_year) rn
from rate_type a,
rates b
where a.rate_type_id = b.rate_type_id
r(
rate_type_id,
rate_desc,
rate_year,
rate_base_year,
rate_value,
cnt,
rn,
result
) as (
select rate_type_id,
rate_desc,
rate_year,
rate_base_year,
rate_value,
cnt,
rn,
rate_base_year + rate_value + rate_base_year * rate_value * 0.01 result
from t
where rn = 1
union all
select t.rate_type_id,
t.rate_desc,
t.rate_year,
t.rate_base_year,
t.rate_value,
t.cnt,
t.rn,
r.result + t.rate_value + r.result * t.rate_value * 0.01 result
from r,
t
where t.rate_type_id = r.rate_type_id
and t.rn = r.rn + 1
select rate_desc name,
rate_year,
result
from r
where rn <= cnt
order by name,
rate_year
NAME RATE_YEAR RESULT
Desc1 2012 5.914908
Desc1 2013 7.2918018
Desc1 2014 8.79388703
Desc2 2012 5.914908
Desc2 2013 7.2918018
Desc2 2014 8.79388703
6 rows selected.
SQL> SY. -
Urgent! Need help in GUI!
Hi, I am doing a small java project and I am expected to code all the GUI I need in just one class file. Can someone help me? My GUI consists of 2 JButtons, 2 JLabels and 1 JTextField. Also I need to have ActionListener for both of the buttons all in just 1 class file. Anyone please help. It is better if you can provide me with some sample coding to view
That sounds like a very arbitrarily cooked-up requirement. Homework?
Assuming your class needs to be a component itself, simply add the buttons, labels and fields into it, typically within the constructor.
If you mean "one source file" then I would advise using an inner class as your ActionListener; you may even want two. You may like to use anonymous classes which, for instance, call methods in your outer class. All of these solutions will produce more than one class file from the single source file.
If you really do mean "one class file" then you will need your outer class to implement ActionListener and determine from the getActionCommand() or getSource() methods which of the two buttons the event emanated from. It's a less clean way of going about it, but you get your single class file.
No sample code - if you need further explanation of the above then just Google for the underlined terms. -
Hi,
I have zip code database and i am trying to get the records based on 100/80/60/40 miles radius.
I Google through and got couple of article explains about using Haversine Formula. Also, following link has a function to calculate the distance.
[url=http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=81360][/url]
seems, this article/function build before the sqlserver 2008 born. Is there any better way to achieve this?
Below the sample structure of my table.
Create table ZipCodes(ID bigint primary key identity(1,1),ZipCode varchar(10),
Address varchar(4000), city varchar(50),state varchar(50),Latitude float,Longitude float)
Create table Mall_Sores(StoreId bigint primary key identity(1,1),StoreName varchar(50),ZipCode varchar(10),
Address varchar(4000), city varchar(50),state varchar(50))
Mall_Sores table has 1 million records. If i pass '10001' as zip i need to look at 20 mile radius of the zipcode and list out the store names.
Any sample will be very appreciated.
loving dotnetHave a look at the GEOGRAPHY data type.
Because you have the LAT and LONG, you can easily create a calculated column which then has a point object of the geography data type. You can then use the native functions to join the tables based on the distance being less than a specified
value.
This requires SQL Server 2008 or later.
Check out this article to create the point data type :
http://www.sql-server-helper.com/sql-server-2008/convert-latitude-longitude-to-geography-point.aspx
Maybe you are looking for
-
How to create different labels in SAP 8.8?
Do I have to use ALD for SAP 8.8 (Is it even available for 8.8?) or do I have to use Crystal Report only? Or is there any other method? I do not think customer would like to pay for another add-on or be complicated by another add-on maintenance etc.
-
Oracle Database11g Express Edition - Some Problems after Installation
Seemed everything went ok until I tried the Query Builder. Selected a Table and checked fields to include in my Query. These fields do not appear in the "Columns" TAB below as the documentation says they should. Any ideas what's wrong? Additionally,
-
Need help Itunes wont re install
Error writing to file C:\Program Files\Common Files\Apple\Apple Application support\Webkit.resources\inspector\ApplicationCaheItemsView.js vertify you have access to this dictonary. How can I fix this?
-
Install Oracle client 9.2.0.1 on AIX 5L
Hell'o, I have a problem while I try to install the client client 9.2.0.1 on AIX 5L. I first installed (custom installation): - network utilities - database utilities - sqlplus - jdbc/oci interface the installation is ok with thisThen I want to add:
-
I am spinning up a new VM server for Prime to migrate from NCS. I have not been able to find the patch Cisco recommends to run before upgrading. My question is do I need to run this patch (ncs_patch-1.1.1.24-upgrade-12.tar.gz) if I am just gong to br