Binding keys to JButtons - java

I have a fairly simple Calculator and I am trying to bind keys to JButtons. I am new to Java and I don't know much. I do know it involves ActionListener but I can't wrap my head around how to get it into what I currently have.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class Calculator2 extends JFrame implements ActionListener {
// Declare the GUI objects and variables HERE
JTextField ansText;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, plus, minus, multi, div,
equal, clear;
JPanel p1, p2, p3;
Double val1 = 0.0, val2 = 0.0, answer = 0.0;
int operator = 0;
public static void main(String[] args) {
new Calculator2();
}
public Calculator2() {
// GUI Creation Code goes HERE
ansText = new JTextField("", 7);
ansText.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
ansText.addKeyListener(new KeyAdapter() { //Allow only numbers in ansText
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
e.consume();
}
}
});
b1 = new JButton("1");
b1.addActionListener(this);
b2 = new JButton("2");
b2.addActionListener(this);
b3 = new JButton("3");
b3.addActionListener(this);
b4 = new JButton("4");
b4.addActionListener(this);
b5 = new JButton("5");
b5.addActionListener(this);
b6 = new JButton("6");
b6.addActionListener(this);
b7 = new JButton("7");
b7.addActionListener(this);
b8 = new JButton("8");
b8.addActionListener(this);
b9 = new JButton("9");
b9.addActionListener(this);
b0 = new JButton("0");
b0.addActionListener(this);
plus = new JButton("+");
plus.addActionListener(this);
minus = new JButton("-");
minus.addActionListener(this);
multi = new JButton("*");
multi.addActionListener(this);
div = new JButton("/");
div.addActionListener(this);
equal = new JButton("=");
equal.addActionListener(this);
clear = new JButton("C");
clear.addActionListener(this);
this.setLayout(new BorderLayout());
p1 = new JPanel();
this.add(p1, BorderLayout.NORTH);
p1.setLayout(new GridLayout(0, 1, 2, 2));
p1.add(ansText);
p2 = new JPanel();
this.add(p2, BorderLayout.CENTER);
p2.setLayout(new GridLayout(4, 3, 2, 2));
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(plus);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(minus);
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(multi);
p2.add(clear);
p2.add(b0);
p2.add(equal);
p2.add(div);
this.setSize(200, 250);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//Number input
if (e.getSource() == b1) {
ansText.setText(ansText.getText() + b1.getText());
}
else if (e.getSource() == b2) {
ansText.setText(ansText.getText() + b2.getText());
}
else if (e.getSource() == b3) {
ansText.setText(ansText.getText() + b3.getText());
}
else if (e.getSource() == b4) {
ansText.setText(ansText.getText() + b4.getText());
}
else if (e.getSource() == b5) {
ansText.setText(ansText.getText() + b5.getText());
}
else if (e.getSource() == b6) {
ansText.setText(ansText.getText() + b6.getText());
}
else if (e.getSource() == b7) {
ansText.setText(ansText.getText() + b7.getText());
}
else if (e.getSource() == b8) {
ansText.setText(ansText.getText() + b8.getText());
}
else if (e.getSource() == b9) {
ansText.setText(ansText.getText() + b9.getText());
}
else if (e.getSource() == b0) {
ansText.setText(ansText.getText() + b0.getText());
}
//Operator input
else if (e.getSource() == plus) {
operator = 1;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
else if (e.getSource() == minus) {
operator = 2;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
else if (e.getSource() == multi) {
operator = 3;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
else if (e.getSource() == div) {
operator = 4;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
//Misc
else if (e.getSource() == equal) {
val2 = Double.parseDouble(ansText.getText());
if (operator == 1) {
answer = val1 + val2;
ansText.setText("" + answer);
} else if (operator == 2) {
answer = val1 - val2;
ansText.setText("" + answer);
} else if (operator == 3) {
answer = val1 * val2;
ansText.setText("" + answer);
} else if (operator == 4) {
answer = val1 / val2;
ansText.setText("" + answer);
}
}
else if (e.getSource() == clear) {
ansText.setText("");
val1 = 0.0;
val2 = 0.0;
answer = 0.0;
operator = 0;
}
}
}

How to Use Key Bindings tutorial describes details of key bindings. Here is a simple example how to bind an action to a plus key both on the keypad and main keyboard:
JPanel panel = new JPanel();
JPanel panel = new JPanel();
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "plus");
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS,
InputEvent.SHIFT_MASK), "plus");
panel.getActionMap().put("plus", plusAction);
panel.add(button);

You do not want to have a single class with a few inner classes doing all your work. Java Swing, like most other GUI systems, is based on MVC, Model-View-Controller.
The Model here would be some object that contains the current value of the accumulator and the value being stored in the display. Were you writing a RPN calculator, the model object would contain the RPN stack.
The View would be the Swing classes: the JTextField, and the JButtons.
The Controller would be some new object, say CalculatorController, that does the actual work. Instead of your ActionListener adding, subtracting, multiplying, or dividing the numbers, they would call methods on your CalculatorController, and that object, in turn, would update the JTextField.
The suggestion by jedyobidan to look at Oracle's documentation is very good. You'd want to put the key strokes into the input map of the JPanel itself since they should apply no matter where in the panel the user has focused upon. The action maps would then hold AbstractActions that call methods on the CalculatorController.
I've always thought that the style of GUI development on the Mac or its predecessor NeXT, with their Interface Builder programs, is much better for novices than the style used by Java Swing.

Related

Why wont my JOptionPane error message pop up?

I made a GUI program where it counts certain elements of whatever is entered in the main text field. If the text field is empty, a message should pop up saying that the user should enter text in the text field. I made an if statement if tfMain == null, a JOptionPane message should pop-up, but for some reason it won't. Any tips on why it doesn't pop up?
here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class LabExcer9 extends WindowAdapter implements ActionListener
{
//Container
private Frame f;
private Panel p1,p2,p3;
//Component
private Button bReadAndComp, bClear;
private TextField tfMain,tf1,tf2,tf3,tf4,tf5,tf6;
private Label l1,l2,l3,l4,l5,l6;
public LabExcer9()
{
f = new Frame("Character Counter of Miguel Martin");
p1 = new Panel();
p2 = new Panel();
p3 = new Panel();
bReadAndComp = new Button("Read and Compute");
bClear = new Button("Clear ALL Values");
tfMain = new TextField(null);
tf1 = new TextField("0");
tf2 = new TextField("0");
tf3 = new TextField("0");
tf4 = new TextField("0");
tf5 = new TextField("0");
tf6 = new TextField("0");
l1 = new Label("Number of Words ");
l2 = new Label("Number of Characters ");
l3 = new Label("Number of Vowels ");
l4 = new Label("Number of Consonants ");
l5 = new Label("Number of Digits ");
l6 = new Label("Number of Symbols and Spaces ");
}
public void assembleGUI()
{
p1.setLayout(new GridLayout(1,1));
p1.setPreferredSize(new Dimension(200, 200));
p1.add(tfMain);
p2.setLayout(new GridLayout(6,2));
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
p2.add(l3);
p2.add(tf3);
p2.add(l4);
p2.add(tf4);
p2.add(l5);
p2.add(tf5);
p2.add(l6);
p2.add(tf6);
p3.setLayout(new GridLayout(1,2));
p3.add(bReadAndComp);
p3.add(bClear);
f.add(p1,BorderLayout.NORTH);
f.add(p2,BorderLayout.CENTER);
f.add(p3,BorderLayout.SOUTH);
f.pack();
f.addWindowListener(this);
f.setVisible(true);
//registers
bReadAndComp.addActionListener(this);
bClear.addActionListener(this);
}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
//gets main text
String textString = tfMain.getText();
//puts words into array
int vowels = 0, consonants = 0, digits = 0, symbolsAndSpaces = 0;
int characters = textString.length();
if(tfMain.getText() == "" || tfMain.getText() == null )
{
if(source == bReadAndComp)
JOptionPane.showMessageDialog(null, "Please Enter Text!");
}
else if(tfMain.getText() != null && tfMain.getText() != "")
{
if(source == bReadAndComp)
{
for(int i = 0;i<textString.length();i++)
{
if(Character.isDigit(textString.charAt(i)))
digits++;
if(Character.isLetterOrDigit(textString.charAt(i)) == false)
symbolsAndSpaces++;
if(isVowel(textString.charAt(i)) == true)
vowels++;
else if(Character.isDigit(textString.charAt(i)) == false && isVowel(textString.charAt(i)) == false && textString.charAt(i) != ' ' && Character.isLetter(textString.charAt(i)) == true)
consonants++;
}
tf1.setText(""+textString.split(" ").length);
tf2.setText(""+characters);
tf3.setText(""+vowels);
tf4.setText(""+consonants);
tf5.setText(""+digits);
tf6.setText(""+symbolsAndSpaces);
//System.out.println(textStringArray[0]+"wat");
//JOptionPane.showMessageDialog(null, "Please Enter Text!");
}
else if (source == bClear)
{
tf1.setText("0");
tf2.setText("0");
tf3.setText("0");
tf4.setText("0");
tf5.setText("0");
tf6.setText("0");
tfMain.setText(null);
}
}
}
public boolean isVowel(char c)
{
if (c == 'a' || c == 'A' ||c== 'e' ||c == 'E' ||c == 'i' ||c == 'I' ||c == 'o' ||c == 'O' ||c == 'u' ||c == 'U')
return true;
else
return false;
}
public static void main(String args [])
{
LabExcer9 GUI = new LabExcer9();
GUI.assembleGUI();
}
}
To compare string please use equals or equalsIgnoreCase.
Replace your
if(tfMain.getText() == "" || tfMain.getText() == null )
statement with the following:
if("".equals(tfMain.getText())){
}

Infinite loop while comparing characters in a string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
What statement should I use to compare the characters in a string one by one so that it does not enter an infinite loop. Something like comparing an array of characters in C/C++.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class Calcc extends JFrame implements ActionListener {
String l = "b";
int z = 0;
JFrame f;
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(10);
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("0");
JButton b11 = new JButton("+");
JButton b12 = new JButton("-");
JButton b13 = new JButton("*");
JButton b14 = new JButton("/");
JButton b15 = new JButton("=");
Calcc() {
f = new JFrame();
f.add(t1);
f.add(t2);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(b10);
f.add(b11);
f.add(b12);
f.add(b13);
f.add(b14);
f.add(b15);
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);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
f.setVisible(true);
f.setSize(350, 350);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String d;
d = t1.getText();
if (e.getSource() == b1) {
t1.setText(d + "1");
}
if (e.getSource() == b2) {
t1.setText(d + "2");
}
if (e.getSource() == b3) {
t1.setText(d + "3");
}
if (e.getSource() == b4) {
t1.setText(d + "4");
}
if (e.getSource() == b5) {
t1.setText(d + "5");
}
if (e.getSource() == b6) {
t1.setText(d + "6");
}
if (e.getSource() == b7) {
t1.setText(d + "7");
}
if (e.getSource() == b8) {
t1.setText(d + "8");
}
if (e.getSource() == b9) {
t1.setText(d + "9");
}
if (e.getSource() == b10) {
t1.setText(d + "0");
}
if (e.getSource() == b11) {
t1.setText(d + "+");
}
if (e.getSource() == b12) {
t1.setText(d + "-");
}
if (e.getSource() == b13) {
t1.setText(d + "*");
}
if (e.getSource() == b14) {
t1.setText(d + "/");
}
if (e.getSource() == b15) {
while (l != "a") {
int b = calcA(d);
if (l == "+")
z = z + b;
else if (l == "-")
z = z - b;
else if (l == "*")
z = z * b;
else if (l == "*")
z = z * b;
}
t2.setText(String.valueOf(z));
}
}
int calcA(String d1) {
l = "a";
int k = 0;
while ((d1 != "+") && (d1 != "-") && (d1 != "*") && (d1 != "/")) {
if (d1 != "\n")
break;
k = k * 10 + Integer.valueOf(d1);
}
l = d1;
return k;
}
}
public class CalcD {
public static void main(String[] args) {
new Calcc();
}
}
You appear to be comparing strings alot, using == to do it is bad practice.
This is because Strings are objects and comparing using the == operator will check to see if they are the exact same object regardless of value. Strings are a special case, when creating a String the jvm will decide whether or not to use an existing object or create a new one, so we can not be 100% sure if "==" will return true or not even the they contain the same value.
To compare Strings please use string1.equals(string2).
The .equals method should be used to compare the value of objects, and the == operator to compare primitives.
You do not need to check with any character like you do in C/C++. You need to simply iterate it with the length of the String. Simply use this in your loop:
for (int i=0;i<string.length();i++) {
char c = string.charAt(i);
// do whatever with your character.
}
That said, when you compare strings for equality in Java, you should always use the String.equals method instead of ==.
So, you should change your code from
getSource() == b1
to
getSource().equals(b1)
Hope this helps!
Thank you guys for clarifying some doubts....
for the above programme i used String.charAt(int);
to compare every specific character at the loop....

JavaFX Program lags

So I'm a college student presently learning Java and JavaFX by myself, with some help from you all.
I'm trying to start by making a relatively simple calculator, customizing it with some CSS. My program works fine, the only real problem is the lag whenever I actually calculate what I want. So I'll go, "5 + 5 =" and as soon as I hit equals it lags and then shows "10". Not sure why and I haven't found much on it.
Thanks for the help in advance.
NOTE: If you have any other suggestions to help me improve my code, feel free to post it. I have a long way to go.
import javafx.application.Application;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javax.script.ScriptEngineManager;
import java.math.BigDecimal;
import javax.script.ScriptEngine;
public class practice3 extends Application {
Stage window;
Button plus,
minus,
divide,
multiply,
clear,
zero,
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
decimal,
equals;
TextField display;
double total,
num1;
String input = "";
String equationInput = ""; //equationInput will store all data up to a symbol is pressed
Label equation;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Simple Calculator");
//Display Text Field
display = new TextField();
display.setEditable(false);
display.setPrefHeight(70);
display.setFont(Font.font("Verdana", 50));
equation = new Label();
equation.setPrefHeight(70);
equation.setFont(Font.font("Verdana", 12));
equation.setText(equationInput);
equation.setPrefWidth(209);
equation.setPadding(new Insets(0, 0, 3, 3));
//Buttons
plus = new Button("+");
plus.setPrefSize(70, 70);
plus.setOnAction(e - >operationButton("+"));
minus = new Button("-");
minus.setPrefSize(70, 70);
minus.setOnAction(e - >operationButton("-"));
divide = new Button("/");
divide.setPrefSize(70, 70);
divide.setOnAction(e->operationButton("/"));
multiply = new Button("*");
multiply.setPrefSize(70, 70);
multiply.setOnAction(e->operationButton("*"));
clear = new Button("C");
clear.setPrefSize(70, 70);
clear.setOnAction(e->clearButton());
equals = new Button("=");
equals.setPrefSize(70, 70);
equals.setOnAction(e->{
try {
calculate();
} catch(Exception e1) {
System.out.println("Error in code.");
}
});
decimal = new Button(".");
decimal.setPrefSize(70, 70);
decimal.setOnAction(e->decimalButton());
//Numbers
one = new Button("1");
one.setPrefSize(70, 70);
one.setOnAction(e->numberButton("1"));
two = new Button("2");
two.setPrefSize(70, 70);
two.setOnAction(e->numberButton("2"));
three = new Button("3");
three.setPrefSize(70, 70);
three.setOnAction(e->numberButton("3"));
four = new Button("4");
four.setPrefSize(70, 70);
four.setOnAction(e->numberButton("4"));
five = new Button("5");
five.setPrefSize(70, 70);
five.setOnAction(e->numberButton("5"));
six = new Button("6");
six.setPrefSize(70, 70);
six.setOnAction(e->numberButton("6"));
seven = new Button("7");
seven.setPrefSize(70, 70); //WidthxHeight
seven.setOnAction(e->numberButton("7"));
eight = new Button("8");
eight.setPrefSize(70, 70);
eight.setOnAction(e->numberButton("8"));
nine = new Button("9");
nine.setPrefSize(70, 70);
nine.setOnAction(e->numberButton("9"));
zero = new Button("0");
zero.setPrefSize(70, 70);
zero.setOnAction(e->numberButton("0"));
BorderPane layout = new BorderPane();
GridPane grid = new GridPane();
layout.setCenter(grid);
layout.setTop(display);
//Setting Constraints for Buttons and Equation Display
grid.setConstraints(seven, 0, 1);
grid.setConstraints(eight, 1, 1);
grid.setConstraints(nine, 2, 1);
grid.setConstraints(clear, 3, 0);
grid.setConstraints(four, 0, 2);
grid.setConstraints(five, 1, 2);
grid.setConstraints(six, 2, 2);
grid.setConstraints(plus, 3, 1);
grid.setConstraints(one, 0, 3);
grid.setConstraints(two, 1, 3);
grid.setConstraints(three, 2, 3);
grid.setConstraints(minus, 3, 2);
grid.setConstraints(decimal, 0, 4);
grid.setConstraints(zero, 1, 4);
grid.setConstraints(multiply, 3, 3);
grid.setConstraints(divide, 3, 4);
grid.setConstraints(equals, 2, 4);
grid.setConstraints(equation, 0, 0, 3, 1);
display.setStyle("-fx-focus-color: transparent;");
grid.getChildren().addAll(seven, eight, nine, clear, four, five, six, plus, one, two, three, minus, decimal, zero, multiply, divide, equals, equation);
layout.setPadding(new Insets(5, 5, 5, 5));
display.setText("0");
Scene scene = new Scene(layout, 290, 462);
//Keyboard Events
scene.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> {
if (key.getCode() == KeyCode.DIGIT1 || key.getCode() == KeyCode.NUMPAD1) {
numberButton("1");
}
else if (key.getCode() == KeyCode.DIGIT2 || key.getCode() == KeyCode.NUMPAD2) {
numberButton("2");
}
else if (key.getCode() == KeyCode.DIGIT3 || key.getCode() == KeyCode.NUMPAD3) {
numberButton("3");
}
else if (key.getCode() == KeyCode.DIGIT4 || key.getCode() == KeyCode.NUMPAD4) {
numberButton("4");
}
else if (key.getCode() == KeyCode.DIGIT5 || key.getCode() == KeyCode.NUMPAD5) {
numberButton("5");
}
else if (key.getCode() == KeyCode.DIGIT6 || key.getCode() == KeyCode.NUMPAD6) {
numberButton("6");
}
else if (key.getCode() == KeyCode.DIGIT7 || key.getCode() == KeyCode.NUMPAD7) {
numberButton("7");
}
else if (key.getCode() == KeyCode.DIGIT8 || key.getCode() == KeyCode.NUMPAD8) {
numberButton("8");
}
else if (key.getCode() == KeyCode.DIGIT9 || key.getCode() == KeyCode.NUMPAD9) {
numberButton("9");
}
else if (key.getCode() == KeyCode.DIGIT0 || key.getCode() == KeyCode.NUMPAD0) {
numberButton("0");
}
else if (key.getCode() == KeyCode.PERIOD || key.getCode() == KeyCode.DECIMAL) {
decimalButton();
}
else if (key.getCode() == KeyCode.ADD) {
operationButton("+");
}
else if (key.getCode() == KeyCode.SUBTRACT) {
operationButton("-");
}
else if (key.getCode() == KeyCode.MULTIPLY) {
operationButton("*");
}
else if (key.getCode() == KeyCode.DIVIDE) {
operationButton("/");
}
else if (key.getCode() == KeyCode.EQUALS) {
try {
calculate();
} catch(Exception e1) {
System.out.println("Error in code.");
}
}
else if (key.getCode() == KeyCode.C) {
clearButton();
}
});
scene.getStylesheets().add("practice3.css");
equation.getStyleClass().add("equation-label");
//End
window.setScene(scene);
window.show();
}
private void clearButton() {
input = "";
total = 0;
num1 = 0;
equationInput = "";
display.setText("0");
equation.setText("");
}
private void numberButton(String value) {
input += value;
display.setText(input);
}
private void decimalButton() {
int check;
if (input.indexOf(".") == -1) {
if (input == "") {
input += "0.";
display.setText(input);
}
else {
input += ".";
display.setText(input);
}
}
}
private void operationButton(String symbol) {
equationInput += input;
input = "";
if (symbol == "+") {
equationInput += " + ";
}
else if (symbol == "-") {
equationInput += " - ";
}
else if (symbol == "*") {
equationInput += " * ";
}
else if (symbol == "/") {
equationInput += " / ";
}
equation.setText(equationInput);
display.setText("0");
}
private void calculate() throws Exception {
String answer = "0";
double answer1;
Object eval;
equationInput += input;
input = "";
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
eval = engine.eval(equationInput);
answer1 = new BigDecimal(eval.toString()).doubleValue();
answer = String.valueOf(answer1);
equationInput += " = ";
display.setText(answer);
equation.setText(equationInput);
}
}
Also, I would like to mention that I'm not very good at organization yet so if anything seems confusing feel free to ask!

Run-time error for GUI calculator in Java

I'm creating a GUI calculator, using FlowLayout, GridLayout and BorderLayout. I have the following code.
import java.awt.*;
import javax.swing.*;
//Imports visual components for program
import java.awt.event.*;
//Imports functions for providing performing action on object
public class Calc extends JFrame implements ActionListener {
JPanel[] row = new JPanel[5];
//5 panels are created for 5 rows of buttons
JButton[] button = new JButton[19];
String[] buttonString = {"1","2","3","+","4","5","6","-",
"7","8","9","*",".","/","C","rt","%",
"=", "0"};
double[] temporary = {0,0};
//Two memory locations for current number and upcoming number for signs such as *,/,%,+,-
boolean[] sign = new boolean[5];
//5 values for +,-,*,/,% are stored in array because they expect another number upon invocation
JTextArea display = new JTextArea(1,10);
//Creates display with location specified
Calc(){
//Constructor begins here
setResizable(false);
//Sets calculator size to be fixed at 380x250
//5x5 is created and selected for the calculator
for(int a = 0; a < 5; a++)
sign[a] = false;
//Initialises the state of the signs for +,-,*,/,%
JPanel displaypanel = new JPanel();
JPanel first = new JPanel();
JPanel last = new JPanel();
//Create three panels for buttons to be placed in
displaypanel.setLayout(new FlowLayout());
displaypanel.add(display);
//Display is added
first.setLayout(new GridLayout(3,5));
for(int a = 0; a<15; a++)
first.add(button[a]);
//"first" panel is added
last.setLayout(new GridLayout(1,4));
last.add(button[15]);
last.add(button[16]);
last.add(button[17]);
last.add(button[18]);
JFrame window = new JFrame("Task twelve");
window.setLayout(new BorderLayout());
window.add(displaypanel, BorderLayout.PAGE_START);
window.add(first, BorderLayout.CENTER);
window.add(last, BorderLayout.PAGE_END);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 400);
for(int a = 0; a < 19; a++){
button[a] = new JButton();
button[a].setText(buttonString[a]);
button[a].addActionListener(this);
//Assigns all the numbers and signs for the buttons
}
for(int a = 0; a < 5; a++)
row[a] = new JPanel();
//Initialises JPanel for rows so they can be used
//Assigns size for all buttons and display
display.setEditable(false);
}
public void clear(){
try{
display.setText("");
//Sets the display to be blank
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false
temporary[0] = 0;
temporary[1] = 0;
//Sets temporary values to be 0 as well
} catch(NullPointerException e){
}
}
public void root(){
try{
double temp = Math.sqrt(Double.parseDouble(display.getText()));
//Creates variable that converts the value in display to a double and Sqroots the value
display.setText(Double.toString(temp));
//Converts value in temp to string and copies it to display
} catch(NullPointerException e){
}
}
public void getResult() {
double result = 0;
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp2 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp2[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp3 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp3[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(sign[0] == true)
//Addition sign
result = temporary[0] + temporary[1];
else if(sign[1] == true)
//Subtraction sign
result = temporary[0] - temporary[1];
else if(sign[2] == true)
//Multiplication sign
result = temporary[0] * temporary[1];
else if(sign[3] == true)
//Division sign
result = temporary[0] / temporary[1];
else if(sign[4] == true)
//Modulus sign
result = temporary[0] % temporary[1];
display.setText(Double.toString(result));
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false after one of them has been invoked
} catch(NumberFormatException e) {
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == button[0])
display.append("1");
//When "1" is pressed, "1" is inserted to the display
if(ae.getSource() == button[1])
display.append("2");
if(ae.getSource() == button[2])
display.append("3");
if(ae.getSource() == button[3]){
//Addition sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5])
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]){
//Subtraction sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("7");
if(ae.getSource() == button[9])
display.append("8");
if(ae.getSource() == button[10])
display.append("9");
if(ae.getSource() == button[11]){
//Multiplication sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]){
//Division sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
root();
if(ae.getSource() == button[16]){
//Modulus sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[4] = true;
display.setText("");
}
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}
public static void main(String[] args){
Calc c = new Calc();
}
}
Compiling this doesn't result in any errors. However, running the class does.
Exception in thread"main" java.lang.NullPointerException
at java.awt.Container.addlmpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Calc.<init>(Calc.java:43)
at Calc.main(Calc.java:198)
I don't understand these errors so I do not know how to fix this. Can anyone help?
You are creating 15 buttons in the loop button[a] = new JButton(buttonString[a]); but then you are asking for button[15, 16, ...] (the 16nth, 17nth... button you have not created) and are null.

What's wrong with this Java Applet code? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to run this code in java applet via appletviewer in Fedora 18. But I get this error
java.lang.NullPointerException
at main.init(main.java:42)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:722)
As per my code 42nd line in my code is bMul.setBounds(100, 280, 50, 50); but this isn't wrong as-far-as i know. After searching on Google, I found that
NullPointerException is a runtime Exception thrown by the JVM when
your application code, other referenced API(s) or middleware
(Weblogic, WAS, JBoss...) encounters the following conditions:
Attempting to invoke an instance method of a null object
Attempting to access or modify a particular field of a null object
Attempting to obtain the length of such null object as an array
I've tried hard but failed in making it work. Please help me. Here I provide main.java file's code.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class main extends Applet implements ActionListener {
Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;
Button bAdd, bSub, bMul, bDiv, bEqu, bCls, bDec, bSqrt, bSin, bCos, bTan;
TextField tf1;
int add, sub, mul, div, temp = 0;
double sqr, s, c, ta;
String t = "";
public void init() {
setLayout(null);
setFont(new Font("cantarell", Font.BOLD, 12));
b0 = new Button("0"); b1 = new Button("1");
b2 = new Button("2"); b3 = new Button("3");
b4 = new Button("4"); b5 = new Button("5");
b6 = new Button("6"); b7 = new Button("7");
b8 = new Button("8"); b9 = new Button("9");
bAdd = new Button("+"); bSub = new Button("-");
bSub = new Button("*"); bDiv = new Button("/");
bEqu = new Button("="); bSqrt = new Button("sqrt");
bSin = new Button("sin"); bCos = new Button("cos");
bTan = new Button("tan"); bCls = new Button("cls");
tf1 = new TextField("0");
tf1.setEditable(false);
tf1.setColumns(8);
tf1.setBounds(100, 100, 250, 50);
b0.setBounds(100, 130, 50, 50);
b1.setBounds(150, 130, 50, 50);
b2.setBounds(200, 130, 50, 50);
b3.setBounds(250, 130, 50, 50);
b4.setBounds(100, 180, 50, 50);
b5.setBounds(150, 180, 50, 50);
b6.setBounds(200, 180, 50, 50);
b7.setBounds(250, 180, 50, 50);
b8.setBounds(100, 230, 50, 50);
b3.setBounds(150, 230, 50, 50);
bAdd.setBounds(200, 230, 50, 50);
bSub.setBounds(250, 230, 50, 50);
bMul.setBounds(100, 280, 50, 50);
bDiv.setBounds(150, 280, 50, 50);
bEqu.setBounds(200, 280, 50, 50);
bSin.setBounds(300, 130, 50, 50);
bCos.setBounds(300, 180, 50, 50);
bTan.setBounds(300, 230, 50, 50);
bSqrt.setBounds(250, 280, 50, 50);
bCls.setBounds(300, 280, 50, 50);
add(b0); add(b1); add(b2);
add(b3); add(b4); add(b5);
add(b6); add(b7); add(b8); add(b9);
add(bAdd); add(bSub); add(bMul); add(bDiv);
add(bEqu); add(bSin); add(bCos); add(bTan);
add(bSqrt); add(bCls); add(tf1);
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);
bSub.addActionListener(this);
bMul.addActionListener(this);
bDiv.addActionListener(this);
bEqu.addActionListener(this);
bSqrt.addActionListener(this);
bSin.addActionListener(this);
bCos.addActionListener(this);
bTan.addActionListener(this);
bCls.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == b0) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b0.getLabel());
else
tf1.setText(tf1.getText()+b0.getLabel());
temp = 0;
}
if(ae.getSource() == b1) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b1.getLabel());
else
tf1.setText(tf1.getText()+b1.getLabel());
temp = 0;
}
if(ae.getSource() == b2) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b2.getLabel());
else
tf1.setText(tf1.getText()+b2.getLabel());
temp = 0;
}
if(ae.getSource() == b3) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b3.getLabel());
else
tf1.setText(tf1.getText()+b3.getLabel());
temp = 0;
}
if(ae.getSource() == b4) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b4.getLabel());
else
tf1.setText(tf1.getText()+b4.getLabel());
temp = 0;
}
if(ae.getSource() == b5) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b5.getLabel());
else
tf1.setText(tf1.getText()+b5.getLabel());
temp = 0;
}
if(ae.getSource() == b6) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b6.getLabel());
else
tf1.setText(tf1.getText()+b6.getLabel());
temp = 0;
}
if(ae.getSource() == b7) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b7.getLabel());
else
tf1.setText(tf1.getText()+b7.getLabel());
temp = 0;
}
if(ae.getSource() == b8) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b8.getLabel());
else
tf1.setText(tf1.getText()+b8.getLabel());
temp = 0;
}
if(ae.getSource() == b9) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b9.getLabel());
else
tf1.setText(tf1.getText()+b9.getLabel());
temp = 0;
}
if(ae.getSource() == bSqrt) {
sqr = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.sqrt(sqr)));
}
if(ae.getSource() == bSin) {
s = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.sin(s)));
}
if(ae.getSource() == bCos) {
c = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.cos(c)));
}
if(ae.getSource() == bTan) {
ta = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.tan(ta)));
}
if(ae.getSource() == bAdd) {
add = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "+";
}
if(ae.getSource() == bSub) {
sub = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "-";
}
if(ae.getSource() == bMul) {
mul = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "*";
}
if(ae.getSource() == bDiv) {
div = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "/";
}
if(ae.getSource() == bEqu) {
if(t == "+") {
int add1 = Integer.parseInt(tf1.getText());
int add2 = add + add1;
tf1.setText(String.valueOf(add2));
}
else if(t == "-") {
int sub1 = Integer.parseInt(tf1.getText());
int sub2 = sub - sub1;
tf1.setText(String.valueOf(sub2));
}
else if(t == "*") {
int mul1 = Integer.parseInt(tf1.getText());
int mul2 = mul * mul1;
tf1.setText(String.valueOf(mul2));
}
else if(t == "/") {
int div1 = Integer.parseInt(tf1.getText());
int div2 = div / div1;
tf1.setText(String.valueOf(div2));
}
if(temp == 0) temp = 1;
}
if(ae.getSource() == bCls)
tf1.setText("0");
if(ae.getSource() == bDec) {
String s = tf1.getText();
for(int i = 0; i < s.length(); i++) {
if((s.charAt(i)) == '.') break;
else tf1.setText(tf1.getText()+bDec.getLabel());
}
}
}
void zero() {
if(temp == 1) tf1.setText("0");
}
}
Look at these lines:
bAdd = new Button("+"); bSub = new Button("-");
bSub = new Button("*"); bDiv = new Button("/");
You're assigning a value to bSub twice, but not assigning any value to bMul, so it's still null.
When you then dereference bMul at line 42:
bMul.setBounds(100, 280, 50, 50);
... that's throwing a NullPointerException. I suspect the start of the second line from above should be:
bMul = new Button("*");
I would strongly advise you to stick to one statement per line. I'd also advise you to break your code up into smaller chunks - for example, one method to initialize the digits, another for the operators etc.
You didn't created the bMul object .
Just add this line bMul=new Button("*");
You didn't initialize bMul!! Thus you are referencing a null object and throw the exception

Categories

Resources