鏈接:程式設計工藝大師
程式代碼:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class calculator extends JFrame implements ActionListener{
public static void main(String[]args){
new calculator();
}
public calculator()
{
JFrame window=new JFrame("Calculator");
window.setDefaultLookAndFeelDecorated(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(3,3));
JPanel jplPanel = new JPanel();
jplPanel.setLayout(new GridLayout(3,3));
JButton button[]=new JButton[10];
for(int i=1;i<=9;i++)
{
button[i] = new JButton();
//button[i].setActionCommand(i);
button[i].addActionListener(this);
button[i].setSize(50,50);
button[i].setText(Integer.toString(i));
jplPanel.add(button[i]);
}
button[1].setActionCommand("1");
button[2].setActionCommand("2");
button[3].setActionCommand("3");
button[4].setActionCommand("4");
button[5].setActionCommand("5");
button[6].setActionCommand("6");
button[7].setActionCommand("7");
button[8].setActionCommand("8");
button[9].setActionCommand("9");
window.getContentPane().add(jplPanel, BorderLayout.CENTER);
window.setSize(500,500);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String cmd = e.getActionCommand();
if (cmd == "1"){
System.out.println(1);
}
if (cmd == "2"){
System.out.println(2);
}
if (cmd == "3"){
System.out.println(3);
}
if (cmd == "4"){
System.out.println(4);
}
if (cmd == "5"){
System.out.println(5);
}
if (cmd == "6"){
System.out.println(6);
}
if (cmd == "7"){
System.out.println(7);
}
if (cmd == "8"){
System.out.println(8);
}
if (cmd == "9"){
System.out.println(9);
}
}
}
沒有留言:
張貼留言