import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.*; public class zyy { JFrame a1; JButton a2; JPanel a3; JTextField a4; String[] xiaosi= {"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"}; public zyy() { a1=new JFrame("计算机"); a3=new JPanel(new GridLayout(4,4,0,0)); a4=new JTextField(); a1.add(BorderLayout.NORTH,a4); a1.add(BorderLayout.CENTER,a3); for(int i=0;i<16;i++) { a2=new JButton(xiaosi[i]); a3.add(a2); } a1.setVisible(true); a1.setSize(400,200); } public static void main(String[] args) { new zyy(); } }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class zy implements ActionListener { JFrame a1; JButton a2,a22,a222; JPanel a3,a4; BorderLayout a5; public zy(){ a1=new JFrame(); a3=new JPanel(); a4=new JPanel(); new BorderLayout(); a1.add(BorderLayout.NORTH,a3); a1.add(BorderLayout.CENTER,a4); a2=new JButton("红色"); a2.addActionListener(this); a3.add(a2); a22=new JButton("绿色"); a22.addActionListener(this); a3.add(a22); a222=new JButton("蓝色"); a222.addActionListener(this); a3.add(a222); a1.setVisible(true); a1.setSize(400,300); } public static void main(String[] args){ new zy(); } public void actionPerformed(ActionEvent e){ JButton b=(JButton)e.getSource(); if(b==a2) { a4.setBackground(Color.RED); }else if(b==a22) { a4.setBackground(Color.GREEN); }else if(b==a222) { a4.setBackground(Color.BLUE); } } }