und das ganze als Java Swing-GUI
Code:
Sprache: Java
Zeilen: 83
Größe des Source in Byte: 2215
Größe der Binary in Byte: 2382
API: keine
Benötigt: ein paar Imports aus der javax.swing. und java.awt.
Compiler: Sun J2SDK 1.4.2
Kompiliert als: javac SwingCalc.java
Das Listing dazu:
Code:
/** import */
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
public class SwingCalc extends JFrame implements ActionListener
{
JTextField first, second;
JLabel result;
public SwingCalc(String s)
{
super(s);
/** inits */
this.getContentPane().setLayout(new GridLayout(1,2));
/** buttons */
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout(2,2));
JButton add = new JButton("+");
add.addActionListener(this);
JButton sub = new JButton("-");
sub.addActionListener(this);
JButton mult = new JButton("*");
mult.addActionListener(this);
JButton div = new JButton("/");
div .addActionListener(this);
buttons.add(add);
buttons.add(sub);
buttons.add(mult);
buttons.add(div);
/** input panel */
JPanel input = new JPanel();
input.setLayout(new GridLayout(5,1));
input.add(new JLabel("First number:"));
first = new JTextField();
input.add(first);
input.add(new JLabel("Second number:"));
second = new JTextField();
input.add(second);
result = new JLabel("Result");
input.add(result);
this.getContentPane().add(input);
this.getContentPane().add(buttons);
}
public static void main(String args[])
{
SwingCalc s = new SwingCalc("SwingCalc 1.0");
s.setSize(300,150);
s.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object o = e.getActionCommand();
float res = 0;
try
{
if(o.equals("+"))
res = Float.parseFloat(first.getText()) + Float.parseFloat(second.getText());
else if(o.equals("-"))
res = Float.parseFloat(first.getText()) - Float.parseFloat(second.getText());
else if(o.equals("*"))
res = Float.parseFloat(first.getText()) * Float.parseFloat(second.getText());
else if(o.equals("/"))
res = Float.parseFloat(first.getText()) / Float.parseFloat(second.getText());
result.setText("Result: " + res);
}
catch(Exception ex) { result.setText("Error calculating..."); }
}
}
Ein paar Anmerkungen:
Das ganze hat auch Exception Handling und fügt die benötigten Klassen einzeln hinzu, anstatt das gesamte Package... kostet aber auch nur ein paar Zeilen mehr.