import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class Main extends JFrame { JButton button1, button2, plus, enter; JTextField screen; ArrayList history; public Main(String title) throws HeadlessException { super(title); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(1920,1080); setLocationRelativeTo(null); setVisible(true); setLayout(new GridBagLayout()); setPreferredSize(new Dimension(500,500)); history = new ArrayList<>(); GridBagConstraints g = new GridBagConstraints(); g.fill = GridBagConstraints.HORIZONTAL; button1 = new JButton("1"); button2 = new JButton("2"); enter = new JButton("E"); plus = new JButton("+"); plus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { history.add(new History(Integer.parseInt(screen.getText()),Operation.PLUS)); screen.setText(""); } }); enter.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Operation operation = null; int result = 0, valueMem = 0; for (History historyItem: history){ operation = historyItem.operation; valueMem = historyItem.value; if (operation != null) { result = countByOperation(result, valueMem, historyItem.operation); } } if(valueMem != 0) { screen.setText(String.valueOf(countByOperation(result, Integer.parseInt(screen.getText()), operation))); history = new ArrayList<>(); } } }); screen = new JTextField(); fillButton(button1, "1"); fillButton(button2, "2"); g.gridx = 0; g.gridy = 0; g.gridwidth = 1; g.gridheight = 1; g.fill = GridBagConstraints.BOTH; add(button1, g); g.gridx = 1; add(button2, g); g.gridx = 2; add(plus, g); g.gridx = 3; add(enter, g); g.gridx = 0; g.gridy = 1; g.gridwidth = 4; add(screen, g); } private void fillButton(JButton button, String text) { button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { screen.setText(screen.getText() + text); } }); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new Main("Kalkulačka"); } }); } private int countByOperation(int valueA, int valueB, Operation operation) { switch (operation) { case PLUS -> { return valueA + valueB; } case MINUS -> { return valueA - valueB; } case MULTIPLE -> { return valueA * valueB; } case DIVISION -> { return valueA / valueB; } } return 0; } }