Selasa, 16 September 2025

JAVA - Calculator

 



package calculator;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Container;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.awt.Window;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;


import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JPanel;

import javax.swing.JTextArea;

import javax.swing.KeyStroke;


public class Calculator extends JFrame implements ActionListener{

// Variables

final int MAX_INPUT_LENGTH = 20;

final int INPUT_MODE = 0;

final int RESULT_MODE = 1;

final int ERROR_MODE = 2;

int displayMode;


boolean clearOnNextDigit, percent;

double lastNumber;

String lastOperator;


private JMenu jmenuFile, jmenuHelp;

private JMenuItem jmenuitemExit, jmenuitemAbout;

private JLabel jlbOutput;

private JButton jbnButtons[];

private JPanel jplMaster, jplBackSpace, jplControl;

/*

* Font(String name, int style, int size)

      Creates a new Font from the specified name, style and point size.

*/

Font f12 = new Font("Times New Roman", 0, 12);

Font f121 = new Font("Times New Roman", 1, 12);

// Constructor 

public Calculator() 

{

/* Set Up the JMenuBar.

* Have Provided All JMenu's with Mnemonics

* Have Provided some JMenuItem components with Keyboard Accelerators

*/ 

jmenuFile = new JMenu("File");

jmenuFile.setFont(f121);

jmenuFile.setMnemonic(KeyEvent.VK_F);

jmenuitemExit = new JMenuItem("Exit");

jmenuitemExit.setFont(f12);

jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X, 

ActionEvent.CTRL_MASK));

jmenuFile.add(jmenuitemExit);


jmenuHelp = new JMenu("Help");

jmenuHelp.setFont(f121);

jmenuHelp.setMnemonic(KeyEvent.VK_H);


jmenuitemAbout = new JMenuItem("About Calculator");

jmenuitemAbout.setFont(f12);

jmenuHelp.add(jmenuitemAbout);

JMenuBar mb = new JMenuBar();

mb.add(jmenuFile);

mb.add(jmenuHelp);

setJMenuBar(mb);

//Set frame layout manager


setBackground(Color.gray);


jplMaster = new JPanel();


jlbOutput = new JLabel("0");

jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);

jlbOutput.setBackground(Color.WHITE);

jlbOutput.setOpaque(true);

// Add components to frame

getContentPane().add(jlbOutput, BorderLayout.NORTH);


jbnButtons = new JButton[23];

// GridLayout(int rows, int cols, int hgap, int vgap) 


JPanel jplButtons = new JPanel(); // container for Jbuttons


// Create numeric Jbuttons

for (int i=0; i<=9; i++)

{

// set each Jbutton label to the value of index

jbnButtons[i] = new JButton(String.valueOf(i));

}


// Create operator Jbuttons

jbnButtons[10] = new JButton("+/-");

jbnButtons[11] = new JButton(".");

jbnButtons[12] = new JButton("=");

jbnButtons[13] = new JButton("/");

jbnButtons[14] = new JButton("*");

jbnButtons[15] = new JButton("-");

jbnButtons[16] = new JButton("+");

jbnButtons[17] = new JButton("sqrt");

jbnButtons[18] = new JButton("1/x");

jbnButtons[19] = new JButton("%");

jplBackSpace = new JPanel();

jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));


jbnButtons[20] = new JButton("Backspace");

jplBackSpace.add(jbnButtons[20]);


jplControl = new JPanel();

jplControl.setLayout(new GridLayout(1, 2, 2 ,2));


jbnButtons[21] = new JButton(" CE ");

jbnButtons[22] = new JButton("C");


jplControl.add(jbnButtons[21]);

jplControl.add(jbnButtons[22]);


// Setting all Numbered JButton's to Blue. The rest to Red

for (int i=0; i<jbnButtons.length; i++) {

jbnButtons[i].setFont(f12);


if (i<10)

jbnButtons[i].setForeground(Color.blue);

else

jbnButtons[i].setForeground(Color.red);

}

// Set panel layout manager for a 4 by 5 grid

jplButtons.setLayout(new GridLayout(4, 5, 2, 2));

//Add buttons to keypad panel starting at top left

// First row

for(int i=7; i<=9; i++) {

jplButtons.add(jbnButtons[i]);

}

// add button / and sqrt

jplButtons.add(jbnButtons[13]);

jplButtons.add(jbnButtons[17]);

// Second row

for(int i=4; i<=6; i++)

{

jplButtons.add(jbnButtons[i]);

}

// add button * and x^2

jplButtons.add(jbnButtons[14]);

jplButtons.add(jbnButtons[18]);


// Third row

for( int i=1; i<=3; i++)

{

jplButtons.add(jbnButtons[i]);

}

//adds button - and %

jplButtons.add(jbnButtons[15]);

jplButtons.add(jbnButtons[19]);

//Fourth Row

// add 0, +/-, ., +, and =

jplButtons.add(jbnButtons[0]);

jplButtons.add(jbnButtons[10]);

jplButtons.add(jbnButtons[11]);

jplButtons.add(jbnButtons[16]);

jplButtons.add(jbnButtons[12]);

jplMaster.setLayout(new BorderLayout());

jplMaster.add(jplBackSpace, BorderLayout.WEST);

jplMaster.add(jplControl, BorderLayout.EAST);

jplMaster.add(jplButtons, BorderLayout.SOUTH);


// Add components to frame

getContentPane().add(jplMaster, BorderLayout.SOUTH);

requestFocus();

//activate ActionListener

for (int i=0; i<jbnButtons.length; i++){

jbnButtons[i].addActionListener(this);

}

jmenuitemAbout.addActionListener(this);

jmenuitemExit.addActionListener(this);


clearAll();


//add WindowListener for closing frame and ending program

addWindowListener(new WindowAdapter() {


public void windowClosed(WindowEvent e)

{

System.exit(0);

}

}

);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} //End of Contructor Calculator


// Perform action

public void actionPerformed(ActionEvent e){

double result = 0;

   

if(e.getSource() == jmenuitemAbout){

JDialog dlgAbout = new CustomABOUTDialog(this, "About Java Swing Calculator", true);

dlgAbout.setVisible(true);

}else if(e.getSource() == jmenuitemExit){

System.exit(0);

}


// Search for the button pressed until end of array or key found

for (int i=0; i<jbnButtons.length; i++)

{

if(e.getSource() == jbnButtons[i])

{

switch(i)

{

case 0:

addDigitToDisplay(i);

break;


case 1:

addDigitToDisplay(i);

break;


case 2:

addDigitToDisplay(i);

break;


case 3:

addDigitToDisplay(i);

break;


case 4:

addDigitToDisplay(i);

break;


case 5:

addDigitToDisplay(i);

break;


case 6:

addDigitToDisplay(i);

break;


case 7:

addDigitToDisplay(i);

break;


case 8:

addDigitToDisplay(i);

break;


case 9:

addDigitToDisplay(i);

break;


case 10: // +/-

processSignChange();

break;


case 11: // decimal point

addDecimalPoint();

break;


case 12: // =

processEquals();

break;


case 13: // divide

processOperator("/");

break;


case 14: // *

processOperator("*");

break;


case 15: // -

processOperator("-");

break;


case 16: // +

processOperator("+");

break;


case 17: // sqrt

if (displayMode != ERROR_MODE)

{

try

{

if (getDisplayString().indexOf("-") == 0)

displayError("Invalid input for function!");


result = Math.sqrt(getNumberInDisplay());

displayResult(result);

}


catch(Exception ex)

{

displayError("Invalid input for function!");

displayMode = ERROR_MODE;

}

}

break;


case 18: // 1/x

if (displayMode != ERROR_MODE){

try

{

if (getNumberInDisplay() == 0)

displayError("Cannot divide by zero!");

result = 1 / getNumberInDisplay();

displayResult(result);

}

catch(Exception ex) {

displayError("Cannot divide by zero!");

displayMode = ERROR_MODE;

}

}

break;


case 19: // %

if (displayMode != ERROR_MODE){

try {

result = getNumberInDisplay() / 100;

displayResult(result);

}

catch(Exception ex) {

displayError("Invalid input for function!");

displayMode = ERROR_MODE;

}

}

break;


case 20: // backspace

if (displayMode != ERROR_MODE){

setDisplayString(getDisplayString().substring(0,

getDisplayString().length() - 1));

if (getDisplayString().length() < 1)

setDisplayString("0");

}

break;


case 21: // CE

clearExisting();

break;


case 22: // C

clearAll();

break;

}

}

}

}


void setDisplayString(String s){

jlbOutput.setText(s);

}


String getDisplayString (){

return jlbOutput.getText();

}


void addDigitToDisplay(int digit){

if (clearOnNextDigit)

setDisplayString("");


String inputString = getDisplayString();

if (inputString.indexOf("0") == 0){

inputString = inputString.substring(1);

}


if ((!inputString.equals("0") || digit > 0)  && inputString.length() < MAX_INPUT_LENGTH){

setDisplayString(inputString + digit);

}


displayMode = INPUT_MODE;

clearOnNextDigit = false;

}


void addDecimalPoint(){

displayMode = INPUT_MODE;


if (clearOnNextDigit)

setDisplayString("");


String inputString = getDisplayString();

// If the input string already contains a decimal point, don't

//  do anything to it.

if (inputString.indexOf(".") < 0)

setDisplayString(new String(inputString + "."));

}


void processSignChange(){

if (displayMode == INPUT_MODE)

{

String input = getDisplayString();


if (input.length() > 0 && !input.equals("0"))

{

if (input.indexOf("-") == 0)

setDisplayString(input.substring(1));


else

setDisplayString("-" + input);

}

}


else if (displayMode == RESULT_MODE)

{

double numberInDisplay = getNumberInDisplay();

if (numberInDisplay != 0)

displayResult(-numberInDisplay);

}

}


void clearAll() {

setDisplayString("0");

lastOperator = "0";

lastNumber = 0;

displayMode = INPUT_MODE;

clearOnNextDigit = true;

}


void clearExisting(){

setDisplayString("0");

clearOnNextDigit = true;

displayMode = INPUT_MODE;

}


double getNumberInDisplay() {

String input = jlbOutput.getText();

return Double.parseDouble(input);

}


void processOperator(String op) {

if (displayMode != ERROR_MODE)

{

double numberInDisplay = getNumberInDisplay();


if (!lastOperator.equals("0"))

{

try

{

double result = processLastOperator();

displayResult(result);

lastNumber = result;

}


catch (DivideByZeroException e)

{

}

}

else

{

lastNumber = numberInDisplay;

}

clearOnNextDigit = true;

lastOperator = op;

}

}


void processEquals(){

double result = 0;


if (displayMode != ERROR_MODE){

try

{

result = processLastOperator();

displayResult(result);

}

catch (DivideByZeroException e) {

displayError("Cannot divide by zero!");

}


lastOperator = "0";

}

}


double processLastOperator() throws DivideByZeroException {

double result = 0;

double numberInDisplay = getNumberInDisplay();


if (lastOperator.equals("/"))

{

if (numberInDisplay == 0)

throw (new DivideByZeroException());


result = lastNumber / numberInDisplay;

}

if (lastOperator.equals("*"))

result = lastNumber * numberInDisplay;


if (lastOperator.equals("-"))

result = lastNumber - numberInDisplay;


if (lastOperator.equals("+"))

result = lastNumber + numberInDisplay;


return result;

}


void displayResult(double result){

setDisplayString(Double.toString(result));

lastNumber = result;

displayMode = RESULT_MODE;

clearOnNextDigit = true;

}


void displayError(String errorMessage){

setDisplayString(errorMessage);

lastNumber = 0;

displayMode = ERROR_MODE;

clearOnNextDigit = true;

}


public static void main(String args[]) {

Calculator calci = new Calculator();

Container contentPane = calci.getContentPane();

// contentPane.setLayout(new BorderLayout());

calci.setTitle("Java Swing Calculator");

calci.setSize(241, 217);

calci.pack();

calci.setLocation(400, 250);

calci.setVisible(true);

calci.setResizable(false);

}

} //End of Swing Calculator Class.


class DivideByZeroException extends Exception{

public DivideByZeroException()

{

super();

}

public DivideByZeroException(String s)

{

super(s);

}

}


class CustomABOUTDialog extends JDialog implements ActionListener {

JButton jbnOk;


CustomABOUTDialog(JFrame parent, String title, boolean modal){

super(parent, title, modal);

setBackground(Color.black);

JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));


StringBuffer text = new StringBuffer();

text.append("Calculator Information\n\n");

text.append("Developer: Hemanth\n");

text.append("Version: 1.0");

JTextArea jtAreaAbout = new JTextArea(5, 21);

jtAreaAbout.setText(text.toString());

jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));

jtAreaAbout.setEditable(false);


p1.add(jtAreaAbout);

p1.setBackground(Color.red);

getContentPane().add(p1, BorderLayout.CENTER);


JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));

jbnOk = new JButton(" OK ");

jbnOk.addActionListener(this);


p2.add(jbnOk);

getContentPane().add(p2, BorderLayout.SOUTH);


setLocation(408, 270);

setResizable(false);


addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)

{

Window aboutDialog = e.getWindow();

aboutDialog.dispose();

}

}

);


pack();

}


public void actionPerformed(ActionEvent e)

{

if(e.getSource() == jbnOk) {

this.dispose();

}

}

}




JAVA - Circle Button

 



package circlebutton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JLabel;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;


public class GuiMain{


public static void main(String[] args){


JFrame frame = new JFrame("Circle Button Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JLabel circleLabel = new JLabel("Exciting circle button:");


CircleButton circleButton = new CircleButton("Click me!");

circleButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

System.out.println("Clicked!");

}

});


JLabel normalLabel = new JLabel("Boring square button:");

JButton normalButton = new JButton("Okay");


JPanel panel = new JPanel();

panel.add(circleLabel);

panel.add(circleButton);

panel.add(normalLabel);

panel.add(normalButton);

frame.add(panel);


frame.setSize(300, 150);

frame.setVisible(true);

}

}

=================================================

package circlebutton;
import javax.swing.JButton;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.awt.FontMetrics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class CircleButton extends JButton{

private boolean mouseOver = false;
private boolean mousePressed = false;

public CircleButton(String text){
super(text);
setOpaque(false);
setFocusPainted(false);
setBorderPainted(false);

MouseAdapter mouseListener = new MouseAdapter(){

@Override
public void mousePressed(MouseEvent me){
if(contains(me.getX(), me.getY())){
mousePressed = true;
repaint();
}
}

@Override
public void mouseReleased(MouseEvent me){
mousePressed = false;
repaint();
}

@Override
public void mouseExited(MouseEvent me){
mouseOver = false;
mousePressed = false;
repaint();
}

@Override
public void mouseMoved(MouseEvent me){
mouseOver = contains(me.getX(), me.getY());
repaint();
}
};

addMouseListener(mouseListener);
addMouseMotionListener(mouseListener);
}

private int getDiameter(){
int diameter = Math.min(getWidth(), getHeight());
return diameter;
}

@Override
public Dimension getPreferredSize(){
FontMetrics metrics = getGraphics().getFontMetrics(getFont());
int minDiameter = 10 + Math.max(metrics.stringWidth(getText()), metrics.getHeight());
return new Dimension(minDiameter, minDiameter);
}

@Override
public boolean contains(int x, int y){
int radius = getDiameter()/2;
return Point2D.distance(x, y, getWidth()/2, getHeight()/2) < radius;
}

@Override
public void paintComponent(Graphics g){

int diameter = getDiameter();
int radius = diameter/2;

if(mousePressed){
g.setColor(Color.LIGHT_GRAY);
}
else{
g.setColor(Color.WHITE);
}
g.fillOval(getWidth()/2 - radius, getHeight()/2 - radius, diameter, diameter);

if(mouseOver){
g.setColor(Color.BLUE);
}
else{
g.setColor(Color.BLACK);
}
g.drawOval(getWidth()/2 - radius, getHeight()/2 - radius, diameter, diameter);

g.setColor(Color.BLACK);
g.setFont(getFont());
FontMetrics metrics = g.getFontMetrics(getFont());
int stringWidth = metrics.stringWidth(getText());
int stringHeight = metrics.getHeight();
g.drawString(getText(), getWidth()/2 - stringWidth/2, getHeight()/2 + stringHeight/4);
}
}


===============================
comment
In the frame class:


       CircleButton JButtonMusic=new CircleButton("");
       //JButtonMusic.setContentAreaFilled(false);
       JButtonMusic.setFocusPainted(false);
       JButtonMusic.setBorderPainted(false);
       JButtonMusic.setSize(120,70);
       imageIcon2 = new ImageIcon(musicIcon); // load the image to a imageIcon
       
       image2 = imageIcon2.getImage(); // transform it 
       newimg2 = image2.getScaledInstance(30, 30,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
       imageIcon2 = new ImageIcon(newimg2);  // transform it back
       JButtonMusic.setIcon( imageIcon2); 

              
       JButtonMusic.setLocation(1050,710);
       
       add(JButtonMusic);

JAVA - Search Text

 





import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import java.util.List;


public class SimpleSearchEngineGUI extends JFrame {


    private JTextField searchField;

    private JList<String> resultList;

    private DefaultListModel<String> listModel;

    private List<String> dataStore; // Your data source


    public SimpleSearchEngineGUI() {

        setTitle("Simple Search Engine");

        setSize(400, 300);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setLayout(new BorderLayout());


        // Initialize data (replace with your actual data loading)

        dataStore = new ArrayList<>();

        dataStore.add("Apple is a fruit.");

        dataStore.add("Banana is a yellow fruit.");

        dataStore.add("Carrot is a vegetable.");

        dataStore.add("Another apple pie recipe.");


        // Search Panel

        JPanel searchPanel = new JPanel();

        searchField = new JTextField(20);

        JButton searchButton = new JButton("Search");

        searchPanel.add(searchField);

        searchPanel.add(searchButton);

        add(searchPanel, BorderLayout.NORTH);


        // Result List

        listModel = new DefaultListModel<>();

        resultList = new JList<>(listModel);

        JScrollPane scrollPane = new JScrollPane(resultList);

        add(scrollPane, BorderLayout.CENTER);


        // Event Listener

        searchButton.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                performSearch();

            }

        });

        searchField.addActionListener(new ActionListener() { // Allow Enter key to trigger search

            @Override

            public void actionPerformed(ActionEvent e) {

                performSearch();

            }

        });

    }


    private void performSearch() {

        String query = searchField.getText().toLowerCase();

        listModel.clear(); // Clear previous results


        if (query.isEmpty()) {

            // Optionally show all data or a message

            for (String item : dataStore) {

                listModel.addElement(item);

            }

            return;

        }


        for (String item : dataStore) {

            if (item.toLowerCase().contains(query)) {

                listModel.addElement(item);

            }

        }

    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override

            public void run() {

                new SimpleSearchEngineGUI().setVisible(true);

            }

        });

    }

}


JAVA - Calculator

 





package mainc;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


public class MainC implements ActionListener {

    private String number;

    private int num;

    private int num_index = 0;

    private int op_index = 0;

    private double[] nums = new double[100];

    private char[] operations = new char[100];

    private JLabel label;

    private JFrame frame;

    private JPanel panel;


    public MainC() {

        frame = new JFrame();

        // Create all buttons needed for the calculator

        JButton b1 = new JButton("1");

        b1.addActionListener(this);


        JButton b2 = new JButton("2");

        b2.addActionListener(this);

        JButton b3 = new JButton("3");

        b3.addActionListener(this);

        JButton b4 = new JButton("4");

        b4.addActionListener(this);

        JButton b5 = new JButton("5");

        b5.addActionListener(this);

        JButton b6 = new JButton("6");

        b6.addActionListener(this);

        JButton b7 = new JButton("7");

        b7.addActionListener(this);

        JButton b8 = new JButton("8");

        b8.addActionListener(this);

        JButton b9 = new JButton("9");

        b9.addActionListener(this);

        JButton b0 = new JButton("0");

        b0.addActionListener(this);

        JButton bp = new JButton("+");

        bp.addActionListener(this);

        JButton bm = new JButton("-");

        bm.addActionListener(this);

        JButton bmu = new JButton("*");

        bmu.addActionListener(this);

        JButton bd = new JButton("/");

        bd.addActionListener(this);

        JButton bc = new JButton("C");

        bc.addActionListener(this);

        JButton be = new JButton("=");

        be.addActionListener(this);



        // Label keeping track of user input

        label = new JLabel("0");

        // Create new JPanel with all buttons and the label

        panel = new JPanel();

        panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 200, 200));

        panel.setLayout(new GridLayout(3, 4));

        panel.add(label);

        panel.add(bc);

        panel.add(b1);

        panel.add(b2);

        panel.add(b3);

        panel.add(b4);

        panel.add(b5);

        panel.add(b6);

        panel.add(b7);

        panel.add(b8);

        panel.add(b9);

        panel.add(b0);

        panel.add(bp);

        panel.add(bm);

        panel.add(bmu);

        panel.add(bd);

        panel.add(be);


        frame.add(panel, BorderLayout.CENTER);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setTitle("Calculator");

        frame.pack();

        frame.setVisible(true);


    }


    public static void main(String[] args) {

        new MainC();

    }


    @Override

    public void actionPerformed(ActionEvent e) {

        JButton clicked = (JButton) e.getSource();

        String val = clicked.getText();

        char newval = val.charAt(0);

        // Handle Clearing and Entering Numbers


        // Clear

        if (val.equals("C")) {

            number = "";

            label.setText("0");

            num = 0;

            operations = new char[100];

            nums = new double[100];

            num_index = 0;

            op_index = 0;

        }

        // First number entered

        else if (label.getText().equals("0")) {

            number = val;

            label.setText(number);

            num = Integer.parseInt(clicked.getText());

        }

        // Any other number

        else if (newval != '+' && newval != '-' && newval != '*' && newval != '/' && newval != '=') {

            label.setText(label.getText() + val);

            number += val;

            num = Integer.parseInt(number);

        }

        // Handle Operations

        if (newval == '+') {


            label.setText(label.getText() + '+');

            number = "";

            nums[num_index] = num;

            num_index++;

            operations[op_index] = '+';

            op_index++;

            num = 0;

        } else if (newval == '-') {

            label.setText(label.getText() + '-');

            number = "";

            nums[num_index] = num;

            num_index++;

            operations[op_index] = '-';

            op_index++;

            num = 0;


        } else if (newval == '*') {

            label.setText(label.getText() + '*');

            number = "";

            nums[num_index] = num;

            num_index++;

            operations[op_index] = '*';

            op_index++;

            num = 0;


        } else if (newval == '/') {

            label.setText(label.getText() + '/');

            number = "";

            nums[num_index] = num;

            num_index++;

            operations[op_index] = '/';

            op_index++;

            num = 0;


        } else if (newval == '=') {

            nums[num_index] = num;

            num_index++;

            int nLength = nums.length;

            int oLength = operations.length;


            for (int i = 0; i < oLength; i++) {

                if (operations[i] == '*' || operations[i] == '/') {

                    double result = 0;

                    if (operations[i] == '*') {

                        result = nums[i] * nums[i + 1];

                    } else if (operations[i] == '/') {

                        if (nums[i + 1] == 0) {

                            label.setText("Division by zero is not allowed.");

                            return;

                        }

                        result = (double)nums[i] / nums[i + 1];

                    }


                    // Update arrays: replace nums[i] with the result, shift the rest left

                    nums[i] = result;

                    nums = shiftLeft(nums, i + 1);

                    operations = shiftLeft(operations, i);


                    // Adjust lengths

                    nLength--;

                    oLength--;


                    // Stay at the same index after shifting

                    i--;

                }

            }


            // Step 2: Handle Addition (+) and Subtraction (-)

            double result = nums[0];

            for (int i = 0; i < oLength; i++) {

                if (operations[i] == '+') {

                    result += nums[i + 1];

                } else if (operations[i] == '-') {

                    result -= nums[i + 1];

                }

            }



            label.setText("" + result);

            number = "";

            num = 0;

            operations = new char[100];

            nums = new double[100];

            num_index = 0;

            op_index = 0;

        }

    }

    // Helper method to shift elements in an int array to the left

    public static double[] shiftLeft(double[] arr, int startIndex) {

        double[] newArr = new double[arr.length - 1];

        for (int i = 0; i < startIndex; i++) {

            newArr[i] = arr[i];

        }

        for (int i = startIndex; i < newArr.length; i++) {

            newArr[i] = arr[i + 1];

        }

        return newArr;

    }


    // Helper method to shift elements in a char array to the left

    public static char[] shiftLeft(char[] arr, int startIndex) {

        char[] newArr = new char[arr.length - 1];

        for (int i = 0; i < startIndex; i++) {

            newArr[i] = arr[i];

        }

        for (int i = startIndex; i < newArr.length; i++) {

            newArr[i] = arr[i + 1];

        }

        return newArr;

    }


}

JAVAFX - Fractal Mandelbrot

 




package javafxmandelbrotset;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.canvas.Canvas;

import javafx.scene.canvas.CanvasBuilder;

import javafx.scene.canvas.GraphicsContext;

import javafx.scene.layout.Pane;

import javafx.scene.paint.Color;

import javafx.stage.Stage;

 

/**

 * Mandelbrot set with JavaFX.

 * @author hameister

 */

public class JavaFXMandelbrotSet extends Application {

    // Size of the canvas for the Mandelbrot set

    private static final int CANVAS_WIDTH = 740;

    private static final int CANVAS_HEIGHT = 605;

    // Left and right border

    private static final int X_OFFSET = 25;

    // Top and Bottom border

    private static final int Y_OFFSET = 25;

    // Values for the Mandelbro set

    private static double MANDELBROT_RE_MIN = -2;

    private static double MANDELBROT_RE_MAX = 1;

    private static double MANDELBROT_IM_MIN = -1.2;

    private static double MANDELBROT_IM_MAX = 1.2;

 

    @Override

    public void start(Stage primaryStage) {

        Pane fractalRootPane = new Pane();

        Canvas canvas = CanvasBuilder

                .create()

                .height(CANVAS_HEIGHT)

                .width(CANVAS_WIDTH)

                .layoutX(X_OFFSET)

                .layoutY(Y_OFFSET)

                .build();

 

        paintSet(canvas.getGraphicsContext2D(),

                MANDELBROT_RE_MIN,

                MANDELBROT_RE_MAX,

                MANDELBROT_IM_MIN,

                MANDELBROT_IM_MAX);

 

        fractalRootPane.getChildren().add(canvas);

 

        Scene scene = new Scene(fractalRootPane, CANVAS_WIDTH + 2 * X_OFFSET, CANVAS_HEIGHT + 2 * Y_OFFSET);

        scene.setFill(Color.BLACK);

        primaryStage.setTitle("Mandelbrot Set");

        primaryStage.setScene(scene);

        primaryStage.show();

    }

 

    private void paintSet(GraphicsContext ctx, double reMin, double reMax, double imMin, double imMax) {

        double precision = Math.max((reMax - reMin) / CANVAS_WIDTH, (imMax - imMin) / CANVAS_HEIGHT);

        int convergenceSteps = 50;

        for (double c = reMin, xR = 0; xR < CANVAS_WIDTH; c = c + precision, xR++) {

            for (double ci = imMin, yR = 0; yR < CANVAS_HEIGHT; ci = ci + precision, yR++) {

                double convergenceValue = checkConvergence(ci, c, convergenceSteps);

                double t1 = (double) convergenceValue / convergenceSteps;

                double c1 = Math.min(255 * 2 * t1, 255);

                double c2 = Math.max(255 * (2 * t1 - 1), 0);

 

                if (convergenceValue != convergenceSteps) {

                    ctx.setFill(Color.color(c2 / 255.0, c1 / 255.0, c2 / 255.0));

                } else {

                    ctx.setFill(Color.PURPLE); // Convergence Color

                }

                ctx.fillRect(xR, yR, 1, 1);

            }

        }

    }

 

    /**

     * Checks the convergence of a coordinate (c, ci) The convergence factor

     * determines the color of the point.

     */

    private int checkConvergence(double ci, double c, int convergenceSteps) {

        double z = 0;

        double zi = 0;

        for (int i = 0; i < convergenceSteps; i++) {

            double ziT = 2 * (z * zi);

            double zT = z * z - (zi * zi);

            z = zT + c;

            zi = ziT + ci;

 

            if (z * z + zi * zi >= 4.0) {

                return i;

            }

        }

        return convergenceSteps;

    }

 

    public static void main(String[] args) {

        launch(args);

    }

}


JAVA - Fractal JPanel

 






package fractalpael;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import javax.swing.JPanel;

import javax.swing.JFrame;


public class FractalPanel extends JPanel {

    final FractalSquare square = new FractalSquare(450, 350);


    public FractalPanel() {

        add(square);

    }


    public static void main(String[] args) {

        FractalPanel fractalPanel = new FractalPanel();

        JFrame frame = new JFrame();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(fractalPanel);

        frame.pack();

        frame.setVisible(true);


        Thread squareThread = new Thread(() -> {

            try {

                fractalPanel.square.render();

            } catch (InterruptedException e) {

                System.err.println("Interrupted");

            }

        });

        squareThread.start();

    }

}


class Fractal extends JComponent {

    final BufferedImage image;

    final Graphics2D offscreenGraphics;


    public Fractal(int width, int height) {

        setPreferredSize(new Dimension(width, height));

        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        offscreenGraphics = image.createGraphics();

    }


    // Copy the offscreen image to the main graphics context

    public void paint(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;

        synchronized (image) { // synchronize with the render thread

            g2.drawImage(image, 0, 0, null);

        }

    }

}


class FractalSquare extends Fractal {

    public FractalSquare(int width, int height) {

        super(width, height);

    }


    public void render() throws InterruptedException {

        drawSquares(getWidth() / 2, getHeight() / 2, 100, 7);

    }


    public void drawSquares(int x, int y, int side, int size) throws InterruptedException {


        // Sleep for 10ms between frames

        Thread.sleep(10);


        if (size > 2) {

            size--;


            synchronized (image) { // synchronize with the draw thread

                offscreenGraphics.setColor(Color.BLUE);

                System.out.printf("Filling [%d, %d, %d, %d]\n", x - side / 2, y - side / 2, side, side);

                offscreenGraphics.fillRect(x - side / 2, y - side / 2, side, side);

            }


            // Tell Swing that we've updated the image and it needs to be redrawn

            repaint();


            side = side / 2;

            x = x - side;

            y = y - side;

            drawSquares(x, y, side, size);

            drawSquares(x + side * 2, y, side, size);

            drawSquares(x, y + side * 2, side, size);

            drawSquares(x + side * 2, y + side * 2, side, size);

        }

    }

}



Minggu, 14 September 2025

JAVA - Traffic Light

 



File : GUIGen.java

package gui;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.Box;

import javax.swing.JButton;

import javax.swing.JFrame;

/**

*

* @author ajb

*/

public class GUIGen extends JFrame implements ActionListener{

    GenPanel panel = new GenPanel();

    JButton stop;

    JButton go;


    GUIGen(){

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(300,300);

        this.setLocationRelativeTo(null);


        Container vert = Box.createVerticalBox();

        Container hoz = Box.createHorizontalBox();

        stop = new JButton("Stop");

        go = new JButton(" Go ");

        stop.addActionListener(this);

        go.addActionListener(this);


        hoz.add(stop);

        hoz.add(go);

        vert.add(panel);

        vert.add(hoz);


        this.add(vert);

        this.setVisible(true);


    }


    /**

    * @param args the command line arguments

    */

    public static void main(String[] args) {

        // TODO code application logic here

        new GUIGen();

    }

    @Override

    public void actionPerformed(ActionEvent ae) {


        if(ae.getSource()==stop) {

            panel.setRed();

        }

        if(ae.getSource()==go) {

            panel.setGreen();

        }

        repaint();

    }

}

========================================



File : GenPanel,java

package gui;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import javax.swing.JPanel;

public class GenPanel extends JPanel {


    Color light = Color.RED;


    public void setRed() {

        light = Color.RED;

    }


    public void setGreen() {

        light = Color.GREEN;

    }


    @Override

    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;


        g2.setColor(Color.BLACK);

        g2.fillRect(100, 10, 100, 100);

        g2.setColor(light);

        g2.fillOval(100,10,100,100);

    }

}