Creating a calculator using JFrame - java

I am a beginner at using Java. I am trying to create a calculator using JFrame through Net beans IDE. When I run the program the build is successful but the GUI display of the calculator is blank. I made sure I put the set visible code but it is still displaying a blank calculator. What could be the problem?
Here is a copy of the code:
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Calculator();
}
});
//TODO code application logic here
}
JPanel[] row = new JPanel[5];
JButton[] button = new JButton[19];
String[] buttonString = {"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
".", "/", "C","Sqrt",
"+/-", "=", "0"};
int[] dimW = {300,45,100,90};
int[] dimH = {35, 40};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
boolean[] function = new boolean[4];
double[] temporary = {0, 0};
JTextArea display = new JTextArea(1,20);
Font font = new Font("Times new Roman", Font.BOLD, 12);
Calculator(){
super("Calculator");
setDesign();
setSize(400, 400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout (5,5);
setLayout(grid);
setVisible(true);
for(int i = 0; i < 19; i++)
function[i] = false;
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);
for(int i = 0; i < 5; i++)
row[i] = new JPanel();
row[0].setLayout(f1);
for(int i = 1; i < 5; i++)
row[i].setLayout(f2);
for(int i = 0; i < 19; i++){
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 14; i++)
button[i].setPreferredSize(regularDimension);
for(int i = 14; i < 18; i++)
button[i].setPreferredSize(rColumnDimension);
button[18].setPreferredSize(zeroButDimension);
row[0].add(display);
add(row[0]);
for(int i = 0; i < 4; i++)
row[1].add(button[i]);
row[1].add(button[14]);
add(row[1]);
for(int i = 4; i < 8; i++)
row[2].add(button[i]);
row[2].add(button[15]);
add(row[2]);
for(int i = 8; i < 12; i++)
row[3].add(button[i]);
row[3].add(button[16]);
add(row[3]);
row[4].add(button[18]);
for(int i = 12; i < 14; i++)
row[4].add(button[i]);
row[4].add(button[17]);
add(row[4]);
}
public void clear() {
try {
display.setText("");
for (int i = 0; i < 4; i++)
function[i] = false;
for(int i = 0; i < 2; i++)
temporary[i] = 0;
} catch(NullPointerException e) {
}
}
public void getSqrt() {
try {
double value = Math.sqrt(Double.parseDouble(display.getText()));
display.setText(Double.toString(value));
}
catch(NumberFormatException e) {
}
}
public void getPosNeg() {
try {
double value = Double.parseDouble(display.getText());
if(value !=0) {
value = value * (-1);
display.setText(Double.toString(value));
}
else {
}
} catch(NumberFormatException 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[] temp00 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp00[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp11 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp11[1]) * -1);
}
}
catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(function[2] == true)
result = temporary[0] * temporary[1];
else if(function[3] == true)
result = temporary[0] / temporary[1];
else if(function[0] == true)
result = temporary[0] + temporary[1];
else if(function[1] == true)
result = temporary[0] - temporary[1];
display.setText(Double.toString(result));
for(int i = 0; i < 4; i++)
function[i] = false;
}
catch(NumberFormatException e) {
}
}
public final void setDesign(){
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0])
display.append("7");
if(ae.getSource() == button[1])
display.append("8");
if(ae.getSource() == button[2])
display.append("9");
if(ae.getSource() == button[3]) {
temporary[0] = Double.parseDouble(display.getText());
function[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]) {
temporary[0] = Double.parseDouble(display.getText());
function[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("1");
if(ae.getSource() == button[9]);
display.append("2");
if(ae.getSource() == button[10]);
display.append("3");
if(ae.getSource() == button[11]) {
temporary[0] = Double.parseDouble(display.getText());
function[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]) {
temporary[0] = Double.parseDouble(display.getText());
function[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
getSqrt();
if(ae.getSource() == button[16])
getPosNeg();
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}

Related

How can I make a button to keep displaying an image for a certain condition in JavaFx?

I am trying to make a memory game in javaFx and it works fine, it tells you when you find two pictures that are the same but how can I make it keep displaying the pictures that match throughout the whole game? because the pictures hide when you don't match and if you matched. I couldn't figure out a way to make the button keep on displaying the picture after you get a match.
public void start(Stage primaryStage) {
ArrayList<String> list = new ArrayList<>();
int userInput = 4;
imageWithLoc = new String[userInput][userInput];
btnArr = new Button[userInput][userInput];
int targetNum = ((userInput * userInput) / 2);
int count = 0;
int count2 = 0;
while (count < targetNum) {
int numC = (int) (Math.random() * userInput);
int numR = (int) (Math.random() * userInput);
if (imageWithLoc[numC][numR] == null) {
if (!list.contains(images[count])) {
imageWithLoc[numC][numR] = images[count];
list.add(images[count]);
count++;
}
}
}
for (int i = 0; i < userInput; i++) {
for (int j = 0; j < userInput; j++) {
if (imageWithLoc[i][j] == null) {
imageWithLoc[i][j] = images[count2];
count2++;
}
}
}
for (int i = 0; i < userInput; i++) {
for (int j = 0; j < userInput; j++) {
System.out.println(imageWithLoc[i][j] + " ");
}
}
for (int i = 0; i < userInput; i++) {
for (int j = 0; j < userInput; j++) {
Button btn = new Button();
btn.setPrefSize(250, 250);
btnArr[i][j] = btn;
Image img1 = new Image(imageWithLoc[i][j], 250, 250, true, true);
String strImg = imageWithLoc[i][j];
btn.setOnAction(e -> {
ImageView iv1 = new ImageView();
iv1.setImage(img1);
btn.setGraphic(iv1);
if (firstImg == null) {
firstImg = strImg;
firstBtn = btn;
} else if (secondImg == null) {
secondImg = strImg;
secondBtn = btn;
} else if (firstImg != null && secondImg != null) {
firstImg = strImg;
secondImg = null;
secondBtn.setGraphic(null);
firstBtn.setGraphic(null);
firstBtn = btn;
secondBtn = null;
}
if (firstImg.equals(secondImg)) {
System.out.println("match");
}
});
btnGp.add(btn, j, i);
btnGp.setHgap(10);
btnGp.setVgap(10);
btnGp.setPadding(new Insets(10, 10, 10, 10));
}
}
bp.setCenter(btnGp);
Scene scene = new Scene(bp, 1000, 1000);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Java Calculator ActionListener. How to change the message "Infinity" when dividing by zero?

I am a student at Uni and having an assignment for Programming. We have to make a Calculator using java and one of the points is to type a message "Not a number" when the user divides by zero. Normally, it shows "Infinity", so the task is to change that message, however I didn't go so far to understand how to do it. If anyone has an idea or can help me rewrite it, please comment here. Thank you!
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(function[2] == true)
result = temporary[0] * temporary[1];
else if(function[3] == true)
result = temporary[0] / temporary[1];
else if(function[0] == true)
result = temporary[0] + temporary [1];
else if(function[1] == true)
result = temporary[0] - temporary[1];
display.setText(Double.toString(result));
for(int i=0; i<4; i++)
function[i] = false;
} catch(NumberFormatException e) {}
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0])
display.append("1");
if(ae.getSource() == button[1])
display.append("2");
if(ae.getSource() == button[2])
display.append("3");
if(ae.getSource() == button[3]) {
temporary[0] = Double.parseDouble(display.getText());
function[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]) {
temporary[0] = Double.parseDouble(display.getText());
function[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]) {
temporary[0] = Double.parseDouble(display.getText());
function[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append("0");
if(ae.getSource() == button[13])
display.append(".");
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15]){
temporary[0] = Double.parseDouble(display.getText());
function[3] = true;
display.setText("");
}
if(ae.getSource() == button[16])
getResult();
}
public static void main(String[] arguments) {
Calculator c = new Calculator();
}
}
As you know divide by zero is infinity. In java there is no error if you divide by zero for primitive wrapper classes. For example
public static void main(String[] args) {
Double a = 1.0;
Double b = 0.0;
Double c = a/b;
c.isInfinite();
System.out.println(c.toString());
}
prints:
Infinity
SO, just change result form double to Double and:
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 (function[2] == true)
result = temporary[0] * temporary[1];
else if (function[3] == true)
result = temporary[0] / temporary[1];
else if (function[0] == true)
result = temporary[0] + temporary[1];
else if (function[1] == true)
result = temporary[0] - temporary[1];
if(c.isInfinite() || c.isNaN()) {
display.setText("Not a number");
} else {
display.setText(result.toString());
}
for (int i = 0; i < 4; i++)
function[i] = false;
} catch (NumberFormatException e) {
display.setText(e.getMessage());
}
}

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.

How do I add the Timer of the game?

My friends and i are creating a gme like bejeweled. it is almost over, but we have some problems. We couldn't add Timer to game. for example, we want to that level 1 finished after 2 minutes. How can we do?
//in this class, we created game area etc.
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class Level1 extends JFrame {
private JPanel anaPanel, p1;
private JPanel grid;
public String comand;
public static JButton[] buttons;
public String imgName;
public Color c1, c2;
public String score=ButtonActionListener.str;
public Level1() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x= ((dim.width-960)/2);
int y= ((dim.height-640)/2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(x, y, 960,640);
anaPanel = new JPanel();
anaPanel.setLayout(new GridLayout(1,2));
p1=new JPanel();
JLabel background = new JLabel(new ImageIcon("img//sol.png"));
c1 = new Color(21,120,227);
c2 = new Color(250,215,1);
grid=new JPanel();
grid.setLayout(new GridLayout(8,8,5,5));
grid.setBounds(5, 5, 460, 640);
buttons = new JButton[64];
//Creating random image for buttons
ActionListener buttonActionListener = new ButtonActionListener();
for (int i = 0; i<buttons.length; i++) {
Random r = new Random();
int a = r.nextInt(7)+1;
switch(a){
case 1 : buttons[i]=new JButton(new ImageIcon("img//Cakal.png"));
break;
case 2 : buttons[i]=new JButton(new ImageIcon("img//BugsBunny.png"));
break;
case 3 : buttons[i]=new JButton(new ImageIcon("img//Pig.png"));
break;
case 4 : buttons[i]=new JButton(new ImageIcon("img//Taz.png"));
break;
case 5 : buttons[i]=new JButton(new ImageIcon("img//Sam.png"));
break;
case 6 : buttons[i]=new JButton(new ImageIcon("img//DuffyDuck.png"));
break;
case 7 : buttons[i]=new JButton(new ImageIcon("img//Tweety.png"));
break;
/*case 8 : buttons[i]=new JButton(new ImageIcon("img//Slyvester.png"));
break;
case 9 : buttons[i]=new JButton(new ImageIcon("img//RoadRunner.png"));
break;*/
}
buttons[i].setBorder(BorderFactory.createEmptyBorder());
buttons[i].setContentAreaFilled(false);
buttons[i].setFocusable(true);
buttons[i].setOpaque(true);
buttons[i].setBackground(c1);
//Adding number to find easily
comand=Integer.toString(i);
//Get ImageIcon name
imgName=((ImageIcon)buttons[i].getIcon()).toString();
buttons[i].addActionListener(buttonActionListener);
buttons[i].setActionCommand(comand);
grid.add(buttons[i]);
}
grid.setBackground(c1);
p1.add(background);
p1.setBackground(c1);
anaPanel.add(p1);
anaPanel.add(grid);
add(anaPanel);
}
static JButton[] getButton(){
return buttons;
}
public static void main(String[] args){
Level1 l=new Level1();
l.setVisible(true);
}
}
In this class, there are algorithms of game.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class ButtonActionListener implements ActionListener {
public JButton previousButton = null;
public int numP, numC;
public JButton[] buttons=Level1.getButton();
public int score=0;
public static String str;
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
JButton currentButton = (JButton)e.getSource();
if (previousButton == null) {
previousButton = currentButton;
return;
}
int numP=Integer.parseInt(((JButton)previousButton).getActionCommand());
int numC=Integer.parseInt(((JButton)currentButton).getActionCommand());
if (numP==(numC+1) || numP==(numC-1) || numP==(numC+8) || numP==(numC-8) ){
Icon previousIcon = previousButton.getIcon();
Icon currentIcon = currentButton.getIcon();
currentButton.setIcon(previousIcon);
previousButton.setIcon(currentIcon);
previousButton = null;
}
else
previousButton=null;
startAnimation();
}
private void startAnimation()
{
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
runAnimation();
}
});
t.start();
}
private int a;
private int b;
private int c;
private int d;
private int e;
private void runAnimation()
{
Random r = new Random();
a = r.nextInt(64);
b = r.nextInt(64);
c = r.nextInt(64);
d = r.nextInt(64);
e = r.nextInt(64);
for(int i=0; i<63; i++)
{
final int iFinal = i;
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
doAnimationStep(iFinal);
}
});
try
{
Thread.sleep(30);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return;
}
}
}
private void doAnimationStep(int i)
{
String s0 = buttons[i].getIcon().toString();
String s1 = buttons[i+1].getIcon().toString();
String s2 = buttons[i+2].getIcon().toString();
String s3 = buttons[i+3].getIcon().toString();
String s4 = buttons[i+4].getIcon().toString();
if(s0.equals(s1) && s1.equals(s2) && s2.equals(s3) && s3.equals(s4)){
if(i > 7){
for(int j = i; j > 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[j-8].getIcon());
buttons[j+1].setIcon(buttons[j-7].getIcon());
buttons[j+2].setIcon(buttons[j-6].getIcon());
buttons[j+3].setIcon(buttons[j-5].getIcon());
buttons[j+4].setIcon(buttons[j-4].getIcon());
score+=100;
str=String.valueOf(score);
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+1].setIcon(buttons[b].getIcon());
buttons[j+2].setIcon(buttons[c].getIcon());
buttons[j+3].setIcon(buttons[d].getIcon());
buttons[j+4].setIcon(buttons[e].getIcon());
score+=100;
str=String.valueOf(score);
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+1].setIcon(buttons[b].getIcon());
buttons[i+2].setIcon(buttons[c].getIcon());
buttons[i+3].setIcon(buttons[d].getIcon());
buttons[i+4].setIcon(buttons[e].getIcon());
score+=100;
str=String.valueOf(score);
}
}else{
if(s0.equals(s1) && s1.equals(s2) && s2.equals(s3)){
if(i > 7){
for(int j = i; j > 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[j-8].getIcon());
buttons[j+1].setIcon(buttons[j-7].getIcon());
buttons[j+2].setIcon(buttons[j-6].getIcon());
buttons[j+3].setIcon(buttons[j-5].getIcon());
score+=100;
str=String.valueOf(score);
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+1].setIcon(buttons[b].getIcon());
buttons[j+2].setIcon(buttons[c].getIcon());
buttons[j+3].setIcon(buttons[d].getIcon());
score+=100;
str=String.valueOf(score);
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+1].setIcon(buttons[b].getIcon());
buttons[i+2].setIcon(buttons[c].getIcon());
buttons[i+3].setIcon(buttons[d].getIcon());
score+=100;
str=String.valueOf(score);
}
}else{
if(s0.equals(s1) && s1.equals(s2))
{
if(i > 7){
for(int j = i; j > 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[j-8].getIcon());
buttons[j+1].setIcon(buttons[j-7].getIcon());
buttons[j+2].setIcon(buttons[j-6].getIcon());
score+=100;
str=String.valueOf(score);
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+1].setIcon(buttons[b].getIcon());
buttons[j+2].setIcon(buttons[c].getIcon());
score+=100;
str=String.valueOf(score);
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+1].setIcon(buttons[b].getIcon());
buttons[i+2].setIcon(buttons[c].getIcon());
score+=100;
str=String.valueOf(score);
}
}
if(i < 48){
String v0 = buttons[i].getIcon().toString();
String v1 = buttons[i+8].getIcon().toString();
String v2 = buttons[i+16].getIcon().toString();
if(v0.equals(v1) && v1.equals(v2)) {
if(i > 23){
for(int j = i; j >= 0; j=j-8){
if(j > 23){
buttons[j].setIcon(buttons[j-24].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
score+=100;
str=String.valueOf(score);
}
else if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
score+=100;
str=String.valueOf(score);
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 15){
for(int j = i; j >= 0; j=j-8){
if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 7){
for(int j = i; j >= 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+8].setIcon(buttons[b].getIcon());
buttons[i+16].setIcon(buttons[c].getIcon());
}
}
}else{
String v0 = buttons[i-16].getIcon().toString();
String v1 = buttons[i-8].getIcon().toString();
String v2 = buttons[i].getIcon().toString();
if(v0.equals(v1) && v1.equals(v2)) {
if(i > 23){
for(int j = i; j >= 0; j=j-8){
if(j > 23){
buttons[j].setIcon(buttons[j-24].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 15){
for(int j = i; j >= 0; j=j-8){
if(j > 15){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[j-16].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else if(i > 7){
for(int j = i; j >= 0; j=j-8){
if(j > 7){
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[j-8].getIcon());
}
else{
buttons[j].setIcon(buttons[a].getIcon());
buttons[j+8].setIcon(buttons[b].getIcon());
buttons[j+16].setIcon(buttons[c].getIcon());
}
}
}
else{
buttons[i].setIcon(buttons[a].getIcon());
buttons[i+8].setIcon(buttons[b].getIcon());
buttons[i+16].setIcon(buttons[c].getIcon());
}
}
}
}
}
}
public String getScore(){
return str;
}
}
Have a look into swing timers.
It's easy to implement and should be enough for your purpose.
You could make it count down the time for user, and at the end, stop the level (let the player retry etc.).
Hope this helps.
You can use the Timer class with it's schedule() method.
On callback simple call the methods to "end your level".
You could do something like this:
int counter = 0;
for (int j = 0 ; j <60 ; j++)
{
delayer (1000);
counter++;
}
if (counter == 60)
{
// put what you want to happen after 60 seconds here
}
and then have a delayer method:
private static void delayer (long milliseconds)
{
try
{
Thread.sleep (1000);
}
catch (InterruptedException ex)
{
}
}

Calculator How to make a calculator that can do multiple operations

I created a calculator that can make simple calculations like 9+8 = 17 or 10*3 = 30 But I would like to make one that can do multiple operations like 9*5/2 or 9*5 *6 etc..
here is my code :
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==zero){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("0");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"0");
}
}
}
else if(e.getSource()==one){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("1");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"1");
}
}
}
else if(e.getSource()==two){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("2");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"2");
}
}
}
else if(e.getSource()==three){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("3");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"3");
}
}
}
else if(e.getSource()==four){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("4");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"4");
}
}
}
else if(e.getSource()==five){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("5");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"5");
}
}
}
else if(e.getSource()==six){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("6");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"6");
}
}
}
else if(e.getSource()==seven){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("7");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"7");
}
}
}
else if(e.getSource()==eight){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("8");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"8");
}
}
}
else if(e.getSource()==nine){
if(answerField.getText().length()<16){
if(clearField ==1){
answerField.setText("9");
clearField = 0;
}
else{
answerField.setText(answerField.getText()+"9");
}
}
}
else if(e.getSource()== negativePositive){
if(answerField.getText().equals("")||answerField.getText().equals("-")){
answerField.setText("-");
}
else{
negativePositive1 = (Double.parseDouble(String.valueOf(answerField.getText())));
negativePositive1 *= -1;
answerField.setText(String.valueOf(negativePositive1));
}
}
else if(e.getSource()==clear){
answerField.setText("");
num1 = 0;
num2 = 0;
addClick = 0;
subClick = 0;
divClick = 0;
multiClick = 0;
}
else if(e.getSource()==decimal){
if(answerField.getText().contains(".")){
answerField.setText(answerField.getText());
}
else{
answerField.setText(answerField.getText()+".");
}
}
else if(e.getSource()==add){
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
addClick = 1;
clearField = 1;
}
}
else if(e.getSource()==Subtract){
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
subClick = 1;
clearField = 1;
}
}
else if(e.getSource()==multiply){
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
multiClick = 1;
clearField = 1;
}
}
else if(e.getSource()==divide){
if(answerField!=null){
answerField.setText(answerField.getText()+"/");
}
if(answerField.getText()!=null){
num1 = Double.parseDouble(String.valueOf(answerField.getText()));
divClick = 1;
clearField = 1;
}
}
else if(e.getSource()==equal){
num2 = Double.parseDouble(String.valueOf(answerField.getText()));
answerField.setText(answerField.getText());
if(addClick ==1){
ans = num1+num2;
answerField.setText(String.valueOf(ans));
addClick = 0;
}
if(subClick ==1){
ans = num1-num2;
answerField.setText(String.valueOf(ans));
subClick = 0;
}
if(multiClick ==1){
ans = num1*num2;
answerField.setText(String.valueOf(ans));
multiClick = 0;
}
if(divClick ==1){
ans = Num1/Num2;
answerField.setText(String.valueOf(ans));
divClick = 0;
}
}
}
Anyone know how I would approach this? I know I am missing something
Consider this example you have 3 buttons: add, substract and equals
private int number = 0;
private void setNumber(int no){
this.number = no;
}
private Integer getNumber(){
return this.number;
}
private void addActionPerformed(java.awt.event.ActionEvent evt) {
int i = 1;
int newAddedNumber = this.number + i;
setNumber(newAddedNumber);
}
private void substractActionPerformed(java.awt.event.ActionEvent evt) {
int i = 1;
int newSubtractedNumber = this.number - i;
setNumber(newSubstractedNumber);
}
private void equalsActionPerformed(java.awt.event.ActionEvent evt) {
int displayCurrentNo = getNumber();
System.out.println("current Number is : " + displayCurrentNo)
}
What this should do is just add or remove 1 from current number.
Its only example and may not be necessary compile-able but this should give you an idea.

Categories

Resources