NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;

public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private StringBuilder expression;

public Calculator() {
expression = new StringBuilder();

// Display field setup with gradient background
display = new JTextField("0");
display.setEditable(false);
display.setHorizontalAlignment(SwingConstants.RIGHT);
display.setFont(new Font("Roboto", Font.BOLD, 30));
display.setBackground(new Color(245, 245, 245));
display.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
display.setPreferredSize(new Dimension(400, 70));

// Button panel setup
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(6, 4, 10, 10));
buttonPanel.setBackground(new Color(245, 245, 245));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

// Button labels in desired layout order, without parentheses and with % and 00 buttons
String[] buttons = {
"7", "8", "9", "÷",
"4", "5", "6", "×",
"1", "2", "3", "-",
"0", "00", ".", "+",
"C", "Del", "√", "^",
"log", "ln", "%", "="
};

// Create and style buttons with rounded corners and custom fonts
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Roboto", Font.BOLD, 20));
button.setFocusPainted(false);
button.setForeground(Color.WHITE);
button.setBorder(BorderFactory.createLineBorder(new Color(50, 50, 50), 2, true)); // Rounded corners

// Style number and dot buttons
if (text.matches("[0-9]") || text.equals(".")) {
button.setBackground(new Color(70, 70, 70));
}
// Style operator buttons
else if ("÷×-+^√logln%".contains(text)) {
button.setBackground(new Color(240, 128, 128));
}
// Style "=" button
else if (text.equals("=")) {
button.setBackground(new Color(255, 165, 0));
}
// Style "C" and "Del" buttons
else if (text.equals("C") || text.equals("Del")) {
button.setBackground(new Color(220, 20, 60));
}
// Style "00" button to match number buttons
else if (text.equals("00")) {
button.setBackground(new Color(70, 70, 70));
}

// Add hover effect
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
button.setBackground(button.getBackground().darker());
}

public void mouseExited(java.awt.event.MouseEvent evt) {
button.setBackground(button.getBackground().brighter());
}
});

button.addActionListener(this);
buttonPanel.add(button);
}

// Frame layout setup with gradient background
setLayout(new BorderLayout(10, 10));
add(display, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);

// Frame properties
setTitle("Aesthetic Calculator");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if (command.matches("[0-9]")) {
if (display.getText().equals("0") || display.getText().equals("Error")) {
expression.setLength(0);
}
expression.append(command);
display.setText(expression.toString());
} else if (command.equals(".")) {
if (!display.getText().contains(".")) {
expression.append(command);
display.setText(expression.toString());
}
} else if (command.equals("C")) {
expression.setLength(0);
display.setText("0");
} else if (command.equals("Del")) {
if (expression.length() > 0) {
expression.deleteCharAt(expression.length() - 1);
display.setText(expression.length() > 0 ? expression.toString() : "0");
}
} else if (command.equals("=")) {
try {
double result = evaluateExpression(expression.toString());
display.setText(String.valueOf(result));
expression.setLength(0);
expression.append(result);
} catch (Exception ex) {
display.setText("Error");
expression.setLength(0);
}
} else if ("logln√^%".contains(command)) {
expression.append(" ").append(command).append(" ");
display.setText(expression.toString());
} else if (command.equals("00")) {
expression.append("00");
display.setText(expression.toString());
} else {
if (expression.length() > 0 && !isOperator(expression.charAt(expression.length() - 1))) {
expression.append(" ").append(command).append(" ");
display.setText(expression.toString());
}
}
}

private double evaluateExpression(String exp) throws Exception {
// Check for functions and handle them
if (exp.contains("log")) {
return Math.log10(parseArgument(exp, "log"));
} else if (exp.contains("ln")) {
return Math.log(parseArgument(exp, "ln"));
} else if (exp.contains("√")) {
return Math.sqrt(parseArgument(exp, "√"));
} else if (exp.contains("%")) {
return parsePercentage(exp);
} else {
Stack<Double> values = new Stack<>();
Stack<String> ops = new Stack<>();
String[] tokens = exp.split(" ");

for (String token : tokens) {
if (token.isEmpty()) continue;
if (token.matches("[0-9.]+")) {
values.push(Double.parseDouble(token));
} else if ("+-×÷^".contains(token)) {
while (!ops.isEmpty() && hasPrecedence(token, ops.peek())) {
values.push(applyOperation(ops.pop(), values.pop(), values.pop()));
}
ops.push(token);
}
}

while (!ops.isEmpty()) {
values.push(applyOperation(ops.pop(), values.pop(), values.pop()));
}

return values.pop();
}
}

private double parseArgument(String exp, String func) throws Exception {
int startIndex = exp.indexOf(func) + func.length();
String arg = exp.substring(startIndex).trim();
return Double.parseDouble(arg);
}

private double parsePercentage(String exp) {
String number = exp.replaceAll("[^0-9.]", "");
return Double.parseDouble(number) / 100;
}

private double applyOperation(String op, double b, double a) {
switch (op) {
case "+": return a + b;
case "-": return a - b;
case "×": return a * b;
case "÷":
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
case "^": return Math.pow(a, b);
}
return 0;
}

private boolean hasPrecedence(String op1, String op2) {
if (op2.equals("(") || op2.equals(")")) return false;
if ((op1.equals("×") || op1.equals("÷") || op1.equals("^")) && (op2.equals("+") || op2.equals("-"))) return false;
return true;
}

private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '×' || c == '÷' || c == '^';
}

public static void main(String[] args) {
SwingUtilities.invokeLater(Calculator::new);
}
}
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.