Monday, September 21, 2015

Calculater-like number inputer (can not calculate)

This calculater-like number inputer can not calculate but can display numbers which you enter. Maybe you can customize it to a better application. You need "Swing" to run this program.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Sample1 extends JFrame{
private static final long serialVersionUID = 1L;

JPanel contentPane = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JTextField result = new JTextField("");


 public static void main(String args[]){
 Sample1 frame = new Sample1("Practice window.");
 frame.setVisible(true);
 }

 Sample1(String title){
        contentPane.setLayout(borderLayout1);
 setContentPane(contentPane);
 setTitle(title);
 setSize(new Dimension(250, 300));
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 contentPane.add(result, BorderLayout.NORTH);

 JPanel keyPanel = new JPanel();
 keyPanel.setLayout(new GridLayout(4, 3));
 contentPane.add(keyPanel, BorderLayout.CENTER);

 keyPanel.add(new NumberButton("7"), 0);
 keyPanel.add(new NumberButton("8"), 1);
 keyPanel.add(new NumberButton("9"), 2);
 keyPanel.add(new NumberButton("4"), 3);
 keyPanel.add(new NumberButton("5"), 4);
 keyPanel.add(new NumberButton("6"), 5);
 keyPanel.add(new NumberButton("1"), 6);
 keyPanel.add(new NumberButton("2"), 7);
 keyPanel.add(new NumberButton("3"), 8);
 keyPanel.add(new NumberButton("0"), 9);
 keyPanel.add(new JButton("Calc"), 10);

 contentPane.add(new JButton("C"), BorderLayout.SOUTH);
 setVisible(true);
   }

    public void appendResult(String c) {
  result.setText(result.getText() + c);
   }

public class NumberButton extends JButton implements ActionListener {
  private static final long serialVersionUID = 1L;

  public NumberButton(String keyTop) {
   super(keyTop);
   this.addActionListener(this);
  }

  public void actionPerformed(ActionEvent evt) {
   String keyNumber = this.getText();
   appendResult(keyNumber);
  }
 }
}