Notes
![]() ![]() Notes - notes.io |
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 "plastic" look
display = new JTextField("0");
display.setEditable(false);
display.setHorizontalAlignment(SwingConstants.RIGHT);
display.setFont(new Font("Arial", Font.BOLD, 30));
display.setBackground(new Color(240, 240, 240));
display.setBorder(BorderFactory.createLineBorder(new Color(160, 160, 160), 5)); // Simulate depth
display.setPreferredSize(new Dimension(400, 70));
display.setMargin(new Insets(10, 10, 10, 10));
// 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
String[] buttons = {
"7", "8", "9", "÷",
"4", "5", "6", "×",
"1", "2", "3", "-",
"0", "00", ".", "+",
"C", "Del", "√", "^",
"log", "ln", "%", "="
};
// Create and style buttons with realistic "plastic" effect
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 20));
button.setFocusPainted(false);
button.setForeground(Color.WHITE);
button.setBorder(BorderFactory.createLineBorder(new Color(150, 150, 150), 2)); // Border to simulate depth
// Button colors based on type
if (text.matches("[0-9]") || text.equals(".")) {
button.setBackground(new Color(70, 70, 70)); // Dark buttons for numbers
}
else if ("÷×-+^√logln%".contains(text)) {
button.setBackground(new Color(240, 128, 128)); // Operators with a soft red tone
}
else if (text.equals("=")) {
button.setBackground(new Color(255, 165, 0)); // Orange for the "=" button
}
else if (text.equals("C") || text.equals("Del")) {
button.setBackground(new Color(220, 20, 60)); // Dark red for "C" and "Del"
}
else if (text.equals("00")) {
button.setBackground(new Color(80, 80, 80)); // Darker button for "00"
}
button.setPreferredSize(new Dimension(80, 80));
button.setMargin(new Insets(10, 10, 10, 10)); // Spacing for button text
button.setFont(new Font("Arial", Font.BOLD, 24));
button.addActionListener(this);
buttonPanel.add(button);
}
// Outer border for the frame (plastic effect)
JPanel outerPanel = new JPanel();
outerPanel.setLayout(new BorderLayout());
outerPanel.setBackground(new Color(245, 245, 245));
outerPanel.setBorder(BorderFactory.createLineBorder(new Color(160, 160, 160), 10)); // Outer border to simulate plastic body
outerPanel.add(display, BorderLayout.NORTH);
outerPanel.add(buttonPanel, BorderLayout.CENTER);
// Frame layout setup
setLayout(new BorderLayout(10, 10));
add(outerPanel, BorderLayout.CENTER);
// Frame properties
setTitle("Realistic Calculator");
setSize(450, 650); // Adjust size for the realistic look
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);
}
}
![]() |
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