GUI per una calcolatrice (non fa i calcoli…)
import java.awt.*; import java.awt.event.*; public class Calcolatrice extends Frame implements ActionListener { Label lcd; Label modello; Button bRIGHT[]=new Button[8]; Button bLEFT []=new Button[16]; String lRIGHT[]={ "-", "C", "+", "CE", "->", "M", "<-", "MR" }; String lLEFT []={ "7", "8", "9", "/", "4", "5", "6", "X", "1", "2", "3", "%", "0", ".", "=", "+/-" }; public Calcolatrice() { this.setLayout(new GridLayout(2, 2, 10, 10)); // nord-ovest lcd=new Label("0", Label.RIGHT); lcd.setBackground(Color.lightGray); this.add(lcd); // nord-est modello=new Label("RDC 2006", Label.CENTER); modello.setBackground(Color.lightGray); this.add(modello); // sud-ovest Panel g4x4=new Panel(); g4x4.setLayout(new GridLayout(4, 4, 2, 2)); for(int i=0; i < 16; i++) { bLEFT[i]=new Button(lLEFT[i]); bLEFT[i].addActionListener(this); g4x4.add(bLEFT[i]); } this.add(g4x4); // sud-est Panel g4x2=new Panel(); g4x2.setLayout(new GridLayout(4, 2, 2, 2)); for(int i=0; i < 8; i++) { bRIGHT[i]=new Button(lRIGHT[i]); bRIGHT[i].addActionListener(this); g4x2.add(bRIGHT[i]); } this.add(g4x2); // globale this.setTitle("Calcolatrice"); this.pack(); this.setResizable(false); this.setVisible(true); } public void actionPerformed(ActionEvent ae) { String evento=ae.getActionCommand(); lcd.setText(evento); } public static void main(String args[]) { Calcolatrice c=new Calcolatrice(); } }
Osserva
Frame, setLayout, GridLayout, add, setTitle, pack, setVisible ActionListener, addActionListener, ActionEvent, getActionCommand